C语言-猜拳游戏
目录
C语言-猜拳游戏
使用c语言编写程序实现人与计算机进行 猜拳游戏。
目录
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
int human;//玩家手势
int comp;//电脑手势
int judge;//判断输赢
int retry;//是否继续游戏
srand((unsigned int)time(NULL));//随机生成电脑的手势
printf("游戏开始!\n");
do
{
comp = rand() % 3;
do
{
printf("\n石头剪刀布 (0)石头(1)剪刀(2)布:");
scanf("%d", &human);//读取玩家的手势
} while (human < 0 || human>2);
printf("电脑出");
switch (comp)//显示电脑的手势
{
case 0:printf("石头"); break;
case 1:printf("剪刀"); break;
case 2:printf("布"); break;
}
printf("玩家出");
switch (human)//显示玩家的手势
{
case 0:printf("石头"); break;
case 1:printf("剪刀"); break;
case 2:printf("布"); break;
}
printf(".\n");
judge = (human - comp + 3) % 3;判断胜负
switch(judge)
{
case 0:printf("平局\n"); break;
case 1:printf("你输了\n"); break;
case 2:printf("你赢了\n"); break;
}
printf("再来一次吗(0)否(1)是:");
scanf("%d", &retry);
} while (retry==1);
return 0;
}
一、游戏总体流程
1.确定计算机要出的手势
2.显示石头剪刀布让玩家选择所要出的手势
3.进行输赢判断,显示结果
4.选择是否进行下一局游戏
二、石头剪刀布设计说明
1.计算机手势
我们用0代表出石头,用1代表出剪刀,用2代表出布, 此时我们就可以用rand函数和srand来实现电脑随机出手势。
代码如下
comp = rand() % 3;
switch (comp)
{
case 0:printf("石头"); break;
case 1:printf("剪刀"); break;
case 2:printf("布"); break;
}
2.玩家手势
玩家出手势较为简单,运用了switch语句。
同时do while循环防止玩家输入除了0,1,2之外的值
do
{
printf("\n石头剪刀布 (0)石头(1)剪刀(2)布:");
scanf("%d", &human);
} while (human < 0 || human>2);
switch (human)
{
case 0:printf("石头"); break;
case 1:printf("剪刀"); break;
case 2:printf("布"); break;
}
3 .输赢判断
1.平局
human与comp的值相同———>human-comp=0
2.玩家失败
箭头终点是玩家,起点为计算机此时玩家失败
human-comp的值为-2或1
3.玩家胜利
箭头终点是计算机,起点为玩家,此时玩家胜利
human-comp的值为-1或2
上述三个判断都可以用一个共同的表达式( human-comp+3)%3 表示
表达式结果为0表示平局,结果为1表示玩家失败,结果为2表示玩家胜利。
平局:
玩家失败:
玩家胜利:
优化
随着代码数量的增加,只用一个main函数来实现变的不太合理,于是下面的函数对程序中的函数进行封装,并增加了胜利条件,五局三胜,并且显示当前的成绩。先上代码:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int human;//player
int comp;//computer
int win_no;
int lose_no;
int draw_no;
char* hd[] = { "石头","剪刀","布" };
void initialize()//初始化
{
win_no = 0;
lose_no = 0;
draw_no = 0;
srand((unsigned int)time(NULL));
printf("猜拳游戏开始了!");
}
void jyanken()//运行猜拳游戏(读取/生成手势)
{
int i;
comp = rand() % 3;
do
{
printf("\n\a石头剪刀布");
for (int i = 0; i < 3; i++)
{
printf("(%d)%s", i, hd[i]);
}
printf(":");
scanf("%d", &human);//读取玩家的手势
} while (human < 0 || human>2);
}
void count_no(int result)//更新失败胜利平局的游戏次数
{
switch (result)
{
case 0: draw_no++; break;
case 1: lose_no++; break;
case 3: win_no++; break;
}
}
void disp_result(int result)
{
switch (result)
{
case 0:puts("平局。"); break;
case 1:puts("你输了。"); break;
case 3:puts("你赢了。"); break;
}
}
int main()
{
int judge;
initialize();
do {
jyanken();
printf("计算机出%s,你出%s。", hd[comp], hd[human]);
judge = (human - comp + 3) % 3;
count_no(judge);
disp_result(judge);
} while (win_no < 3 && lose_no < 3);
printf(win_no == 3 ? "\n你赢了.\n" : "\n计算机赢了\n");
printf("%d胜%d负%d平。\n", win_no, lose_no, draw_no);
return 0;
}