c++九宫格棋小游戏
时间: 2023-06-29 14:12:22 浏览: 119
好的,以下是一份简单的 C++ 九宫格棋小游戏代码,希望能对你有所帮助。代码中使用了二维数组来表示棋盘,玩家可以通过输入坐标来在棋盘上下棋,程序会判断胜负并输出结果。
```c++
#include <iostream>
using namespace std;
const int ROW = 3; // 行数
const int COL = 3; // 列数
char board[ROW][COL]; // 棋盘
void initBoard() {
// 初始化棋盘
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
board[i][j] = ' ';
}
}
}
void printBoard() {
// 打印棋盘
cout << " 1 2 3" << endl;
for (int i = 0; i < ROW; i++) {
cout << i + 1 << " ";
for (int j = 0; j < COL; j++) {
cout << "[" << board[i][j] << "]";
}
cout << endl;
}
}
bool checkWin(char player) {
// 判断胜负
for (int i = 0; i < ROW; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return true;
}
}
for (int j = 0; j < COL; j++) {
if (board[0][j] == player && board[1][j] == player && board[2][j] == 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() {
initBoard(); // 初始化棋盘
char player = 'X'; // 玩家先下 X
int row, col;
while (true) {
printBoard(); // 打印棋盘
cout << "请玩家 " << player << " 下棋,输入坐标(如:1 2):" << endl;
cin >> row >> col;
if (row < 1 || row > 3 || col < 1 || col > 3) {
cout << "坐标不合法,请重新输入!" << endl;
continue;
}
if (board[row - 1][col - 1] != ' ') {
cout << "该位置已有棋子,请重新输入!" << endl;
continue;
}
board[row - 1][col - 1] = player; // 下棋
if (checkWin(player)) {
printBoard(); // 打印最后一步棋盘
cout << "恭喜玩家 " << player << " 获胜!" << endl;
break;
}
if (player == 'X') {
player = 'O'; // 轮到 O 下棋
} else {
player = 'X'; // 轮到 X 下棋
}
}
return 0;
}
```
以上是一份简单的 C++ 九宫格棋小游戏代码,该代码并不完整,您可以根据自己的需求进行修改和完善。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)