三子棋游戏实现.
第一次体验到函数的使用使得稍微大一点的程序变得有条理而又简单.
分析所要完成的任务,条理清晰的写出步骤解释,然后使用代码一一实现.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int Menu() {
printf("==================\n");
printf("====1.开始游戏====\n");
printf("====0.结束游戏====\n");
printf("==================\n");
int choize = 0;
scanf("%d", &choize);
return choize;
}
#define MAX_ROW 3
#define MAX_COL 3
char chess_board[MAX_ROW][MAX_COL];
void Init() {
for (int row = 0; row < MAX_ROW; row++) {
for (int col = 0; col < MAX_COL; col++) {
chess_board[row][col] = ' ';
}
}
//设置随机种子
srand((unsigned int)time(0));
}
void Print() {
for (int row = 0; row < MAX_ROW; row++) {
printf(" | %c | %c | %c | \n ", chess_board[row][0],
chess_board[row][1], chess_board[row][2]);
if (row != MAX_ROW - 1) {
printf("| --- | --- | --- |\n");
}
}
}
void PlayerMove() {
printf("玩家落子!\n");
while (1) {
printf("请输入落子位置的坐标:(row,col):");
int row = 0;
int col = 0;
scanf("%d %d", &row, &col);
//判断玩家落子坐标是否合法?
if (row < 0 || row >= MAX_ROW
|| col < 0 || col >= MAX_COL) {
printf("您输入的坐标非法,请重新输入!\n");
continue;
} if (chess_board[row][col] != ' ') {
printf("您输入的位置已被占用.\n");
continue;
}
chess_board[row][col] = 'x';
break;
}
printf("玩家落子完毕!\n");
}
//如果棋盘满了返回1,否则返回0
int IsFull() {
for (int row = 0; row < MAX_ROW; row++) {
for (int col = 0; col < MAX_COL; col++) {
if (chess_board[row][col] == ' '); {
return 0;
}
}
}
return 1;
}
//用返回值表示胜利方
//x表示玩家胜
//o表示电脑胜
//q表示和棋
//' '表示未分胜负
char CheakWinner() {
//检查所有行元素是否一样
for (int row = 0; row < MAX_ROW; row++) {
if (chess_board[row][0] == chess_board[row][1]
&& chess_board[row][0] == chess_board[row][2]) {
return chess_board[row][0];
}
}
//检查所有列元素是否一样
for (int col = 0; col < MAX_COL; col++) {
if (chess_board[0][col] == chess_board[1][col]
&& chess_board[0][col] == chess_board[2][col]) {
return chess_board[0][col];
}
}
//检查所有对角线元素是否一样
if (chess_board[0][0] == chess_board[1][1]
&& chess_board[0][0] == chess_board[2][2]) {
return chess_board[0][0];
}
if (chess_board[0][2] == chess_board[1][1]
&& chess_board[0][2] == chess_board[2][0]) {
return chess_board[2][0];
}
//若棋盘已满并未分出胜负
if (IsFull()) {
return 'q';
}
return ' ';
}
void ComputerMove() {
printf("电脑落子!\n");
while (1) {
int row = rand() % 3;
int col = rand() % 3;
if (chess_board[row][col] != ' ') {
continue;
}
chess_board[row][col] = 'o';
break;
}
printf("电脑落子完毕'\n");
}
void Game() {
//1.初始化棋盘
Init();
char winner = ' ';
while (1) {
//2.打印棋盘
Print();
//3.玩家落子
PlayerMove();
//4.判断胜负
winner = CheakWinner();
if (winner != ' ') {
break;
}
//5.电脑落子
ComputerMove();
//6.判断胜负
winner = CheakWinner();
if (winner != ' ') {
break;
}
}
Print();
if (winner == 'x') {
printf("您赢了!\n");
}
else if (winner == 'o') {
printf("你真菜,连电脑都下不过!\n");
}
else if (winner == 'q') {
printf("和棋.\n");
}
else {
printf("代码出现bug了!\n");
}
}
int main() {
while (1) {
int choize = Menu();
if (choize == 1) {
Game();
}
else if (choize == 0) {
printf("goodbye!\n");
}
else {
printf("您的输入有误!请您重新输入.\n");
}
}
system("pause");
return 0;
}