点数和是7或11(胜) 如果第一次点数和为2、3、12 (输 庄家赢) 点数和是 4、5、6、8、9、10 想赢就继续掷骰子 直到点数与第一次相同 游戏胜利"/>
有两个骰子 掷骰子 两者点数和是7或11(胜) 如果第一次点数和为2、3、12 (输 庄家赢) 点数和是 4、5、6、8、9、10 想赢就继续掷骰子 直到点数与第一次相同 游戏胜利
定义一个骰子类
import java.util.Random;public class Dice {/*** 需求:* 有两个骰子 点数1-6**/private int a ,b;Random random = new Random();public int[] setdice() {int[] dice = {1, 2, 3, 4, 5, 6};return dice;}public int getA() {return a=setdice()[random.nextInt(6)];//setdice 返回时一个数组 和arr[random.nextInt(6)] 相当}public int getB() {return b=setdice()[random.nextInt(6)];//setdice 返回时一个数组 和arr[random.nextInt(6)] 相当}}
游戏过程类
package test03.task.DiceGame;import com.sun.apache.xpath.internal.operations.Div;import java.lang.reflect.Method;
import java.util.Random;
import java.util.Scanner;public class DiceGame {/*** 有两个骰子* 掷骰子 两者点数和是7或11(胜)* 如果第一次点数和为2、3、12 (输 庄家赢)* 点数和是 4、5、6、8、9、10 想赢就继续掷骰子 直到点数与第一次相同* 再次期间如过掷到7就输*/Dice dice = new Dice();int a= dice.getA(); //骰子1int b= dice.getB(); //骰子1//开始游戏int i;public void playgame() {while (true){if (a+b==7||a+b==11){System.out.println("游戏胜利");System.exit(0);}switch (a+b){ //判读第一次结果所满足的条件case 2 :defeat(); //游戏失败case 3 :defeat();case 4 :judge(); //进入判断是否继续投掷case 5 :judge();case 6 :judge();case 8 :judge();case 9 :judge();case 10 :judge();case 12 :defeat();}}}public void defeat(){ //庄家赢System.out.println("输,庄家赢");System.exit(0);}public void next(){ //结果在4-8或9-10 之间继续投掷while (true){int d= dice.getA();int c= dice.getB();if (d+c == 7) { //判断是否满足输的条件System.out.println("输,庄家赢");System.out.println(c+d); //测试使用System.exit(0);}else if (d+c==a+b){ //判读是否满足赢的条件System.out.println("游戏胜利");System.out.println(d+c); //测试使用break;}}System.exit(0);}public void judge (){ //第一次投掷在4-6 和8-9 之间 是否继续投掷System.out.println("点数和在 4、5、6、8、9、10 之间想赢就继续掷骰子 ");System.out.println(a+b);System.out.println("是否继续游戏(您有三次机会):");System.out.println("1.继续游戏");System.out.println("2.退出游戏(庄家赢)");try { //异常 防止数据输入错误Scanner scanner = new Scanner(System.in);int a=scanner.nextInt();switch (a) {case 1: //继续System.out.println("游戏继续");next();case 2: //退出System.out.println("退出游戏");System.exit(0);}}catch (Exception e) { //出先异常 执行一下代码System.out.println("输入数据错误请重新输入");System.out.println("您还有" + (2 - i) + "次机会");i++;if (i > 2) {System.out.println("输入错误大于三次游戏结束:您输了");System.exit(0);}judge();}}
}
测试类 游戏开始:
package test03.task.DiceGame;import java.util.Scanner;public class TestDiceGame {public static void main(String[] args) {System.out.println("是否进行掷骰子游戏:");System.out.println("1.开始游戏");System.out.println("2.退出游戏");try { //捕捉异常Scanner scanner = new Scanner(System.in);int a = scanner.nextInt();switch (a){case 1:DiceGame diceGame =new DiceGame();diceGame.playgame();case 2:System.out.println("游戏结束");System.exit(0);}}catch (Exception e){ //若出现异常 则执行catch 后的语句System.out.println("输入错误");main(args);}}}
更多推荐
有两个骰子 掷骰子 两者点数和是7或11(胜) 如果第一次点数和为2、3、12 (输 庄家赢) 点数和是 4、5、6、8、9、10 想赢就继续掷骰子 直到点数与
发布评论