以下是五子棋的C++实现代码:

#include using namespace std;

const int SIZE = 15; // 棋盘大小

enum ChessType { EMPTY, BLACK, WHITE }; // 棋子类型

class ChessBoard { private: ChessType board[SIZE][SIZE]; // 棋盘数组 public: ChessBoard() { // 初始化棋盘 for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { board[i][j] = EMPTY; } } } void print() { // 打印棋盘 cout << " "; for (int i = 0; i < SIZE; i++) { cout << " " << i + 1; } cout << endl; for (int i = 0; i < SIZE; i++) { cout << i + 1 << " "; for (int j = 0; j < SIZE; j++) { switch (board[i][j]) { case BLACK: cout << "X"; break; case WHITE: cout << "O"; break; default: cout << "."; break; } cout << " "; } cout << endl; } } bool put(ChessType type, int x, int y) { // 下棋,返回是否胜利 if (board[x][y] != EMPTY) { // 位置已有棋子 return false; } board[x][y] = type; // 放置棋子 return checkWin(type, x, y); // 检查是否胜利 } bool checkWin(ChessType type, int x, int y) { // 检查是否胜利 int count = 1; // 连续棋子数量 // 横向 for (int i = x - 1; i >= 0 && board[i][y] == type; i--) { // 左侧 count++; } for (int i = x + 1; i < SIZE && board[i][y] == type; i++) { // 右侧 count++; } if (count >= 5) { return true; } // 纵向 count = 1; for (int j = y - 1; j >= 0 && board[x][j] == type; j--) { // 上方 count++; } for (int j = y + 1; j < SIZE && board[x][j] == type; j++) { // 下方 count++; } if (count >= 5) { return true; } // 斜向(左上到右下) count = 1; for (int i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j] == type; i--, j--) { // 左上方 count++; } for (int i = x + 1, j = y + 1; i < SIZE && j < SIZE && board[i][j] == type; i++, j++) { // 右下方 count++; } if (count >= 5) { return true; } // 斜向(右上到左下) count = 1; for (int i = x - 1, j = y + 1; i >= 0 && j < SIZE && board[i][j] == type; i--, j++) { // 右上方 count++; } for (int i = x + 1, j = y - 1; i < SIZE && j >= 0 && board[i][j] == type; i++, j--) { // 左下方 count++; } if (count >= 5) { return true; } return false; } };

int main() { ChessBoard board; ChessType turn = BLACK; // 黑方先手 while (true) { board.print(); int x, y; cout << (turn == BLACK ? "Black" : "White") << "'s turn: "; cin >> x >> y; if (board.put(turn, x - 1, y - 1)) { // 下棋并检查是否胜利 board.print(); cout << (turn == BLACK ? "Black" : "White") << " wins!" << endl; break; } turn = turn == BLACK ? WHITE : BLACK; // 轮换下棋方 } return 0; }

给我写个五子棋的C++实现代码

原文地址: https://www.cveoy.top/t/topic/buJm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录