设计思路:
代码大体分为菜单显示,玩家走棋,电脑走棋,判断输赢,显示棋盘这几个主要模块。
菜单显示:让玩家选择游戏或者退出
玩家走棋:让玩家输入棋盘坐标放棋。需判断位置是否合理。
电脑走棋:让电脑循环生成两个3以内的随机数,直至位置合理退出循环,确定坐标。
判断输赢:逐行逐列判断是否有三子连珠(排除全是初始值(空格)的情况),或是和局,或是继续下棋。
显示棋盘:双层循环输出棋盘上每行每列的值。
代码如下:
#include<stdio.h>
#include<string.h>
#include<time.h>
#include<Windows.h>
#pragma warning(disable:4996)
#define P_COLOR 'X'
#define C_COLOR 'O'
#define ROW 3
#define COL 3
#define NEXT 'N'
#define DRAW 'D'
void Menu()//菜单
{
printf("#######################\n");
printf("## 1. Play 2. Exit ##\n");
printf("#######################\n");
printf("请输入:\n ");
}
static void ShowBoard(char board[][COL], int row, int col)//显示棋盘
{
printf(" | 1 | 2 | 3 |\n");
printf("---------------\n");
for (int i = 0; i < row; i++){
printf("%d |", i + 1);
for (int j = 0; j < col; j++){
printf(" %c |", board[i][j]);
}
printf("\n---------------\n");
}
}
static void PlayerMove(char board[][COL], int row, int col)//玩家走棋
{
int x = 0;
int y = 0;
while (1){
printf("请输入你的位置");
scanf("%d %d", &x, &y);
if (x < 1 || x > 3 || y < 1 || y > 3){
printf("你输入的坐标有误!\n");
continue;
}
else if (board[x - 1][y - 1] != ' '){
printf("该位置已经被占用!\n");
continue;
}
else{
board[x - 1][y - 1] = P_COLOR;
break;
}
}
}
static char Judge(char board[][COL], int row, int col)//判断当前棋局的情况
{
for (int 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 (int j = 0; j < col; j++){
if (board[0][j] == board[1][j] && \
board[1][j] == board[2][j] && \
board[0][j] != ' '){
return board[0][j];
}
}
if (board[0][0] == board[1][1] && \
board[1][1] == board[2][2] && \
board[0][0] != ' '){
return board[1][1];
}
if (board[0][2] == board[1][1] && \
board[1][1] == board[2][0] && \
board[1][1] != ' '){
return board[1][1];
}
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
if (board[i][j] == ' '){
return NEXT;
}
}
}
return DRAW;
}
static void ComputerMove(char board[][COL], int row, int col)//电脑随机走棋
{
while (1){
int x = rand() % row;
int y = rand() % col;
if (board[x][y] == ' '){
board[x][y] = C_COLOR;
break;
}
}
}
void Game()
{
srand((unsigned long)time(NULL));//随机数种子
char board[ROW][COL];
memset(board, ' ', sizeof(board));
char result = 'x';
do{
ShowBoard(board, ROW, COL);
PlayerMove(board, ROW, COL);
result = Judge(board, ROW, COL);
if (result != NEXT){
break;
}
ComputerMove(board, ROW, COL);
result = Judge(board, ROW, COL);
if (result != NEXT){
break;
}
} while (1);
if (P_COLOR == result){
printf("你赢了!\n");
}
else if (C_COLOR == result){
printf("你输了!\n");
}
else{
printf("和棋!\n");
}
ShowBoard(board, ROW, COL);
}
int main()
{
int n;
int quit = 0;
while (!quit)
{
Menu();
scanf("%d",&n);
switch (n)
{
case 1:
Game();
break;
case 2:
quit = 1; break;
default:printf("输入有误!请重新输入!\n"); break;
}
}
printf("ByeBye!\n");
system("pause");
return 0;
}