用C语言写一个五子棋小游戏
时间: 2023-11-14 07:04:24 浏览: 104
简易五子棋_小游戏五子棋_standard5l6_
好的,以下是用C语言写的五子棋小游戏的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ROWS 15
#define COLS 15
char board[ROWS][COLS];
void initBoard()
{
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = '+';
}
}
}
void printBoard()
{
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
bool isWin(int row, int col, char piece)
{
int i, j, count;
// 检查横向
count = 0;
for (i = col - 4; i <= col; i++) {
if (i >= 0 && i + 4 < COLS &&
board[row][i] == piece &&
board[row][i + 1] == piece &&
board[row][i + 2] == piece &&
board[row][i + 3] == piece &&
board[row][i + 4] == piece) {
return true;
}
}
// 检查纵向
count = 0;
for (i = row - 4; i <= row; i++) {
if (i >= 0 && i + 4 < ROWS &&
board[i][col] == piece &&
board[i + 1][col] == piece &&
board[i + 2][col] == piece &&
board[i + 3][col] == piece &&
board[i + 4][col] == piece) {
return true;
}
}
// 检查左上到右下斜向
count = 0;
for (i = row - 4, j = col - 4; i <= row && j <= col; i++, j++) {
if (i >= 0 && i + 4 < ROWS && j >= 0 && j + 4 < COLS &&
board[i][j] == piece &&
board[i + 1][j + 1] == piece &&
board[i + 2][j + 2] == piece &&
board[i + 3][j + 3] == piece &&
board[i + 4][j + 4] == piece) {
return true;
}
}
// 检查左下到右上斜向
count = 0;
for (i = row + 4, j = col - 4; i >= row && j <= col; i--, j++) {
if (i >= 0 && i - 4 < ROWS && j >= 0 && j + 4 < COLS &&
board[i][j] == piece &&
board[i - 1][j + 1] == piece &&
board[i - 2][j + 2] == piece &&
board[i - 3][j + 3] == piece &&
board[i - 4][j + 4] == piece) {
return true;
}
}
return false;
}
int main()
{
int row, col;
char piece = 'O';
initBoard();
printBoard();
while (true) {
printf("请 %c 方输入落子坐标(row col): ", piece);
scanf("%d %d", &row, &col);
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
printf("坐标不合法,请重新输入!\n");
continue;
}
if (board[row][col] != '+') {
printf("该位置已有棋子,请重新输入!\n");
continue;
}
board[row][col] = piece;
printBoard();
if (isWin(row, col, piece)) {
printf("恭喜 %c 方胜利!\n", piece);
break;
}
piece = piece == 'O' ? 'X' : 'O';
}
return 0;
}
```
这个五子棋游戏是基于命令行的,运行程序后,会显示出一个 15x15 的棋盘,每个位置用 + 表示。玩家轮流输入落子坐标,坐标输入格式为 row col,例如输入 7 7 表示在第 7 行第 7 列落子。如果输入的坐标不合法或者该位置已有棋子,则会提示重新输入。当某一方在横向、纵向或斜向连续五个棋子时,游戏结束,该方胜利。
阅读全文