c++五子棋代码
时间: 2023-07-09 22:19:02 浏览: 21
以下是一个简单的 C++ 五子棋代码示例:
```c++
#include <iostream>
using namespace std;
const int BOARD_SIZE = 15;
const int EMPTY = 0;
const int BLACK = 1;
const int WHITE = 2;
int board[BOARD_SIZE][BOARD_SIZE];
void init_board() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY;
}
}
}
void print_board() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY) {
cout << "+ ";
} else if (board[i][j] == BLACK) {
cout << "x ";
} else if (board[i][j] == WHITE) {
cout << "o ";
}
}
cout << endl;
}
}
bool check_win(int player) {
// 检查横向
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j <= BOARD_SIZE - 5; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[i][j + k] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
// 检查纵向
for (int i = 0; i <= BOARD_SIZE - 5; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[i + k][j] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
// 检查左上到右下斜线
for (int i = 0; i <= BOARD_SIZE - 5; i++) {
for (int j = 0; j <= BOARD_SIZE - 5; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[i + k][j + k] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
// 检查左下到右上斜线
for (int i = 4; i < BOARD_SIZE; i++) {
for (int j = 0; j <= BOARD_SIZE - 5; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[i - k][j + k] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
return false;
}
int main() {
init_board();
int player = BLACK;
while (true) {
print_board();
int x, y;
cout << "Player " << player << " enter your move (x y): ";
cin >> x >> y;
if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) {
cout << "Invalid move!" << endl;
continue;
}
if (board[x][y] != EMPTY) {
cout << "Invalid move!" << endl;
continue;
}
board[x][y] = player;
if (check_win(player)) {
cout << "Player " << player << " wins!" << endl;
break;
}
player = 3 - player; // 切换玩家
}
print_board();
return 0;
}
```
这个代码实现了:
1. 初始化棋盘
2. 打印棋盘
3. 检查是否获胜
4. 循环交替让两个玩家下棋,直到有人获胜
阅读全文