【问题标题】:Craps Game Java掷骰子游戏 Java
【发布时间】:2015-10-19 02:14:40
【问题描述】:

我应该在 java 中做一个掷骰子游戏,但我有一个问题。你看,从技术上讲,游戏已经结束了,但即使你输了,它也不会说你是否输掉了比赛。它只会继续滚动直到您获胜。我尝试了几种解决方法,但似乎只是将其困在无限循环中。 游戏规则: 掷两个骰子。每个骰子有六个面,分别代表值 1、2、……和 6。 检查两个骰子的总和。如果总和是 2、3 或 12(称为掷骰子),您 失去;如果总和是 7 或 11(称为自然),则您获胜;如果总和是另一个值 (即 4、5、6、8、9 或 10),建立一个点。继续掷骰子直到 掷出 7 或相同的点值。如果掷出 7,您就输了。否则,你赢了。

Example run:
You rolled 4 + 4 = 8
point is 8
You rolled 6 + 2 = 8
You win

我的代码如下:

import java.util.*;
public class CrapsGame
{

   public static void main (String[]args)
   {



      String restart = "y";
      Scanner scan = new Scanner(System.in);
      int sum=rollDice();
      int points = points(sum);
      boolean youWin=youWin(sum, points);  

      while(restart.equals("y")){
         youWin=false;
         while(youWin==false){
            rollDice();
            sum=rollDice();
            points=points(sum);
            youWin=youWin(sum, points);
         }


         System.out.print("\nWould you like to play again? y or n: ");
         restart = scan.next();
      }
      System.out.print("The program has ended!"); 
   }
   public static int rollDice() 
   {
      int num1= (int)(6.0*Math.random() + 1.0); //first die
      int num2= (int)(6.0*Math.random() + 1.0); //second die
      int sum= num1 + num2; //sum of roll
      System.out.printf("\nYou have rolled %d + %d = %d\n", num1, num2, sum);  //Prints the sum
      return sum;
   }


   public static int points(int sum)
   {  
      int points=0;
      if (sum>=4 && sum<=6) {  //Counts points based on your rolls
         points = points + 1;
         System.out.print("Your points are: " + points);
      }
      else if (sum>=8 && sum<=10){
         points = points + 1;
         System.out.print("Your points are: " + points);
      }
      return points;
   }

   public static boolean youWin(int sum, int points)
   {  
      boolean youWin=false;
      if (sum==2 || sum==3 || sum == 12) {
         youWin=false;
         System.out.print("You lost with a " + sum);  //Determines if you win or loose based on the sum and points and returns the youWin boolean
      }
      else if (sum==7 || sum==11) {
         youWin=true;
         System.out.print("You won with a " + sum);
      }
      else if (points==7){
         youWin=true;
      }
      return youWin;
   }

}

【问题讨论】:

  • 1.删除代码中的所有噪音。删除所有与您的问题无关的无意义的 cmets 和代码。 2. 你应该清楚你的行为如何偏离预期的行为。 3. 学习使用调试器并跟踪它。通常这种问题在调试器的帮助下很容易发现
  • 我会这样做的,我必须把所有的废话都放在那里,因为这是我的教授希望我拥有的。我知道这没有帮助。
  • 你会在你的作业中需要它,但这里的问题中不需要。
  • 是的,我意识到:/ 我总是忘记删除 cmets,因为我想在考虑它的同时发布它。对此感到抱歉。

标签: java random methods printing


【解决方案1】:

好像是这个方法:

youWin=youWin(sum, points)

需要返回 2 种以上的类型。它应该:

  • 如果你确定输了,返回一个值
  • 如果你肯定赢了,就返回一个值
  • 如果您建立一个点,则返回一个值。

【讨论】:

  • 我正在循环播放,因为它应该继续打印总和并加分,直到您获胜或获得掷骰子为止。我会更新游戏规则。
猜你喜欢
  • 2015-12-24
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多