下面是一個(gè)簡(jiǎn)單的C++實(shí)現(xiàn)五子棋的示例代碼:
#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: 實(shí)現(xiàn)判斷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)位置
// 繼續(xù)下棋...
return 0;
}
上述代碼演示了一個(gè)簡(jiǎn)單的五子棋游戲,主要實(shí)現(xiàn)了棋盤的打印、下棋和判斷勝利等功能。在play
方法中,通過傳入玩家的行列坐標(biāo)和玩家類型,即可在指定位置下對(duì)應(yīng)的棋子,并判斷勝負(fù)。實(shí)際運(yùn)行時(shí),玩家可以交替在棋盤上下棋,直到有一方獲勝或平局為止。