1.声明
当前内容主要为本人复习和使用C语言,并编写的一个小demo
主要涉及:
- 伪随机数的产生:srand(time(NULL));
return rand() % 3; // 控制计算机的出拳 - 个人输出,其他的就是业务逻辑的处理
2.demo
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define HAND_SIZE 3
int get_compare_int(int player,int computer){
if(player==computer)
{
return 0;
}else if((player==0 && computer==1)||(player==1 && computer==2)|| (player==2 && computer==0)){
return 1;
}else
{
return -1;
}
}
int win_count=0;
int lose_count=0;
int draw_no_count=0;
char* get_compare_char(int result){
char *str;
switch(result)
{
case 0:
str="平局";
draw_no_count++;
break;
case 1:
str="你赢了";
win_count++;
break;
case -1:
str="你输了";
lose_count++;
break;
}
return str;
}
char* get_guess_str(int input,char **hands){
char* result;
/*
switch(input)
{
case 0:
result="石头";
break;
case 1:
result="剪刀";
break;
case 2:
result="布";
break;
default:
result="石头";
break;
}*/
return result=hands[input];
}
int get_player_input(){
int p1;
scanf("%d",&p1);
if(p1>HAND_SIZE-1 || p1<0)
{
p1=0;
puts("默认出石头");
}
return p1;
}
int get_computer_input(){
srand(time(NULL));
return rand() % 3;
}
void input_prompt(char **hands){
printf("请输入出的拳:");
for(int i=0;i<HAND_SIZE;i++)
{
printf("%s(%d)",hands[i],(i));
if(i<HAND_SIZE-1)
{
printf(",");
}
}
printf("\n");
}
int prompt_try_again(){
puts("是否继续?(y/n)");
char isContinue[2];
scanf("%s",isContinue);
if(strcmp(isContinue,"n")==0||strcmp(isContinue, "N")==0)
{
return 0;
}
return 1;
}
void print_game_record(){
puts("游戏统计===============");
printf("赢局:%d次\n",win_count);
printf("输局:%d次\n",lose_count);
printf("平局:%d次\n",draw_no_count);
}
int main()
{
// 该申明方式有问题出现打印错误
/*char hands[3][5]={
"石头",
"剪刀",
"布"
};
// 该方式也错误
char** hands={
"石头",
"剪刀",
"布"
};
*/
// 正确方式创建字符指针类型数组
char* hands[HAND_SIZE]={
"石头",
"剪刀",
"布"
};
/*char* hands[]={
"石头",
"剪刀",
"布"
};*/
//input_prompt(hands);
while(1)
{
input_prompt(hands);
int player=get_player_input();
printf("玩家出:%s\n",get_guess_str(player,hands));
int computer=get_computer_input();
printf("电脑出:%s\n",get_guess_str(computer,hands));
int result=get_compare_int(player, computer);
printf("胜负结果:%s\n",get_compare_char( result));
if(!prompt_try_again())
{
puts("游戏结束");
break;
}
}
print_game_record();
return 0;
}
3.测试
测试结果正常