用c++写一个三连棋
以下是一个使用C++编写的简单三连棋游戏:
#include <iostream>
#include <vector>
using namespace std;
// 游戏面板大小
const int BOARD_SIZE = 3;
// 游戏状态
enum class GameState {
PLAYING,
DRAW,
WIN_X,
WIN_O
};
// 游戏类
class TicTacToe {
public:
TicTacToe() {
board.resize(BOARD_SIZE, vector<char>(BOARD_SIZE, ' '));
currentPlayer = 'X';
gameState = GameState::PLAYING;
}
// 打印游戏面板
void printBoard() {
for (int i = 0; i < BOARD_SIZE; ++i) {
for (int j = 0; j < BOARD_SIZE; ++j) {
cout << board[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
// 玩家进行移动
void makeMove(int row, int col) {
if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && board[row][col] == ' ') {
board[row][col] = currentPlayer;
checkGameState(row, col);
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}
// 获取游戏状态
GameState getGameState() const {
return gameState;
}
private:
vector<vector<char>> board;
char currentPlayer;
GameState gameState;
// 检查游戏状态
void checkGameState(int row, int col) {
// 检查行
if (board[row][0] == board[row][1] && board[row][1] == board[row][2]) {
if (board[row][0] == 'X') {
gameState = GameState::WIN_X;
} else if (board[row][0] == 'O') {
gameState = GameState::WIN_O;
}
return;
}
// 检查列
if (board[0][col] == board[1][col] && board[1][col] == board[2][col]) {
if (board[0][col] == 'X') {
gameState = GameState::WIN_X;
} else if (board[0][col] == 'O') {
gameState = GameState::WIN_O;
}
return;
}
// 检查对角线
if ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) ||
(board[0][2] == board[1][1] && board[1][1] == board[2][0])) {
if (board[1][1] == 'X') {
gameState = GameState::WIN_X;
} else if (board[1][1] == 'O') {
gameState = GameState::WIN_O;
}
return;
}
// 检查平局
bool isDraw = true;
for (int i = 0; i < BOARD_SIZE; ++i) {
for (int j = 0; j < BOARD_SIZE; ++j) {
if (board[i][j] == ' ') {
isDraw = false;
break;
}
}
}
if (isDraw) {
gameState = GameState::DRAW;
}
}
};
int main() {
TicTacToe game;
while (game.getGameState() == GameState::PLAYING) {
game.printBoard();
int row, col;
cout << "Player " << game.getCurrentPlayer() << ", enter your move (row and column): ";
cin >> row >> col;
game.makeMove(row, col);
}
game.printBoard();
GameState gameState = game.getGameState();
if (gameState == GameState::WIN_X) {
cout << "Player X wins!" << endl;
} else if (gameState == GameState::WIN_O) {
cout << "Player O wins!" << endl;
} else if (gameState == GameState::DRAW) {
cout << "It's a draw!" << endl;
}
return 0;
}
这是一个简单的命令行游戏,玩家可以输入行和列来进行移动。游戏通过检查行、列和对角线来判断是否有玩家获胜,如果棋盘已满且没有玩家获胜,则判定为平局。游戏结束后,将显示相应的胜者或平局信息
原文地址: https://www.cveoy.top/t/topic/hZ2b 著作权归作者所有。请勿转载和采集!