用c++写一个五子棋项目
时间: 2024-05-15 16:20:05 浏览: 99
好的,以下是一个简单的五子棋项目的C代码:
```
#include <stdio.h>
#include <stdbool.h>
#define ROWS 15
#define COLS 15
char board[ROWS][COLS];
void initialize_board() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = '-';
}
}
}
void print_board() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
bool is_valid_move(int row, int col) {
if (row >= 0 && row < ROWS && col >= 0 && col < COLS && board[row][col] == '-') {
return true;
} else {
return false;
}
}
bool is_win(char symbol) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (board[i][j] == symbol) {
if (i + 4 < ROWS && board[i+1][j] == symbol && board[i+2][j] == symbol && board[i+3][j] == symbol && board[i+4][j] == symbol) {
return true;
}
if (j + 4 < COLS && board[i][j+1] == symbol && board[i][j+2] == symbol && board[i][j+3] == symbol && board[i][j+4] == symbol) {
return true;
}
if (i + 4 < ROWS && j + 4 < COLS && board[i+1][j+1] == symbol && board[i+2][j+2] == symbol && board[i+3][j+3] == symbol && board[i+4][j+4] == symbol) {
return true;
}
if (i + 4 < ROWS && j - 4 >= 0 && board[i+1][j-1] == symbol && board[i+2][j-2] == symbol && board[i+3][j-3] == symbol && board[i+4][j-4] == symbol) {
return true;
}
}
}
}
return false;
}
int main() {
initialize_board();
print_board();
char player1 = 'X';
char player2 = 'O';
char current_player = player1;
int row, col;
while (true) {
printf("Current player: %c\n", current_player);
printf("Enter row and column numbers (e.g. 3 4): ");
scanf("%d %d", &row, &col);
if (!is_valid_move(row, col)) {
printf("Invalid move!\n");
continue;
}
board[row][col] = current_player;
print_board();
if (is_win(current_player)) {
printf("Player %c wins!\n", current_player);
break;
}
if (current_player == player1) {
current_player = player2;
} else {
current_player = player1;
}
}
return 0;
}
```
这个程序实现一个简单的五子棋游戏,实现了下棋、判断是否胜利、交替下棋等功能。您可以按照自己的需求进行修改和扩展。
阅读全文