c语言二维数组五子棋
时间: 2023-10-26 22:59:03 浏览: 91
以下是一个使用C语言实现的简单五子棋游戏代码示例:
```c
#include <stdio.h>
#include <stdbool.h>
const int BOARD_SIZE = 15;
char board[15][15];
// 初始化棋盘
void initBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = '+';
}
}
}
// 绘制棋盘
void drawBoard() {
printf(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
printf(" %d", i);
}
printf("\n");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%d", i);
for (int j = 0; j < BOARD_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 < BOARD_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 < BOARD_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 < BOARD_SIZE && j < BOARD_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 < BOARD_SIZE && board[i][j] == player; i--, j++) {
count++;
}
for (int i = row + 1, j = col - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == player; i++, j--) {
count++;
}
if (count >= 5) {
return true;
}
return false;
}
int main() {
initBoard();
drawBoard();
char currentPlayer = 'X';
int row, col;
while (true) {
printf("Player %c, enter your move (row col): ", currentPlayer);
scanf("%d %d", &row, &col);
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE || board[row][col] != '+') {
printf("Invalid move!\n");
continue;
}
board[row][col] = currentPlayer;
drawBoard();
if (checkWin(row, col, currentPlayer)) {
printf("Player %c wins!\n", currentPlayer);
break;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
return 0;
}
```
这个代码示例与之前的C++示例非常相似,只是使用了C语言的输入输出函数。你可以运行这段代码来玩一下五子棋游戏。
阅读全文