阅读量:0
下面是一个简单的C++实现五子棋的示例代码:
#include <iostream> #include <vector> const int BOARD_SIZE = 15; enum class Player { None, Black, White }; class FiveChess { private: std::vector<std::vector<Player>> board; public: FiveChess() : board(BOARD_SIZE, std::vector<Player>(BOARD_SIZE, Player::None)) {} void printBoard() { for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { switch (board[i][j]) { case Player::None: std::cout << "."; break; case Player::Black: std::cout << "X"; break; case Player::White: std::cout << "O"; break; } std::cout << " "; } std::cout << std::endl; } } bool checkWin(Player player) { // TODO: 实现判断player是否获胜的逻辑 return false; } void play(int row, int col, Player player) { board[row][col] = player; printBoard(); if (checkWin(player)) { std::cout << (player == Player::Black ? "Black" : "White") << " wins!" << std::endl; } } }; int main() { FiveChess game; game.play(7, 7, Player::Black); // 黑棋下在(7, 7)位置 game.play(8, 8, Player::White); // 白棋下在(8, 8)位置 // 继续下棋... return 0; }
上述代码演示了一个简单的五子棋游戏,主要实现了棋盘的打印、下棋和判断胜利等功能。在play
方法中,通过传入玩家的行列坐标和玩家类型,即可在指定位置下对应的棋子,并判断胜负。实际运行时,玩家可以交替在棋盘上下棋,直到有一方获胜或平局为止。