问题描述:一个玩家投掷两颗骰子。每个骰子都有六个面,分别标有1,2,3,4,5和6,当被投掷的骰子停下来后,要统计每个骰子向上的面所标的点数之和作为判断输赢的依据。如果第一次投掷的两颗骰子的点数之和为7或11,则玩家赢,游戏结束。如果第一次投掷的两颗骰子的点数之和为2.3或者12,则玩家输,游戏结束。如果第一次投资的两颗骰子的得到的点数之和为4,5,6,8,9或者10,则这个数目作为玩家获胜所需要的点数,为了获胜,玩家必须继续投掷两颗骰子,直至一次投出的点数之和为这个点数,这是游戏结束,但是在此之前,投掷的点数之和等于7,则玩家输,游戏结束。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int face=0,face1=0,face2=0,win=0;
srand(time(NULL));
face1=1+(rand()%6);
face2=1+(rand()%6);
if (((face1+face2)==7) || ((face1+face2)==11)){
win=1;
}else{
if(((face1+face2)==2) || ((face1+face2)==3) || ((face1+face2)==12)){
win=0;
}else{
face=face1+face2;
face1=1+(rand()%6);
face2=1+(rand()%6);
while(((face1+face2)!=7) && (face!=(face1+face2))){
face1=1+(rand()%6);
face2=1+(rand()%6);
}
if((face1+face2)==7){
win=0;
}else{
win=1;
}
}
}
if(win==1){
printf("The player rolled %d +%d =%d\n",face1,face2,(face1+face2));
printf("The player win!\n");
}else{
printf("The player rolled %d +%d =%d\n",face1,face2,(face1+face2));
printf("The player lost!\n");
}
return 0;
}
接下来换一种思路,用gameSsatus标记游戏状态,将游戏分成两个阶段,第一个阶段是第一次骰子投掷导致游戏结束,第二阶段是第一阶段未结束进行的相当于加时赛,通过gameStatus的状态确定是否有第二阶段,并将骰子投掷行为封装在一个rollDice的函数里面。程序如下:
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
enum Status{CONTINUE,WON,LOST};
int rollDice(void);
int main()
{
int sum,myPoint;
enum Status gameStatus;
srand(time(NULL));
sum=rollDice();
switch(sum){
case 7:
case 11:
gameStatus=WON;
break;
case 2:
case 3:
case 12:
gameStatus=LOST;
break;
default :
gameStatus=CONTINUE;
myPoint=sum;
printf("myPoint is %d\n",myPoint);
break;
}
if(gameStatus==CONTINUE){
do{
sum=rollDice();
}while(sum!=myPoint && sum!=7);
if(sum==myPoint){
gameStatus=WON;
}
else{
gameStatus=LOST;
}
}
if(gameStatus==LOST){
printf("sorry , you are lost!\n");
}
else {
printf("congratulations,you won!\n");
}
return 0;
}
//roll dice and return the sum
int rollDice(void){
int face1,face2,sum;
face1=1+rand()%6;
face2=1+rand()%6;
sum=face1+face2;
printf("%d + %d = %d\n",face1,face2,sum);
return sum;
}