c++简易井字棋小游戏
时间: 2023-07-01 15:22:20 浏览: 142
简单的井字棋游戏使用C++源代码.zip
好的,以下是一个简易的C++井字棋小游戏代码,供你参考:
```
#include <iostream>
using namespace std;
char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
char player = 'X';
void draw_board() {
cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl;
cout << " -----------" << endl;
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl;
cout << " -----------" << endl;
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
}
bool check_win() {
for (int i = 0; i < 3; i++) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
return true;
if (board[0][i] == board[1][i] && board[1][i] == board[2][i])
return true;
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
return true;
if (board[0][2] == board[1][1] && board[1][1] == board[2][0])
return true;
return false;
}
int main() {
int choice;
cout << "Welcome to Tic-Tac-Toe!" << endl;
draw_board();
while (true) {
cout << "Player " << player << ", please enter your choice: ";
cin >> choice;
int row = (choice - 1) / 3;
int col = (choice - 1) % 3;
if (board[row][col] == 'X' || board[row][col] == 'O') {
cout << "Invalid move! Please try again." << endl;
continue;
}
board[row][col] = player;
draw_board();
if (check_win()) {
cout << "Player " << player << " wins!" << endl;
break;
}
if (player == 'X')
player = 'O';
else
player = 'X';
}
return 0;
}
```
这个代码实现了一个简单的C++井字棋小游戏。在游戏开始时,程序会打印出一个3x3的棋盘。玩家可以轮流输入数字来选择位置,程序会在棋盘上添加“X”或“O”。如果某个玩家连成了一条直线,程序会宣布其获胜。如果棋盘填满了但没有玩家获胜,程序会宣布平局。
阅读全文