写一个C++的五子棋程序
时间: 2024-05-10 09:18:44 浏览: 74
以下是一个简单的命令行五子棋程序,使用 C++ 编写:
```cpp
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
const int BOARD_SIZE = 15;
const char EMPTY = ' ';
const char BLACK = 'X';
const char WHITE = 'O';
class Board {
public:
Board() {
for (int i = 0; i < BOARD_SIZE; i++) {
vector<char> row(BOARD_SIZE, EMPTY);
board.push_back(row);
}
}
void display() const {
cout << " ";
for (int i = 0; i < BOARD_SIZE; i++) {
cout << i << " ";
}
cout << endl;
for (int i = 0; i < BOARD_SIZE; i++) {
cout << i << " ";
for (int j = 0; j < BOARD_SIZE; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
bool is_valid_move(int x, int y) const {
return x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE && board[x][y] == EMPTY;
}
bool make_move(int x, int y, char player) {
if (!is_valid_move(x, y)) {
return false;
}
board[x][y] = player;
return true;
}
bool has_five_in_a_row(int x, int y) const {
char player = board[x][y];
int count;
// check horizontal
count = 1;
for (int i = y - 1; i >= 0 && board[x][i] == player; i--) {
count++;
}
for (int i = y + 1; i < BOARD_SIZE && board[x][i] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// check vertical
count = 1;
for (int i = x - 1; i >= 0 && board[i][y] == player; i--) {
count++;
}
for (int i = x + 1; i < BOARD_SIZE && board[i][y] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// check diagonal
count = 1;
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j] == player; i--, j--) {
count++;
}
for (int i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == player; i++, j++) {
count++;
}
if (count >= 5) {
return true;
}
// check anti-diagonal
count = 1;
for (int i = x - 1, j = y + 1; i >= 0 && j < BOARD_SIZE && board[i][j] == player; i--, j++) {
count++;
}
for (int i = x + 1, j = y - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == player; i++, j--) {
count++;
}
if (count >= 5) {
return true;
}
return false;
}
private:
vector<vector<char>> board;
};
int main() {
Board board;
char current_player = BLACK;
while (true) {
board.display();
cout << "Current player: " << current_player << endl;
int x, y;
while (true) {
cout << "Enter x and y coordinates (0-14): ";
cin >> x >> y;
if (board.is_valid_move(x, y)) {
break;
}
cout << "Invalid move. Please try again." << endl;
}
if (!board.make_move(x, y, current_player)) {
cout << "Invalid move. Please try again." << endl;
continue;
}
if (board.has_five_in_a_row(x, y)) {
cout << "Player " << current_player << " wins!" << endl;
break;
}
current_player = (current_player == BLACK) ? WHITE : BLACK;
}
return 0;
}
```
该程序使用了一个 `Board` 类来表示五子棋棋盘,并实现了以下方法:
- `display()`:打印当前棋盘状态。
- `is_valid_move()`:判断一个坐标是否为有效的落子位置。
- `make_move()`:在指定坐标上落子,并返回落子是否成功。
- `has_five_in_a_row()`:判断指定坐标是否连成了五子。
主函数循环接受玩家输入并执行落子和判断胜利的逻辑,直到有一方玩家胜利。
阅读全文