說明
一個簡單的賭博遊戲,遊戲規則如下:玩家擲兩個骰子,點數爲1到6,如果第一次點數和爲7或11,則玩家勝,如果點數和爲2、3或12,則玩家輸,如果和 爲其它點數,則記錄第一 次的點數和,然後繼續擲骰,直至點數和等於第一次擲出的點數和,則玩家勝,如果在這之前 擲出了點數和爲7,則玩家輸。
解法 規則看來有些複雜,但是其實只要使用switch配合if 條件判斷來撰寫即可,小心不要弄錯勝負順序即可。
*****************************************程序***************************
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define WON 0
#define LOST 1
#define CONTINUE 2
int rollDice(){
return (rand()% 6) + (rand()% 6) + 2;
}
int main(void){
int firstRoll = 1;
int gameStatus = CONTINUE;
int die1,die2,sumOfDice;
int firstPoint= 0;
char c;
srand(time(0));
printf("Craps賭博遊戲,按Enter鍵開始遊戲****");
while(1){
getchar();
if(firstRoll){
sumOfDice = rollDice();
printf("\n玩家擲出點數和:%d\n",sumOfDice);
switch(sumOfDice){
case 7:
case 11:gameStatus = WON; break;
case 2:
case 3:
case 12:gameStatus = LOST;break;
default:firstRoll = 0;gameStatus = CONTINUE; firstPoint= sumOfDice; break;
}
}else {
sumOfDice = rollDice();
printf("\n玩家擲出點數和:%d\n",sumOfDice);
if(sumOfDice == firstPoint)
gameStatus = WON;
else if(sumOfDice == 7)
gameStatus = LOST;
}
if(gameStatus == CONTINUE)
puts("未分勝負,再擲一次****\n");
else {
if(gameStatus == WON)
puts("玩家勝");
else
puts("玩家輸");
printf("再玩一次?");
scanf("%c",&c);
if(c == 'n'){
puts("遊戲結束");
break;
}
firstRoll = 1;
}
}
return 0;
}
***********************************END***************************************