VS2013环境下编写“三子棋”小游戏

版权声明:禁止侵权,打击盗版! https://blog.csdn.net/ChenGX1996/article/details/79980178

首先,创建一个game.h头文件:


内容如图所示。

创建一个main.c文件:


内容如图所示。

接下来,编写game函数:

#include "game.h"  




static void displayBoard(char board[ROW][COL], int row)//打印游戏面板  
{
int i = 0;
for (; i < row; i++)
{
printf("| %c | %c | %c |\n", board[i][0], board[i][1], board[i][2]);
printf("|---|---|---|\n");
}
}


static void playerMove(char board[ROW][COL], int row)//玩家移动  
{
int x, y;
do{
printf("Please Enter(x,y):\n");
scanf("%d%d", &x, &y);
if (x >= 1 && x <= 3 && y >= 1 && y <= 3)
{
if (board[x - 1][y - 1] == ' ')
{
board[x - 1][y - 1] = 'x';
break;
}
else
{
printf("这个位置被占用,try again!\n");
}
}
else
{
printf("Select errors,Please try again!\n");
}
} while (1);


}


static void computerMove(char board[ROW][COL], int row)//电脑移动  
{
srand((unsigned long)time(NULL));
do
{
int x = rand() % row;
int y = rand() % COL;
if (board[x][y] == ' ')
{
board[x][y] = 'o';
break;
}
} while (1);
}


static int isFull(char board[ROW][COL], int row)//判断是否把棋盘下满  
{
int i = 0;
for (; i < row; i++)
{
int j = 0;
for (; j < COL; j++)
{
if (board[i][j] == ' ')
{
return 0;
}
}
}
return 1;
}


static char isWin(char board[ROW][COL], int row)//判断是否胜利  
{
int i = 0;
for (i = 0; i < row; i++)
{
if (board[i][0] == board[i][1] && \
board[i][1] == board[i][2] && \
board[i][0] != ' ')//判断行  
{
return board[i][0];
}
}
for (i = 0; i < COL; i++)
{
if (board[0][i] == board[1][i] && \
board[1][i] == board[2][i] && \
board[0][i] != ' ')//判断列  
{
return board[0][i];
}
}
if (board[0][0] == board[1][1] && \
board[1][1] == board[2][2] && \
board[0][0] != ' ')//判断对角线  
{
return board[0][0];
}
if (board[0][2] == board[1][1] && \
board[1][1] == board[2][0] && \
board[0][2] != ' ')//判断对角线  
{
return board[0][2];
}
if (isFull(board, row))
{
return 'q';
}
return ' ';
}
void game()
{
char board[ROW][COL];
memset(board, ' ', ROW*COL);
char ret;
printf("开始游戏\n");
do
{
system("CLS");//清屏  
displayBoard(board, COL);//显示棋盘  
playerMove(board, COL);//玩家移动; 
system("CLS");
displayBoard(board, COL);
ret = isWin(board, COL);
if (ret != ' ')
{
break;
}
computerMove(board, COL);//电脑移动: 
system("CLS");
displayBoard(board, COL);
ret = isWin(board, COL);
} while (ret == ' ');
if (ret == 'q')//平局  
{
printf("平局!\n");
}
else if (ret == 'x')//玩家胜利  
{
printf("恭喜你,你赢了!\n");
}
else if (ret == 'o')//电脑胜利  
{
printf("你输了!\n");
}
else
{
printf("debug!\n");  
}
}

在VS2013环境下运行此程序,则可以创建一个“三子棋”的游戏。

运行结果如下图所示:

开始游戏:


游戏面板:


选择位置:


游戏结束:


重开一局请输入1,退出游戏请输入2.

阅读更多

没有更多推荐了,返回首页