骰子滚动java程序

时间:2014-10-06 20:13:18

标签: java dice

我正在制作骰子滚动游戏!将掷出2个骰子,并生成1-6之间的2个随机数。总和将取自2个数字,用于确定下一个数字。如果用户的总和是2,3,12那么他们输了。如果总和是7,11那么他们就赢了。如果总和是4,5,6,8,9,10,则程序会自动再次掷骰子直到用户获胜或输掉。此外,在显示的每个总和之后,显示他们赢得/输掉的游戏数量。到目前为止,这是我的代码:

//import java.util.Scanner;
public class Lab5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub


        //variables
        int dice1;
        int dice2;


        //Call the welcome method
        welcome();

        //fetch random numbers


        /*
         * **************************************************************
         *welcome method
         *welcome user
         *no parameters
         *no return
         ****************************************************************
         */
    }
    public static void welcome() {
        System.out.println("Welcome to a Lucky (for me) Dice Game! \nFEELING LUCKY?!? Hope you brought lots of CASH!");{
    }

    int dice1=(int)(Math.random()*6+1);
    int dice2=(int)(Math.random()*6+1);
    int sum= dice1 + dice2;

    System.out.println("Roll: total = " +sum); 

    if (sum==2|| sum==3|| sum==12){
    System.out.println("Sorry with a " + sum + " You LOSE :("); }
    else if(sum==7 || sum==11) { 
    System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!"); } 
    else{ 
    if(sum==4 ||sum==5 ||sum==6 ||sum==8 ||sum==9 ||sum==10) 
    dice1=(int)(Math.random()*6+1);
    dice2=(int)(Math.random()*6+1);}
    int roll2 = dice1 + dice2;}
    System.out.print("You rolled "+roll2+"  ");{
    while (roll2 !=7){
    if (roll == roll2);{
    System.out.println("You Win !");
    break;
    }else{

        }
    }
}}

我不确定如何显示用户赢/输的游戏,或者如果他们没有输赢,如何让程序再次掷骰子。

1 个答案:

答案 0 :(得分:2)

你应该使用while循环:骰子一次又一次地滚动,直到玩家赢了或输了(然后,break结束了while循环)。

while (true) {
    int dice1=(int)(Math.random()*6+1);
    int dice2=(int)(Math.random()*6+1);
    int sum = dice1 + dice2;

    System.out.println("Roll: total = " + sum); 

    if (sum==2 || sum==3 || sum==12) {
        System.out.println("Sorry with a " + sum + " You LOSE :(");
        break;
    } else if(sum==7 || sum==11) { 
        System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
        break; 
    }

    // If you wanted, you could wait here for the user to confirm (e.g. with a key press)
}