五子棋小游戏C语言VSCode
时间: 2023-06-21 19:06:59 浏览: 165
好的,我可以为您提供一份基于C语言和VSCode的五子棋小游戏代码。请注意,由于字符界面限制,该游戏不支持鼠标操作。以下是代码:
```
#include <stdio.h>
#include <stdlib.h>
#define ROWS 15
#define COLS 15
char board[ROWS][COLS]; // 保存棋盘状态
char player = 'X'; // 当前玩家棋子
// 初始化棋盘
void init_board()
{
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = '-';
}
}
}
// 打印棋盘
void print_board()
{
printf(" ");
for (int i = 0; i < COLS; i++) {
printf("%d ", i + 1);
}
printf("\n");
for (int i = 0; i < ROWS; i++) {
printf("%2d ", i + 1);
for (int j = 0; j < COLS; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
// 判断是否胜利
int is_win(int row, int col)
{
// 判断横向是否有5个棋子相连
int count = 1;
for (int i = col - 1; i >= 0; i--) {
if (board[row][i] == player) {
count++;
} else {
break;
}
}
for (int i = col + 1; i < COLS; i++) {
if (board[row][i] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return 1;
}
// 判断纵向是否有5个棋子相连
count = 1;
for (int i = row - 1; i >= 0; i--) {
if (board[i][col] == player) {
count++;
} else {
break;
}
}
for (int i = row + 1; i < ROWS; i++) {
if (board[i][col] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return 1;
}
// 判断左上-右下是否有5个棋子相连
count = 1;
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
for (int i = row + 1, j = col + 1; i < ROWS && j < COLS; i++, j++) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return 1;
}
// 判断左下-右上是否有5个棋子相连
count = 1;
for (int i = row + 1, j = col - 1; i < ROWS && j >= 0; i++, j--) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
for (int i = row - 1, j = col + 1; i >= 0 && j < COLS; i--, j++) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return 1;
}
return 0;
}
// 玩家下棋
void player_move()
{
int row, col;
do {
printf("请输入下棋位置(row col): ");
scanf("%d %d", &row, &col);
row--;
col--;
} while (row < 0 || row >= ROWS || col < 0 || col >= COLS || board[row][col] != '-');
board[row][col] = player;
}
// 电脑下棋
void computer_move()
{
// TODO: 实现电脑下棋功能
}
int main()
{
init_board();
while (1) {
print_board();
if (player == 'X') {
player_move();
} else {
computer_move();
}
if (is_win()) {
printf("游戏结束,%c方胜利!\n", player);
break;
}
player = player == 'X' ? 'O' : 'X';
}
return 0;
}
```
该五子棋小游戏以字符界面形式展示,玩家通过输入行列坐标下棋,电脑暂未实现下棋功能。您可以根据需要自行修改代码。
阅读全文