用c语言写一个五子棋小游戏
时间: 2024-05-14 17:18:52 浏览: 89
简易五子棋_小游戏五子棋_standard5l6_
好的,以下是用C语言实现的五子棋小游戏代码。
```c
#include <stdio.h>
#include <stdlib.h>
#define ROW 15
#define COL 15
char board[ROW][COL];
int player = 1;
void init_board() {
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
board[i][j] = '+';
}
}
}
void print_board() {
int i, j;
printf(" ");
for (i = 0; i < COL; i++) {
printf(" %2d", i + 1);
}
printf("\n");
for (i = 0; i < ROW; i++) {
printf("%2d", i + 1);
for (j = 0; j < COL; j++) {
printf(" %2c", board[i][j]);
}
printf("\n");
}
}
int check_win(int row, int col) {
char c = player == 1 ? 'O' : 'X';
int count = 0, i, j;
// 横向检查
for (i = col - 4; i <= col; i++) {
if (i < 0 || i + 4 >= COL) {
continue;
}
count = 0;
for (j = i; j <= i + 4; j++) {
if (board[row][j] == c) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
// 纵向检查
for (i = row - 4; i <= row; i++) {
if (i < 0 || i + 4 >= ROW) {
continue;
}
count = 0;
for (j = i; j <= i + 4; j++) {
if (board[j][col] == c) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
// 左上到右下斜向检查
for (i = row - 4, j = col - 4; i <= row && j <= col; i++, j++) {
if (i < 0 || i + 4 >= ROW || j < 0 || j + 4 >= COL) {
continue;
}
count = 0;
int k;
for (k = 0; k < 5; k++) {
if (board[i + k][j + k] == c) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
// 右上到左下斜向检查
for (i = row - 4, j = col + 4; i <= row && j >= col; i++, j--) {
if (i < 0 || i + 4 >= ROW || j < 0 || j - 4 >= COL) {
continue;
}
count = 0;
int k;
for (k = 0; k < 5; k++) {
if (board[i + k][j - k] == c) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
return 0;
}
int main() {
int row, col;
init_board();
print_board();
while (1) {
printf("Player %d's turn:\n", player);
printf("Row: ");
scanf("%d", &row);
printf("Col: ");
scanf("%d", &col);
if (board[row - 1][col - 1] != '+') {
printf("Invalid move, please try again.\n");
continue;
}
board[row - 1][col - 1] = player == 1 ? 'O' : 'X';
print_board();
if (check_win(row - 1, col - 1)) {
printf("Player %d wins!\n", player);
break;
}
player = player == 1 ? 2 : 1;
}
return 0;
}
```
该代码实现了一个基本的五子棋小游戏,玩家可以在控制台输入行和列坐标下棋,并且可以检查胜利条件。该代码中使用了一个二维字符数组来表示棋盘,初始化时将所有元素设置为加号,表示棋盘为空。玩家下棋时,程序会检查该位置是否为空,如果不为空,则提示玩家重新输入。每次下棋后,程序会检查是否有一方获胜,如果有则结束游戏并宣布胜利者。
阅读全文