下面是一個簡單的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
方法中,通過傳入玩家的行列坐標和玩家類型,即可在指定位置下對應的棋子,并判斷勝負。實際運行時,玩家可以交替在棋盤上下棋,直到有一方獲勝或平局為止。