一个代码梦到童年小游戏c++示例代码
时间: 2024-07-20 08:01:18 浏览: 51
当然可以。让我们来看一个简单的C++代码示例,模拟一个经典的童年游戏——"井字棋"(Tic Tac Toe),也称为“X's and O's”。这个程序实现了两个玩家轮流在3x3网格上放置他们的标记的游戏。
```cpp
#include <iostream>
#include <vector>
// 代表游戏板的状态
enum class BoardState {
Empty,
PlayerOne,
PlayerTwo
};
// 井字棋类
class TicTacToe {
private:
std::vector<BoardState> board; // 3x3的游戏板
public:
void print_board() const {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
char symbol;
switch (board[i * 3 + j]) {
case BoardState.Empty:
symbol = ' ';
break;
case BoardState.PlayerOne:
symbol = 'X';
break;
case BoardState.PlayerTwo:
symbol = 'O';
break;
}
std::cout << symbol << " ";
}
std::cout << "\n";
}
}
bool make_move(int row, int col, char player) {
if (row < 0 || row >= 3 || col < 0 || col >= 3 || board[row * 3 + col] != BoardState.Empty) {
return false;
}
board[row * 3 + col] = static_cast<BoardState>(player);
return true;
}
// 其他方法...
};
int main() {
TicTacToe game;
game.print_board();
while (!game.is_game_over()) { // 游戏结束条件...
int row, col;
std::cout << "Player X's turn, enter row and column: ";
std::cin >> row >> col;
game.make_move(row - 1, col - 1, 'X'); // 减一是因为索引从0开始
game.print_board();
// 判断并切换玩家...
}
return 0;
}
```
阅读全文