请用c语言写出五子棋游戏代码。
时间: 2024-01-18 22:01:58 浏览: 73
好的,以下是基于 C 语言的五子棋游戏代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROWS 15
#define COLS 15
char board[ROWS][COLS]; // 二维数组表示棋盘
void init_board() // 初始化棋盘
{
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = '+';
}
}
}
void print_board() // 打印棋盘
{
int i, j;
printf(" ");
for (i = 0; i < COLS; i++) {
printf("%2d", i + 1);
}
printf("\n");
for (i = 0; i < ROWS; i++) {
printf("%2d", i + 1);
for (j = 0; j < COLS; j++) {
printf("%2c", board[i][j]);
}
printf("\n");
}
}
int check_win(int row, int col, char ch) // 判断胜负
{
int i, j, count;
// 检查横向
count = 0;
for (i = col - 4; i <= col; i++) {
if (i < 0 || i + 4 >= COLS) continue;
count = 0;
for (j = i; j <= i + 4; j++) {
if (board[row][j] == ch) count++;
}
if (count == 5) return 1;
}
// 检查纵向
count = 0;
for (i = row - 4; i <= row; i++) {
if (i < 0 || i + 4 >= ROWS) continue;
count = 0;
for (j = i; j <= i + 4; j++) {
if (board[j][col] == ch) count++;
}
if (count == 5) return 1;
}
// 检查左上到右下的斜线
count = 0;
for (i = row - 4, j = col - 4; i <= row && j <= col; i++, j++) {
if (i < 0 || j < 0 || i + 4 >= ROWS || j + 4 >= COLS) continue;
count = 0;
for (int k = 0; k < 5; k++) {
if (board[i + k][j + k] == ch) count++;
}
if (count == 5) return 1;
}
// 检查左下到右上的斜线
count = 0;
for (i = row + 4, j = col - 4; i >= row && j <= col; i--, j++) {
if (i >= ROWS || j < 0 || i - 4 < 0 || j + 4 >= COLS) continue;
count = 0;
for (int k = 0; k < 5; k++) {
if (board[i - k][j + k] == ch) count++;
}
if (count == 5) return 1;
}
return 0;
}
int main()
{
int row, col, turn = 1;
char ch;
init_board();
while (1) {
print_board();
ch = (turn % 2 == 1) ? 'X' : 'O';
printf("Player %c's turn:\n", ch);
printf("Enter row and col (e.g. 3 4): ");
scanf("%d %d", &row, &col);
if (row < 1 || row > ROWS || col < 1 || col > COLS) {
printf("Invalid input!\n");
continue;
}
if (board[row - 1][col - 1] != '+') {
printf("This position has been taken!\n");
continue;
}
board[row - 1][col - 1] = ch;
if (check_win(row - 1, col - 1, ch)) {
print_board();
printf("Player %c wins!\n", ch);
break;
}
turn++;
}
return 0;
}
```
这是一个简单的五子棋游戏实现,包括棋盘的初始化、打印、玩家输入、胜负判断等功能。
阅读全文