小游戏:骰子游戏

规则很简单:

编写函数模拟掷骰子的游戏(两个骰子)。第一次掷骰子的时候,如果点数为7或11则获胜;如果点数之和为2、3或12则落败;其他情况下的点数之和称为目标,游戏继续。后续的投掷中,如果玩家再次掷出目标点数则获胜,掷出7则落败,其他情况忽略,游戏继续进行。每局游戏结束时,程序询问用户是否再玩一次,如果用户输入的回答不是y或Y,程序会显示胜败的次数然后终止。

设计思路:

随机数函数和时间函数进行赋值,其余细节见代码注释。

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int roll_dice(void){
	int a,b;
	a=rand()%6+1;
	b=rand()%6+1;
	return a+b;
}//骰子点数生成器

int play_game(void){
	int i,j,k,m;
	i=roll_dice();
	printf("You rolled: %d\n",i);
	printf("Your point is %d\n",i);
	if (i==7||i==11) { 
	  k=1;
	} 
	else if(i==2||i==3||i==12){
		k=0;
	}
	else{
		for(;;){
			j=roll_dice();
			printf("You rolled: %d\n",j);
			if(j==7){
				k=0;
				break;
			}
			else if(j==i){
				k=1;
				break;
			}
			else
			continue;
		}
	}
	return k;
}//游戏发生函数



int main()
{
	printf("This is a game concerning luck.\n");
	printf("Are your ready?(press Enter)");
	while(getchar()!='\n')
	;
	printf("Good luck!") ;
	while(getchar()!='\n')
	;
	srand((unsigned)time(0));
	int k,losses=0,wins=0;//计数器
	char ch1,ch2;
	k=play_game();
	if(k==0) {
	printf("You lose!\n");
	losses++;
    }
	else {
	printf("You win!\n");
	wins++;
    }
    printf("Play again? ");
    while(1){
      ch1=getchar();
      ch2=getchar();//读取回车符(至关重要) 
      printf("\n");
      if(ch1=='y'){
       k=play_game();
	    if(k==0) {
	     printf("You lose!\n");
	     losses++;
        }
	    else {
	     printf("You win!\n");
	     wins++;
        } 
        printf("Play again?");
      }
      else{
      	printf("\n");
      	break;
	  }
    }
    printf("Wins:%d Losses:%d",wins,losses);
    
	return 0;
}
 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Detachment_destin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值