c++怎么写井字棋游戏
时间: 2023-07-23 11:14:10 浏览: 104
井字棋c++一个
4星 · 用户满意度95%
以下是一个简单的 C++ 代码示例,用于实现井字棋游戏:
```c++
#include <iostream>
using namespace std;
char board[3][3] = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};
char player = 'X';
void drawBoard() {
cout << " 1 2 3" << endl;
for (int i = 0; i < 3; i++) {
cout << i + 1 << " ";
for (int j = 0; j < 3; j++) {
cout << board[i][j];
if (j < 2) {
cout << "|";
}
}
cout << endl;
if (i < 2) {
cout << " -----" << endl;
}
}
}
bool isValidMove(int row, int col) {
if (row < 0 || row > 2 || col < 0 || col > 2) {
return false;
}
if (board[row][col] != ' ') {
return false;
}
return true;
}
bool hasWon(char player) {
for (int i = 0; i < 3; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return true;
}
if (board[0][i] == player && board[1][i] == player && board[2][i] == player) {
return true;
}
}
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) {
return true;
}
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
return true;
}
return false;
}
int main() {
int row, col;
while (true) {
drawBoard();
cout << "Player " << player << " turn. Enter row and column: ";
cin >> row >> col;
if (isValidMove(row - 1, col - 1)) {
board[row - 1][col - 1] = player;
if (hasWon(player)) {
cout << "Player " << player << " has won!" << endl;
drawBoard();
break;
}
if (player == 'X') {
player = 'O';
} else {
player = 'X';
}
} else {
cout << "Invalid move. Try again." << endl;
}
}
return 0;
}
```
代码中的 `board` 数组表示井字棋盘,`player` 变量表示当前玩家。`drawBoard` 函数用于绘制井字棋盘,`isValidMove` 函数用于验证玩家的落子是否合法,`hasWon` 函数用于判断玩家是否获胜。主函数中通过循环实现玩家轮流落子,直到有一方获胜为止。
阅读全文