题目描述:
掷双骰子游戏是赌场中非常流行的骰子游戏。编写程序,玩这个游戏的一个变种,如下所示:掷两个骰子。每个骰子有六个面,分别表示值 1,2,……,6。检査这两个殽子的和。如果和为 2、3 或 12(称为掷骰子(craps)),你就输了;如果和是 7 或者 11(称作自然(natural)),你就贏了;但如果和是其他数字(例如:4、5、6、8、9 或者 10),就确定了一个点。继续掷骰子,直到掷出一个 7 或者掷出和刚才相同的点数。如果掷出的是 7,你就输了。如果掷出的点数和你前一次掷出的点数相同,你就贏了。程序扮演一个独立的玩家。下面是一些运行示例。
代码:
import java.util.Random;
public class Test11 {
public static void main(String[] args) {
Random r = new Random();
int dicePoint1 = r.nextInt(6) + 1;//随机生成骰子点数1
int dicePoint2 = r.nextInt(6) + 1;//随机生成骰子点数2
int sum = dicePoint1 + dicePoint2;
//掷骰子(craps)
if(sum == 2 || sum == 3 || sum == 12)
{
System.out.printf("You rollde %d + %d = %d\nYou lose\n",dicePoint1,dicePoint2,sum);
return;
}
//自然(natural)
else if(sum == 7 || sum == 11)
{
System.out.printf("You rollde %d + %d = %d\nYou win\n",dicePoint1,dicePoint2,sum);
return;
}
//其它数
else
System.out.printf("You rollde %d + %d = %d\npoint is %d\n",dicePoint1,dicePoint2,sum,sum);
while(true)
{
dicePoint1 = r.nextInt(6) + 1;
dicePoint2 = r.nextInt(6) + 1;
if(dicePoint1 + dicePoint2 == 7)
{
System.out.printf("You rollde %d + %d = 7\nYou lose\n",dicePoint1,dicePoint2);
return;
}
if(dicePoint1 + dicePoint2 == sum)
{
System.out.printf("You rollde %d + %d = %d\nYou win\n",dicePoint1,dicePoint2,sum);
return;
}
}
}
}
运行结果:
运行一:
You rollde 6 + 2 = 8
point is 8
You rollde 3 + 4 = 7
You lose
运行二:
You rollde 1 + 5 = 6
point is 6
You rollde 2 + 4 = 6
You win
运行三:
You rollde 1 + 2 = 3
You lose
运行四:
You rollde 2 + 5 = 7
You win