用C++写一个五子棋游戏代码
时间: 2024-01-28 14:05:53 浏览: 88
用C++写的五子棋游戏
下面是一个简单的五子棋游戏的代码,其中包括显示游戏界面、玩家与电脑下棋、判断胜负等功能。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define CHESSBOARD_SIZE 15
#define PLAYER_CHESS 'X'
#define COMPUTER_CHESS 'O'
// 五子棋棋盘
char chessboard[CHESSBOARD_SIZE][CHESSBOARD_SIZE] = {0};
// 打印游戏界面
void print_game_board()
{
printf(" ");
for(int i = 0; i < CHESSBOARD_SIZE; i++)
{
printf(" %d", i + 1);
}
printf("\n");
for(int i = 0; i < CHESSBOARD_SIZE; i++)
{
printf("%d", i + 1);
for(int j = 0; j < CHESSBOARD_SIZE; j++)
{
printf(" %c", chessboard[i][j]);
}
printf("\n");
}
}
// 判断胜负
int check_win(int x, int y, char chess)
{
// 判断横向
int count = 0;
for(int i = x - 4; i <= x; i++)
{
if(i < 0 || i + 4 >= CHESSBOARD_SIZE)
{
continue;
}
count = 0;
for(int j = i; j <= i + 4; j++)
{
if(chessboard[y][j] == chess)
{
count++;
}
}
if(count == 5)
{
return 1;
}
}
// 判断纵向
count = 0;
for(int i = y - 4; i <= y; i++)
{
if(i < 0 || i + 4 >= CHESSBOARD_SIZE)
{
continue;
}
count = 0;
for(int j = i; j <= i + 4; j++)
{
if(chessboard[j][x] == chess)
{
count++;
}
}
if(count == 5)
{
return 1;
}
}
// 判断正斜线
count = 0;
int diff = y - x;
for(int i = diff - 4; i <= diff; i++)
{
if(i < 0 || i + 4 >= CHESSBOARD_SIZE)
{
continue;
}
count = 0;
for(int j = i; j <= i + 4; j++)
{
if(chessboard[j - diff + x][j] == chess)
{
count++;
}
}
if(count == 5)
{
return 1;
}
}
// 判断反斜线
count = 0;
diff = y + x;
for(int i = diff - 4; i <= diff; i++)
{
if(i < 0 || i + 4 >= CHESSBOARD_SIZE)
{
continue;
}
count = 0;
for(int j = i; j <= i + 4; j++)
{
if(chessboard[diff - j][j] == chess)
{
count++;
}
}
if(count == 5)
{
return 1;
}
}
return 0;
}
// 玩家下棋
void player_move()
{
int x, y;
do
{
printf("Please enter your move (row column): ");
scanf("%d %d", &y, &x);
}while(y < 1 || y > CHESSBOARD_SIZE || x < 1 || x > CHESSBOARD_SIZE || chessboard[y - 1][x - 1] != ' ');
chessboard[y - 1][x - 1] = PLAYER_CHESS;
}
// 电脑下棋
void computer_move()
{
int x, y;
srand((unsigned)time(NULL));
do
{
x = rand() % CHESSBOARD_SIZE;
y = rand() % CHESSBOARD_SIZE;
}while(chessboard[y][x] != ' ');
printf("The computer moves: %d %d\n", y + 1, x + 1);
chessboard[y][x] = COMPUTER_CHESS;
}
int main()
{
int player_turn = 1;
while(1)
{
print_game_board();
if(player_turn)
{
player_move();
if(check_win(player_x - 1, player_y - 1, PLAYER_CHESS))
{
printf("You win!\n");
break;
}
}
else
{
computer_move();
if(check_win(computer_x, computer_y, COMPUTER_CHESS))
{
printf("The computer wins!\n");
break;
}
}
player_turn = !player_turn;
}
return 0;
}
```
请注意,此代码只是一个简单的实现,如果您想要实现更完整的五子棋游戏,可能需要添加更多的功能和规则。
阅读全文