下面的代码会实现一个猜拳游戏,让你与电脑对决。你出的拳头由你自己决定,电脑则随机出拳,最后判断胜负。
启动程序后,让用户出拳,截图:
用户出拳,显示对决结果:截图:
代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
char gamer// 玩家出拳
int computer// 电脑出拳
int result// 比赛结果
// 为了避免玩一次游戏就退出程序,可以将代码放在循环中
while (1){
printf("这是一个猜拳的小游戏,请输入你要出的拳头:\n")
printf("A:剪刀\nB:石头\nC:布\nD:不玩了\n")
scanf("%c%*c",&gamer)
switch (gamer){
case 65: //A
case 97: //a
gamer=4
break
case 66: //B
case 98: //b
gamer=7
break
case 67: //C
case 99: //c
gamer=10
break
case 68: //D
case 100: //d
return 0
default:
printf("你的选择为 %c 选择错误,退出...\n",gamer)
getchar()
system("cls")// 清屏
return 0
break
}
srand((unsigned)time(NULL))// 随机数种子
computer=rand()%3// 产生随机数并取余,得到电脑出拳
result=(int)gamer+computer// gamer 为 char 类型,数学运算时要强制转换类型
printf("电脑出了")
switch (computer)
{
case 0:printf("剪刀\n")break//4 1
case 1:printf("石头\n")break//7 2
case 2:printf("布\n")break //10 3
}
printf("你出了")
switch (gamer)
{
case 4:printf("剪刀\n")break
case 7:printf("石头\n")break
case 10:printf("布\n")break
}
if (result==6||result==7||result==11) printf("你赢了!")
else if (result==5||result==9||result==10) printf("电脑赢了!")
else printf("平手")
system("pause>nul&&cls")// 暂停并清屏
}
return 0
}
代码分析
1) 首先,我们需要定义3个变量来储存玩家出的拳头(gamer)、电脑出的拳头(computer)和最后的结果(result),然后给出文字提示,让玩家出拳。
接下来接收玩家输入:
scanf("%c%*c",&gamer)
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <time.h>#define ORIGINGOLD 100 typedef struct { char name[100]unsigned long score} Uservoid Menu() { system("cls")printf("========================made by 小恩 =====================\n")printf("1:start game\n")printf("2:show order\n")printf("3:quit game\n")printf("==========================================================\n")} int choise() { int chprintf("Input your choice(1~3): ")while(ch=getchar()) { if('\n'==ch) continuewhile('\n'!=getchar())if(ch>'3'||ch<'1') { printf("Error input,Try again(1~3): ")continue} else break} return ch} int agree(const char *p) { char yesprintf("%s",p)while(scanf("%c",&yes),yes!='Y'&&yes!='N'&&yes!='y'&&yes!='n') { while('\n'!=getchar())printf("Error input! Try again(Y/N): ")} while('\n'!=getchar())if(yes=='Y'|| yes=='y') return 1else return 0} User getUser(const unsigned long score) { User gamerint ch,i=0memset(&gamer,0,sizeof(User))printf("Please input the User's name:")while(!strcmp(gamer.name,"")) { while((i<99) &&('\n'!=(ch=getchar()))) gamer.name[i++]=(char)chgamer.name[i]='\0'} gamer.score=scorereturn gamer} int getInt(int minR,int maxR) { int showhandwhile(!scanf_s("%d",&showhand) || showhand<minR|| showhand>maxR) { while('\n'!=getchar())printf("Invide input!Try again:(%d~%d) ",minR,maxR)} while('\n'!=getchar())return showhand} void save(const unsigned long score) { FILE *fpint num=0User gamer={"",0L},temp={"",0L},gmif(fopen_s(&fp,"F:\\fist.gm","r+")) { if(fopen_s(&fp,"F:\\fist.gm","w")) { printf("Error,Can't open file F:\\fist.gm for save!\n")exit(1)希望采纳
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)