C++ 人机下棋游戏:3x3 棋盘,实现行、列、对角线获胜
下面是一个简单的 C++ 代码示例,实现了人机下棋的功能:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
class Board {
private:
vector<vector<char>> grid;
char userSymbol;
char computerSymbol;
bool userTurn;
int size;
public:
Board(int boardSize) {
size = boardSize;
grid.resize(size, vector<char>(size, '*'));
userTurn = true;
}
void setUserSymbol(char symbol) {
userSymbol = symbol;
computerSymbol = (symbol == 'X') ? 'O' : 'X';
}
void drawBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cout << grid[i][j] << ' ';
}
cout << endl;
}
}
bool isGameOver() {
// Check rows
for (int i = 0; i < size; i++) {
if (grid[i][0] != '*' && grid[i][0] == grid[i][1] && grid[i][1] == grid[i][2]) {
return true;
}
}
// Check columns
for (int j = 0; j < size; j++) {
if (grid[0][j] != '*' && grid[0][j] == grid[1][j] && grid[1][j] == grid[2][j]) {
return true;
}
}
// Check diagonals
if (grid[0][0] != '*' && grid[0][0] == grid[1][1] && grid[1][1] == grid[2][2]) {
return true;
}
if (grid[0][2] != '*' && grid[0][2] == grid[1][1] && grid[1][1] == grid[2][0]) {
return true;
}
// Check for tie
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (grid[i][j] == '*') {
return false;
}
}
}
return true;
}
bool makeMove(int row, int col) {
if (row < 0 || row >= size || col < 0 || col >= size || grid[row][col] != '*') {
return false;
}
if (userTurn) {
grid[row][col] = userSymbol;
} else {
grid[row][col] = computerSymbol;
}
userTurn = !userTurn;
return true;
}
void computerMove() {
// Generate a random move for the computer
srand(time(NULL));
while (true) {
int row = rand() % size;
int col = rand() % size;
if (grid[row][col] == '*') {
grid[row][col] = computerSymbol;
userTurn = !userTurn;
break;
}
}
}
};
int main() {
int boardSize;
cout << "Enter the size of the board: ";
cin >> boardSize;
Board board(boardSize);
char userSymbol;
cout << "Choose your symbol (X/O): ";
cin >> userSymbol;
board.setUserSymbol(userSymbol);
int turn;
cout << "Choose your turn (1 - First, 2 - Second): ";
cin >> turn;
if (turn == 2) {
board.computerMove();
}
while (!board.isGameOver()) {
board.drawBoard();
int row, col;
cout << "Enter your move (row col): ";
cin >> row >> col;
if (!board.makeMove(row, col)) {
cout << "Invalid move! Try again." << endl;
continue;
}
if (!board.isGameOver()) {
board.computerMove();
}
}
board.drawBoard();
cout << "Game over!" << endl;
return 0;
}
这个代码创建了一个名为Board的类,表示棋盘。它包含了一个二维字符向量来存储棋盘状态。用户可以选择棋盘的大小和自己的棋子符号。游戏通过交替进行用户和计算机的移动来进行。计算机的移动是随机生成的。游戏在每个移动后检查是否有玩家获胜或平局。如果游戏结束,它将显示最终的棋盘状态和游戏结束的消息。
原文地址: https://www.cveoy.top/t/topic/qp5S 著作权归作者所有。请勿转载和采集!