說明
一個簡單的賭博遊戲,遊戲規則如下:玩家擲兩個骰子,點數為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; }
import java.io.*;
public class Craps { public static void main(String[] args) throws IOException { final int WON = 0, LOST = 1, CONTINUE = 2; boolean firstRoll = true; int gameStatus = CONTINUE; int die1, die2, sumOfDice; int firstPoint = 0; System.out.print( "Craps賭博遊戲,按Enter鍵開始遊戲****");
while(true) { System.in.read();
if(firstRoll) { sumOfDice = rollDice(); System.out.println( "\n玩家擲出點數和:" + sumOfDice);
switch(sumOfDice) { case 7: case 11: gameStatus = WON; break; case 2: case 3: case 12: gameStatus = LOST; break; default: firstRoll = false; gameStatus = CONTINUE; firstPoint = sumOfDice; break; } } else { sumOfDice = rollDice(); System.out.println( "\n玩家擲出點數和:" + sumOfDice);
if(sumOfDice == firstPoint) gameStatus = WON; else if(sumOfDice == 7) gameStatus = LOST; }
if(gameStatus == CONTINUE) System.out.println("未分勝負,再擲一次****"); else { if(gameStatus == WON) System.out.println("玩家勝"); else System.out.println("玩家輸");
System.out.print("再玩一次?"); if(System.in.read() == 'n') { System.out.println("遊戲結束"); break; } firstRoll = true; } } }
public static int rollDice() { int roll = ((int)(Math.random() * 6) + (int)(Math.random() * 6));
if(roll < 2) { roll = 2; }
return roll; } }
|
|