c语言五子棋人人对战
时间: 2023-06-22 16:18:16 浏览: 61
好的,您需要一个人人对战的五子棋游戏,以下是一个简单的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 15 // 棋盘大小
#define EMPTY 0 // 空格
#define BLACK 1 // 黑子
#define WHITE 2 // 白子
int board[SIZE][SIZE]; // 棋盘
int player = BLACK; // 当前执子的玩家
// 初始化棋盘
void init_board() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = EMPTY;
}
}
}
// 打印棋盘
void print_board() {
printf(" ");
for (int i = 0; i < SIZE; i++) {
printf("%c ", 'A' + i);
}
printf("\n");
for (int i = 0; i < SIZE; i++) {
printf("%2d ", i + 1);
for (int j = 0; j < SIZE; j++) {
if (board[i][j] == EMPTY) {
printf("+ ");
} else if (board[i][j] == BLACK) {
printf("● ");
} else {
printf("○ ");
}
}
printf("%2d\n", i + 1);
}
printf(" ");
for (int i = 0; i < SIZE; i++) {
printf("%c ", 'A' + i);
}
printf("\n");
}
// 判断落子是否合法
bool is_valid(int row, int col) {
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) {
return false; // 落子位置超出棋盘范围
}
if (board[row][col] != EMPTY) {
return false; // 落子位置已经有棋子
}
return true;
}
// 判断当前玩家是否胜利
bool is_win() {
int count; // 连续棋子的个数
// 横向
for (int i = 0; i < SIZE; i++) {
count = 0;
for (int j = 0; j < SIZE; j++) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
}
// 纵向
for (int j = 0; j < SIZE; j++) {
count = 0;
for (int i = 0; i < SIZE; i++) {
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
}
// 斜向
for (int i = 0; i <= SIZE - 5; i++) {
for (int j = 0; j <= SIZE - 5; j++) {
count = 0;
for (int k = 0; k < 5; k++) {
if (board[i + k][j + k] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
}
}
for (int i = 0; i <= SIZE - 5; i++) {
for (int j = SIZE - 1; j >= 4; j--) {
count = 0;
for (int k = 0; k < 5; k++) {
if (board[i + k][j - k] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
}
}
return false;
}
int main() {
init_board();
print_board();
while (true) {
printf("Player %d's turn: ", player);
char col;
int row;
scanf(" %c%d", &col, &row);
int c = col - 'A';
int r = row - 1;
if (!is_valid(r, c)) {
printf("Invalid position!\n");
continue;
}
board[r][c] = player;
print_board();
if (is_win()) {
printf("Player %d wins!\n", player);
break;
}
player = (player == BLACK ? WHITE : BLACK);
}
return 0;
}
```
这是一个简单的控制台程序,您可以将其编译并运行。每次轮到玩家输入时,输入行和列(例如 A1 表示第一行第一列),程序会判断该位置是否合法,如果合法则在该位置落子,并判断当前玩家是否胜利。如果胜利,则输出胜利信息并结束游戏。如果没有胜利,则交换玩家并继续游戏。