五子棋
程序员文章站
2022-06-14 10:59:42
...
仿照三子棋写了一个简易版的五子棋三子棋
代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define ROW 5
#define COL 5
//菜单
int Meau() {
printf("-----------\n");
printf("1.开始游戏\n" );
printf("2.结束游戏\n" );
printf("-----------\n");
printf("请选择\n");
int choice = 0;
scanf("%d", &choice);
return choice;
}
char arr[ROW][COL];
//初始化棋盘
void Init() {
for (int row = 0; row < ROW; row++) {
for (int col = 0; col < COL; col++) {
arr[row][col] = ' ';
}
}
}
//打印棋盘
void Print() {
for (int row = 0; row < ROW; row++) {
printf("| %c | %c | %c | %c | %c |\n", arr[row][0], arr[row][1], arr[row][2], arr[row][3], arr[row][4]);
if (row != 4) {
printf("|---|---|---|---|---|\n");
}
}
}
//玩家落子用X表示
void PlayerMove() {
int row = 0, col = 0;
while (1) {
printf("请输入一个坐标(row col):\n");
scanf("%d %d", &row, &col);
if (row < 0 || row >= ROW || col<0 || col>+COL) {
printf("您的输入不合法,请重新输入\n");
continue;
}
else if (arr[row][col] != ' ') {
printf("该位置已被占用,请重新输入\n");
continue;
}
else {
arr[row][col] = 'X';
break;
}
}
arr[row][col] = 'X';
}
//电脑落子用O表示
void ComputerMove() {
while (1) {
int row = rand() % ROW;
int col = rand() % COL;
if (arr[row][col] != ' ') {
continue;
}
arr[row][col] = 'O';
break;
}
}
int Isfull() {
for (int row = 0; row < ROW; row++) {
for (int col = 0; col < COL; col++) {
if (arr[row][col] == ' ') {
return 1;
}
}
}
return 0;
}
//检查游戏是否结束
int CheckGameOver() {
for (int row = 0; row < ROW; row++) {
if (arr[row][0] == arr[row][1] && arr[row][0] == arr[row][2] && arr[row][0] == arr[row][3] && arr[row][0] == arr[row][4]) {
return arr[row][0];
break;
}
}
for (int col = 0; col < COL; col++) {
if (arr[0][col] == arr[1][col] && arr[0][col] == arr[2][col] && arr[0][col] == arr[3][col] && arr[0][col] == arr[4][col]) {
return arr[0][col];
break;
}
}
if (arr[0][0] == arr[1][1] && arr[0][0] == arr[2][2] && arr[0][0] == arr[3][4] && arr[0][0] == arr[4][4]) {
return arr[0][0];
}
if (arr[0][4] == arr[1][3] && arr[0][4] == arr[2][2] && arr[0][4] == arr[3][1] && arr[0][4] == arr[4][0]) {
return arr[0][4];
}
int n = Isfull();
if (n == 0) {
return 'Q';
}
return ' ';
}
void Game() {
//创建并初始化一个棋盘
Init();
char winner = ' ';
while (1) {
//打印棋盘
Print();
//玩家落子
PlayerMove();
//检测游戏结束
winner = CheckGameOver();
if (winner != ' ') {
break;
}
//电脑落子
ComputerMove();
//检查游戏结束
winner = CheckGameOver();
if (winner != ' ') {
break;
}
}
if (winner == 'X') {
printf("玩家胜!\n");
}
else if (winner == 'O') {
printf("电脑胜!\n");
}
else if (winner == 'Q') {
printf("和棋!\n");
}
else {
printf("好像出错了!\n");
}
}
int main() {
while (1) {
int choice = Meau();
if (choice == 1) {
Game();
}
else if (choice == 2) {
printf("goodbye!\n");
break;
}
else {
printf("输入有误,请重新输入\n");
continue;
}
}
system("pause");
return 0;
}