code show as below:
//(It runs normally under linux! It may be garbled when running under windows!)
/**************************************************** ************
*Function: Realize the rock-paper-scissors game in C language
*Author: lml Time: April 17, 2020 11:41:57
*********** ***************************************************** */
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
int do_Compare(int us);
void do_Menu()
{ system("clear"); // clear screen printf("****************************** *************** \n"); printf(" ~~~~~~~ Welcome to rock-paper-scissors ~~~~~~~ \n"); printf(" If you If I win, I will tell you a story! \n"); printf(" ********************************* *****************\n"); }
int do_Game()
{ int i=0,j=0; int us=0,res=0; char user[20]=""; while(1){ char num[2]=""; printf("Please punch(scissors: 1 rock: 2 cloth: 3 exit: 9): "); fflush(stdout); scanf("%s",num);
//判断输入是否有误
if((num[0]<'1' || num[0]>'9') || (num[0] >'3' && num[0]<'9') || num[1]!='\0'){
printf("输入错误啦!\n");
continue;
}
//退出
us = atoi(num);
if(us == 9){
printf("游戏已退出!\n");
exit(1);
}
//判断用户输入的是什么
if(us == 1){
strcpy(user,"剪刀");
}else if(us == 2){
strcpy(user,"石头");
}else{
strcpy(user,"布");
}
printf("你出的是:%s\n",user);
//调用判断函数
res = do_Compare(us);
//分析结果
if(res == 0){
printf("哎呀呀,平局了!\n");
}else if(res == 1){
printf("哇塞,你赢了,好厉害啊!\n");
//do_story(); //这里赢了可以调用打印故事的函数,博主就不做了
}else{
printf("哎呀,你输了,再接再厉!\n");
}
}
return 0;
}
int do_Compare(int us)
{ int ra=0; char pc[20]=""; srand((unsigned)time(0)); ra = rand()%3 +1;//Random 1~3 Number, scissors 1 rock 2 cloth 3; if(ra == 1){ strcpy(pc,"scissors"); }else if(ra == 2){ strcpy(pc,"rock"); }else{ strcpy( pc, "cloth"); } printf("The output from the computer is: %s\n", pc);
//平局的情况
if(ra == us){
return 0; //返0是平局回
}
//不平局的情况
if(ra == 1){
if(us == 2){
return 1; //返回1表示用户胜利,
}else{
return -1;//返回1是用户失败。
}
}
if(ra == 2){
if(us == 3){
return 1;
}else{
return -1;
}
}
if(ra == 3){
if(us == 1){
return 1;
}else{
return -1;
}
}
}
int main(int argc, const char *argv[])
{
do_Menu();
do_Game();
return 0;
}
Finish.