难以决定在我的猪骰子游戏程序中放置一个while循环的位置

时间:2014-05-19 15:54:33

标签: java while-loop user-input dice

所以我正在编写一个程序,其中两个用户轮流掷骰子。如果用户滚动1然后他们的回合结束,如果用户滚动2-6然后我应该保持得分的总计得分,直到用户决定再次滚动并冒险他的存储点为该回合或者保存它。

我现在遇到的问题与我应该在我的代码中放置while循环的位置有关,这样用户可以玩一段不确定的时间。理想情况下,只要用户滚动1,我就想离开while循环,但是每次在循环之外我也会遇到如何更新该数字的问题。

任何帮助将不胜感激!注意:游戏尚未完成,我试图在继续之前写下一些问题,也就是我想把while循环放在takeTurn方法中的地方。

再次感谢!

这是我的代码:

import java.util.*;
public class PigDice {

// when a player reaches this number, they win
public static final int WINNING_SCORE = 50; 

public static final int DIE = 6; // sides on a die. 

public static void main( String[] args ) {
    Scanner keyboard = new Scanner( System.in );
    Random rand = new Random();

    String winner = playGame( keyboard, rand );
    System.out.println( winner + " wins!" );
}
public static String playGame( Scanner scanner, Random rand ) {

    int score1 = 0; // player 1's score 
    int score2 = 0; // player 2's score 

    // play till someone wins
    while ( score1 < WINNING_SCORE && score2 < WINNING_SCORE ) {
        score1 += takeTurn( scanner, rand, 1, score1 );
        System.out.println( "Player 1 score: " + score1 );
        System.out.println( "***************************" );
        if ( score1 < WINNING_SCORE ) {   
            score2 += takeTurn( scanner, rand, 2, score2 );
            System.out.println( "Player 2 score: " + score2 );
            System.out.println( "***************************" );
        }
    }
    if ( score1 >= WINNING_SCORE ) {
        return "Player 1";
    }
    else {
        return "Player 2";
    }
}

public static int takeTurn( Scanner scanner, Random rand, int player, int score ) {
    int random = rand.nextInt(DIE)+ 1;
    System.out.println("Player " + player + " rolls: " + random);
    int firstRoll = random;
    int roundTotal = 0;

    if ( random > 1) {
        System.out.println( "Player " + player + " total for this round: " + firstRoll);
        roundTotal += firstRoll;
        System.out.print("Roll again? (y or n) : ");
        String getAnswer = scanner.nextLine();
        System.out.println();
        if ( "y".equalsIgnoreCase(getAnswer)) {
            System.out.println("Player " + player + " rolls: " + random);

        }else if ( "n".equalsIgnoreCase(getAnswer)) {
            System.out.println("Player " + player + " score: " + roundTotal);
        } 
    }else {
        System.out.println("Player " + player + ": turn ends with no new points.");
        System.out.println("Player " + player + " score: " + score);
    }     


    return WINNING_SCORE;    
} 

}

3 个答案:

答案 0 :(得分:1)

提示:这可能不是最纯粹的解决方案,但是(没有多少人知道这一点,可能是最好的)Java循环可以使用labels :)有了它们,你可以轻松地去任何你喜欢的地方你的循环。

答案 1 :(得分:0)

你应该把你的循环放在主类中,为了在玩家滚动一个循环时退出,只需返回一个类似'lost'的字符串,在循环结束时检查它然后退出程序,或不。

答案 2 :(得分:0)

我在takeTurn方法的主体中添加了一个do while循环,允许其他所有内容都能解决。