用C语言编写五子棋游戏,给出代码
时间: 2024-04-17 16:26:28 浏览: 84
用C语言写的五子棋游戏代码
3星 · 编辑精心推荐
以下是一个简单的五子棋游戏的示例代码:
```c
#include <stdio.h>
#include <stdbool.h>
#define SIZE 15
char board[SIZE][SIZE];
// 初始化棋盘
void initBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = '-';
}
}
}
// 绘制棋盘
void drawBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
// 检查是否有五子连线
bool checkWin(int row, int col, char player) {
int count = 1;
// 水平方向
for (int i = col - 1; i >= 0 && board[row][i] == player; i--) {
count++;
}
for (int i = col + 1; i < SIZE && board[row][i] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// 垂直方向
count = 1;
for (int i = row - 1; i >= 0 && board[i][col] == player; i--) {
count++;
}
for (int i = row + 1; i < SIZE && board[i][col] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// 左斜方向
count = 1;
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0 && board[i][j] == player; i--, j--) {
count++;
}
for (int i = row + 1, j = col + 1; i < SIZE && j < SIZE && board[i][j] == player; i++, j++) {
count++;
}
if (count >= 5) {
return true;
}
// 右斜方向
count = 1;
for (int i = row - 1, j = col + 1; i >= 0 && j < SIZE && board[i][j] == player; i--, j++) {
count++;
}
for (int i = row + 1, j = col - 1; i < SIZE && j >= 0 && board[i][j] == player; i++, j--) {
count++;
}
if (count >= 5) {
return true;
}
return false;
}
int main() {
initBoard();
int row, col;
char player = 'X';
while (true) {
drawBoard();
printf("Player %c's turn. Enter row and column: ", player);
scanf("%d %d", &row, &col);
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE || board[row][col] != '-') {
printf("Invalid move. Try again.\n");
continue;
}
board[row][col] = player;
if (checkWin(row, col, player)) {
printf("Player %c wins!\n", player);
break;
}
// 切换玩家
player = (player == 'X') ? 'O' : 'X';
}
drawBoard();
return 0;
}
```
这段代码实现了一个简单的五子棋游戏。玩家可以依次输入行号和列号来下棋,程序会判断是否有五子连线来决定胜负。注意,这只是一个简单的示例,还可以进一步完善游戏规则和用户交互体验。希望对您有帮助!
阅读全文