Craps Game Java

时间:2015-10-19 02:14:41

标签: java random methods printing

我应该在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 个答案:

答案 0 :(得分:1)

看来这个方法:

youWin=youWin(sum, points)

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

  • 如果你绝对失败则返回一个值
  • 如果你肯定赢了,则返回一个值
  • 如果您建立了一个点,则返回一个值。