设计过程:
1.设计一个菜单,选项有游戏和退出选项
2.设计游戏代码块
3.创建棋盘面板,初始化为空
4.用户输入随机的字符
5.进行判断,是否胜利
6.电脑输入随机的字符
7.进行判断,是否胜利
8.一直进行循环,直到游戏结束
代码块:
1.头文件
#ifndef GAM_H
#define
GAM_H
#include<stdio.h>
#include<windows.h>
#include<time.h>
#define ROW 3
#define COL 3
#define P_COLOR 'X'
#define C_COLOR 'O'
#define NEXT 'N'
#define DRAW 'D'
void Meau();
void Game();
#endif
2.game.c
#include "game.h"
void Meau()
{
printf("#######################################\n");
printf("###### 1 Play 2 Exit ######\n");
printf("#######################################\n");
printf("please select#:");
}
void ShowBoard(char board[][COL],int row,int col)
{
printf("棋盘如下:\n");
printf("___");
printf("\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf("| %c ",board[i][j]);
}
printf("|\n");
printf("|_
|||\n");
}
printf("\n");
}
void PlayerMove(char board[][COL], int row, int col)
{
int x = 0;
int y = 0;
while (1)
{
printf("请输入你的位置# ");
scanf_s("%d %d", &x, &y);
if (x < 1 || x > 3 || y < 1 || y > 3)
{
printf("您输入的坐标有误!\n");
continue;
}
if (board[x - 1][y - 1] != ' ')
{
printf("该位置已经被占用!\n");
continue;
}
board[x - 1][y - 1] = P_COLOR;
break;
}
}
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;
}
void ComputerMove(char board[][COL], int row, int col)
{
while (1)
{
int x = rand() % 3;
int y = rand() % 3;
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)
{
ShowBoard(board, ROW, COL);
printf("你赢了!\n");
}
else if (C_COLOR == result)
{
ShowBoard(board, ROW, COL);
printf("你输了!\n");
}
else
{
printf("和棋");
}
}
3.test.c
#include "game.h"
int main()
{
int quit = 0;
int select = 0;
while (!quit)
{
Meau();
scanf_s("%d", &select);
switch (select)
{
case 1:
Game();
printf("你要不要再来一把\n");
break;
case 2:
quit = 1;
break;
default:
printf("输入有误\n");
break;
}
}
printf("byebye\n");
return 0;
}
来源:oschina
链接:https://my.oschina.net/u/4348489/blog/4689256