????????相信每一位同学都玩过井字棋游戏吧,这次我们写的三字棋游戏就是小时候的井字棋游戏。
? ? ? ? ? ? ? ?
下面是游戏的主代码。
#define _CRT_SECURE_NO_WARNINGS 1
#define ROW 3
#define COL 3
#include"game.h";
void print_borad(char borad[ROW][COL])//输出你的键盘
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
printf(" %c ", borad[i][j]);
if (j < COL-1)
printf("|");
}
printf("\n");
if(i<ROW-1)
for (int k = 0; k < COL; k++)
{
printf("---");
if (k < COL-1)
printf("+");
}
printf("\n");
}
}
void player_move(char borad[ROW][COL])
{
int x = 0;
int y = 0;
printf("请输入你的坐标:>");
while (1)
{
scanf("%d%d", &x, &y);//输入坐标
if (x > 0 && x <= ROW && y > 0 && y <= COL)
{
if (borad[x - 1][y - 1] == ' ')
{
borad[x - 1][y - 1] = '*';
break;
}
else
{
printf("坐标已经有棋了,请重新输入!\n");
}
}
else
printf("坐标非法!请重新输入!\n");
}
}
void pc_move(char borad[ROW][COL])
{
srand((unsigned)time(NULL));
printf("电脑下棋:>\n");
int x = 0;
int y = 0;//限制范围0~2
while (1)
{
x = rand()%ROW;
y = rand()%COL;
if (borad[x][y] == ' ')
{
borad[x][y] = '#';
break;
}
}
}
char who_win(char borad[ROW][COL])
{
for (int i = 0; i < ROW; i++)
{
if (borad[i][0] == borad[i][1] && borad[i][1] == borad[i][2] && borad[i][1] != ' ')//行判断
return borad[i][1];
}
for (int i = 0; i < COL; i++)
{
if (borad[0][i] == borad[1][i] && borad[1][i] == borad[2][i] && borad[1][i] != ' ')//列判断
return borad[1][i];
}
if (borad[1][1] == borad[0][0] && borad[1][1] == borad[2][2] && borad[1][1] != ' ')
return borad[1][1];
if (borad[1][1] == borad[0][2] && borad[1][1] == borad[2][0] && borad[1][1] != ' ')
return borad[1][1];
int flag = 0;//假设没有空格存在了
for(int i = 0;i<ROW;i++)
for (int j = 0; j < COL; j++)
{
if (borad[i][j] == ' ')
{
flag = 1;
break;
}
if (flag == 1)
break;
}
if (flag == 1)
return 'C';
else
return 'Q';
}
void game()//游戏的主体函数
{
char borad[ROW][COL] = { 0 };
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
borad[i][j] = ' ';
}//先全部初始化为空格
print_borad(borad);//输出键盘
while (1)
{
printf("玩家走!\n");
player_move(borad);
if (who_win(borad) != 'C')
break;
print_borad(borad);
printf("电脑动!\n");
pc_move(borad);
if (who_win(borad) != 'C')
break;
print_borad(borad);
}
print_borad(borad);
if (who_win(borad) == '*')
printf("玩家胜利!\n");
else if (who_win(borad) == '#')
printf("电脑胜利!\n");
else if (who_win(borad) == 'Q')
printf("平局!\n");
}
?接下来是游戏的头文件
#pragma once
#define ROW 3
#define COL 3
#include<stdio.h>
#include<stdlib.h>
void game();//游戏主函数
void print_borad(char borad[ROW][COL]);//输出你的键盘
void player_move(char borad[ROW][COL]);//玩家走
void pc_muve(char borad[ROW][COL]);//电脑走
void who_win(char borad[ROW][COL]);//判断哪边胜利
接下来是主函数的代码
#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void choose()
{
printf("*************************\n");
printf("******** 1.play *******\n");
printf("******** 0.exit *******\n");
printf("*************************\n");
}
int main()
{
int i;
while (1)
{
choose();
printf("请选择:>");
scanf("%d", &i);
switch (i)
{
case 1: {
printf("玩游戏\n");
game();
break;
}
case 0: {
printf("退出\n");
}
default: {
printf("输入错误!请重新输入!\n");
}
}
}
}
|