C语言数组实现三子棋

2023-02-21,,

C语言实现三子棋(通过数组

需要包含的头文件

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

创建一个全局数组

因为如果数组大小变化,游戏规则和实现思路都会有很大的变化,所以不进行宏定义常量来定义数组

char board[3][3];

设计主程序框架

game()函数为游戏过程框架

int main()
{ do
{
int i = 0;
printf("1.Start the game\n");
printf("2.Quit the game\n");
printf("Please enter your options->");
scanf("%d", &i);
switch (i)
{
case 1:
game(); //game()函数为游戏过程框架
break;
case 2:
return 0;
default:
printf("Input error,please enter again!\n");
break;
}
} while(1);
}

设计游戏过程框架

void game()
{
initBoard();
srand((unsigned)time(NULL)); //生成随机种子,后面需要生成随机坐标
char temp = ' '; //定义一个字符变量,用于接收后面判断函数返回值,用于决定游戏胜负
do
{
printBoard(); //打印棋盘的函数
userPlay(); //玩家下棋的函数
temp = judge(); //判断游戏是否分出胜负
if (temp != ' ')
break;
robotPlay(); //电脑下棋的函数
temp = judge();
} while (temp == ' ');
printBoard();
switch (temp)
{
case '@':
printf("User WIN!\n");
break;
case '$':
printf("Bobot WIN!\n");
break;
case '*':
printf("Dogfall !\n");
break;
dafault:
break;
}
}

设计棋盘样式

有兴趣的可以搞的更加花里胡哨,这里草草了事,呸,简单设计一下 哈

//##########
// | |
//_|_|_
// | |
//_|_|_
// | |
//##########

打印棋盘

重点就在这了,棋盘设计的再牛逼,也得能打印出来才行

这里棋盘设计的比较简易,打印起来也比较简单,关键是思路要清晰

void printBoard()
{
printf("##########\n");
int i = 0,j = 0;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
if (j != 2)
{
printf("%c|",board[i][j]);
}
else
printf("%c\n",board[i][j]); }
if (i != 2)
printf("_|_|_\n");
}
printf("##########\n");
}

玩家下棋

本人习惯用界面编程的坐标系表示坐标,因此下面赋值时横坐标和纵坐标倒过来了

void userPlay()
{
printf("Please enter coordinates->");
int x = 0,y = 0;
while(1)
{
scanf("%d %d", &x, &y);
if (x > 0 && x < 4 && y > 0 && y < 4)
{ if (board[y - 1][x - 1] == ' ')
{
board[y - 1][x - 1] = '@';
break;
}
else
printf("There are chess pieces here,please enter again!->");
}
else
printf("Input error,please enter again!->");
}
}

电脑下棋

这里关键是 要生成可行的坐标,以及随机数的生成

void robotPlay()
{
int i = 0, j = 0;
while (1)
{
i = rand() % 3;
j = rand() % 3;
if (board[i][j] == ' ')
{
board[i][j] = '$';
break;
}
} }

判断游戏胜负

这里就到了最难分析的一部分了

废话不多说,直接看代码

char judge()
{
int i = 0, j = 0;
//判断两条对角线 对i j 的值不做带动,所以放在前面
if (board[i][j] == board[i + 1][j + 1] && board[i][j] == board[i + 2][j + 2] && board[i][j] != ' ')
return board[i][j];
if (board[i][j + 2] == board[i + 1][j + 1] && board[i][j + 2] == board[i + 2][j] && board[i][j] != ' ')
return board[i][j + 2];
//依次判断三行、三列
for (i = 0,j = 0; j < 3; j++)
{
if (board[i][j] == board[i + 1][j] && board[i][j] == board[i + 2][j] && board[i][j] != ' ')
return board[i][j];
}
for (i = 0,j = 0; i < 3; i++)
{
if (board[i][j] == board[i][j + 1] && board[i][j] == board[i][j + 2] && board[i][j] != ' ')
return board[i][j];
}
//判断棋盘是否满了(平局)
for (i = 0; i < 3; i++)
{
for (j = 0;j < 3; j++)
{
if (board[i][j] == ' ')
return board[i][j];
}
}
//如果没出现以上情况,随便返回一个不同符号,使游戏继续进行
return '*'; }

源代码链接(Github)

C语言数组实现三子棋的相关教程结束。

《C语言数组实现三子棋.doc》

下载本文的Word格式文档,以方便收藏与打印。