用c++写一个下五子棋的代码
时间: 2024-05-20 22:18:20 浏览: 57
好的,下面是一个简单的下五子棋的 C 代码:
#include <stdio.h>
#include <stdlib.h>
#define ROW 15
#define COL 15
#define BLACK 1
#define WHITE 2
#define EMPTY 0
int chessboard[ROW][COL]; // 棋盘
int player = BLACK; // 当前玩家
void init_chessboard() { // 初始化棋盘
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
chessboard[i][j] = EMPTY;
}
}
}
void print_chessboard() { // 打印棋盘
int i, j;
printf(" ");
for (i = 0; i < COL; i++) {
printf("%d ", i + 1);
}
printf("\n");
for (i = 0; i < ROW; i++) {
printf("%d ", i + 1);
for (j = 0; j < COL; j++) {
if (chessboard[i][j] == EMPTY) {
printf("+ ");
} else if (chessboard[i][j] == BLACK) {
printf("● ");
} else if (chessboard[i][j] == WHITE) {
printf("○ ");
}
}
printf("%d", i + 1);
printf("\n");
}
printf(" ");
for (i = 0; i < COL; i++) {
printf("%d ", i + 1);
}
printf("\n");
}
int check_win(int row, int col) { // 判断胜负
int i, j, k, count;
int directions[4][2] = {{1, 0}, {0, 1}, {1, 1}, {1, -1}};
for (i = 0; i < 4; i++) {
count = 1;
for (j = 1; j < 5; j++) {
if (row + j * directions[i][0] >= 0 && row + j * directions[i][0] < ROW &&
col + j * directions[i][1] >= 0 && col + j * directions[i][1] < COL &&
chessboard[row + j * directions[i][0]][col + j * directions[i][1]] == player) {
count++;
} else {
break;
}
}
for (k = 1; k < 5; k++) {
if (row - k * directions[i][0] >= 0 && row - k * directions[i][0] < ROW &&
col - k * directions[i][1] >= 0 && col - k * directions[i][1] < COL &&
chessboard[row - k * directions[i][0]][col - k * directions[i][1]] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return 1;
}
}
return 0;
}
void play() { // 下棋
int row, col;
printf("请玩家 %d 下棋:", player);
scanf("%d%d", &row, &col);
if (row >= 1 && row <= ROW && col >= 1 && col <= COL && chessboard[row - 1][col - 1] == EMPTY) {
chessboard[row - 1][col - 1] = player;
if (check_win(row - 1, col - 1)) {
printf("玩家 %d 获胜!\n", player);
exit(0);
}
player = player == BLACK ? WHITE : BLACK;
} else {
printf("输入有误,请重新输入!\n");
}
}
int main() {
init_chessboard();
while (1) {
print_chessboard();
play();
}
return 0;
}
希望对您有帮助!
阅读全文