C 语言实现三子棋(通过数组)
须要蕴含的头文件
include <stdio.h>
include <stdlib.h>
include <time.h>
创立一个全局数组
因为如果数组大小变动,游戏规则和实现思路都会有很大的变动,所以不进行宏定义常量来定义数组
char board3;
设计主程序框架
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 '*';
}