2016-03-24 2 views
-2

Я пытаюсь создать игру Dice Rolling, в которой пользователь может сыграть свою сумму очков (начальная сумма = 1000 очков) на высоком или низком уровне. Числа 1-6 являются низкими, 7 - автоматическими потерями, а 8-12 - высокими. У меня возникают проблемы с системой баллов и как он не добавляет/вычитает правильно, когда пользователь догадывается правильно или неправильно. Этот код написан полностью в GUI одного класса.Dice Roll Game Java

int die;//dice1 
    int dice;//dice2 
    int diceSum; 
    int points; 
    int guess; 
    int userBet; 

    points =(1000);//amount of point user starts with 

    jTextField4.setText("" + points);//setting user points 



    guess = Integer.parseInt(jTextField2.getText()); //determine if user bet high or low (1 = high), (0=low) 
    userBet = Integer.parseInt(jTextField3.getText());//determine amount user bet 

    die = 1 + (int) ((Math.random() * (7 - 1)));//dice 1 
    jLabel8.setText("" + die);//prints out dice # 
    dice = 1 + (int) ((Math.random() * (7 - 1)));//dice 2 
    jLabel9.setText("" + dice);//prints out dice # 
    diceSum = die + dice;//total sum of dice 

    { 
    if ((diceSum >=8)&&(guess == 1)) //user guesses high 
    jTextField1.setText("High, " + diceSum);//dice tells user its high 
    jTextField4.setText(userBet + points + "");//reward player points 

    } 
    { 
    if ((diceSum >=8)&&(guess ==0)) //user guesses low 
    jTextField1.setText("High, " + diceSum);//dice tells user its high 
    jTextField4.setText(userBet - points + ""); //subtract amount user bet 
    } 
    {   
    if((diceSum <= 6) && (guess ==1))//user guesses high 
    jTextField1.setText("Low, " + diceSum);//dice tells user its low 
    jTextField4.setText(points - userBet+"");//subtract amount user bet 

    } 
    { 
    if((diceSum <= 6)&& (guess ==0))//user guesses low 
    jTextField1.setText("Low, " + diceSum);//dice tells user its low 
    jTextField4.setText(userBet + points + ""); //reward player points 
    } 
    { 
    if (diceSum ==7)//automatic lose 
    jTextField1.setText("You Lose, " + diceSum);//automatic lose 
    jTextField4.setText(points - userBet+"");//subtract points 
    } 
+1

Вы имеете в виду крэпс? Мой совет - забыть о пользовательском интерфейсе. Получите ваш класс Die, а затем верните Dice and Game. Вы можете управлять им с помощью текстового интерфейса, пока поведение не будет правильным. Затем вы можете написать интерфейс Swing. Большинство noobs совершают эту ошибку: стены кода с UI встроены повсюду. Это неуместно. – duffymo

+1

Возможно, вы захотите рассмотреть возможность реструктуризации. Вы вводите ту же логику в кучу мест, что способствует ошибкам. Кроме того, отступы делают его несколько трудным для чтения. Ваша победа/убыток должна быть в одном месте. 'if ((guess == 1) && (diceSum> 7) || ((guess == 0) && (diceSum <7)) {adjust = 1 * bet; // win} else {adjust = -1 * ставка // loss} points + = adjust; '. Обновите свой пользовательский интерфейс независимо от расчета выигрыша/потери – Tibrogargan

ответ

1

Вместо того чтобы делать jTextField4.setText(userBet - points + ""); попробовать сделать что-то вроде этого:

points -= userBet; 
JTextField4.setText(points); 

При попытке выполнения операций внутри(), он не хранит значение, поэтому, когда вы делаете следующий время, точки все равно будут 1000.

Кроме того, почему вы вычитаете общее количество баллов из ставки? Это означает, что если у вас есть 100 очков и ставка 4, то у вас будет 96 очков, а не 96.

0
int die;//dice1 
int dice;//dice2 
int diceSum; 
int points; 
int guess; 
int userBet; 

points =(1000);//amount of point user starts with 

jTextField4.setText("" + points);//setting user points 

guess = Integer.parseInt(jTextField2.getText()); //determine if user bet high or low (1 = high), (0=low) 
userBet = Integer.parseInt(jTextField3.getText());//determine amount user bet 

die = 1 + (int) ((Math.random() * (7 - 1)));//dice 1 
jLabel8.setText("" + die);//prints out dice # 
dice = 1 + (int) ((Math.random() * (7 - 1)));//dice 2 
jLabel9.setText("" + dice);//prints out dice # 
diceSum = die + dice;//total sum of dice 

{ 
if ((diceSum >=8)&&(guess == 1)) //user guesses high 
jTextField1.setText("High, " + diceSum);//dice tells user its high 
jTextField4.setText(userBet + points + "");//reward player points 

} 
{ 
if ((diceSum >=8)&&(guess ==0)) //user guesses low 
jTextField1.setText("High, " + diceSum);//dice tells user its high 
jTextField4.setText(points - userBet + ""); //subtract amount user bet 
} 
{   
if((diceSum <= 6) && (guess ==1))//user guesses high 
jTextField1.setText("Low, " + diceSum);//dice tells user its low 
jTextField4.setText(points - userBet+"");//subtract amount user bet 

} 
{ 
if((diceSum <= 6)&& (guess ==0))//user guesses low 
jTextField1.setText("Low, " + diceSum);//dice tells user its low 
jTextField4.setText(userBet + points + ""); //reward player points 
} 
{ 
if (diceSum ==7)//automatic lose 
jTextField1.setText("You Lose, " + diceSum);//automatic lose 
jTextField4.setText(points - userBet+"");//subtract points 
}