Thread: Issues looping and breaking in Pigs Dice Game

1. Member
Join Date
Feb 2011
Posts
2
Rep Power
0

Issues looping and breaking in Pigs Dice Game

Hello, I am very new to this forum and fairly new to Java and my newest assignment is a pigs game which i've listed the rules for in the code below. I'm not asking for anybody to do my hw for me, i just want some guidance on how to implement these "rules". At this point, the program wont loop in the "game" loop properly.
Java Code:
```/*
**********************************************************************************************************************************
*                                                                                                                                *
*	Using the PairOfDice class, deisgn and implement a class to play a game called Pig. In this game, the user competes against  *
*	the computer. On each turn, the player rolls a pair of dice and adds up his or her points. Whoever reaches 100 first, wins.  *
*	If a player rolls a 1, he or she loses all points for that round and the dice go to the other player. If a player rolls two  *
*	1s in one turn, the player loses control of the dice. The player may voluntarily turn over the dice after each roll. So the  *
*	player must decide to either roll again (be a pig) and risk losing points, or give up the dice, possibly letting the other   *
*	player win. Set up the computer player that it always gives up the dice after getting 20 or more points in a round.          *
*                                                                                                                                *
**********************************************************************************************************************************/

import cs1.*;

public class PigNew
{
public static void main (String[]args)
{
PairOfDice die1 = new PairOfDice();

//int yesNo= 0;
//System.out.println("Press 1 to roll die and play Pig!");
// all variables used declared here
int TotalPoints=0;//these are points used for game loop purposes
int compTotal=0;
int humanTotal=0;
int roundPoints= 0;
int die1Result=0;
int die2Result=0;
boolean humanTurn=true;
boolean gameIsOver= false;
boolean roundIsOver=false;
//game loop starts here to determine the roll of the dice
while(compTotal < 100 && humanTotal < 100)
{
//dice rolled here
die1Result=die1.rollDie();
die2Result=die1.rollDie2();
// statements to sort out die results
if(die1Result==1 && die2Result==1)//if both die equal 1 all points = 0
{
TotalPoints= 0;
roundPoints= 0;

System.out.println("Computer says "+die1Result +" and "+die2Result);
System.out.println("Round points = " + roundPoints);

System.out.println("Number of points = " + TotalPoints);
humanTurn=false;
break;
}

else if(die1Result==1 || die2Result == 1)//if 1 die is 1 then round points = 0
{
System.out.println("Computer says "+die1Result +" and "+die2Result);
roundPoints= 0;
System.out.println("Round points = " + roundPoints);
System.out.println("Number of points = " + TotalPoints);
humanTurn=false;
break;
}

else//for legit dice points added to roundpoints
{
roundPoints=die1Result+die2Result;
System.out.println("Computer says "+die1Result +" and "+die2Result);
System.out.println("Round points = " + roundPoints);
System.out.println("Number of points = " + TotalPoints);

}//end of else

if(1==1)//identifier to separate loop to organize for point adding
{
System.out.println("Would you like to continue? 1 for yes.");
{
break;
}//end of if
if(humanTurn=true)
{
humanTotal += roundPoints;
humanTurn=false;
roundPoints=0;
}
else//computer got round
{
compTotal+=roundPoints;
humanTurn=true;
roundPoints=0;
}
}
} // end of game loop

if(compTotal>= 100)
{
System.out.println("The computer wins!");
}
else if(humanTotal>= 100)
{
System.out.println("You win!");
}
}

}```
thanks a lot everyone, i appreciate any help i get on this, i really am having problems which i feel like are the dumbest issues ever, and I'm probably going to feel a lot worse when I find out how careless my mistakes were.

2. Member
Join Date
Feb 2011
Posts
2
Rep Power
0
heres the specs that might have gotten cut off

Using the PairOfDice class, deisgn and implement a class to play a game called Pig. In this game, the user competes against the computer. On each turn, the player rolls a pair of dice and adds up his or her points. Whoever reaches 100 first, wins. If a player rolls a 1, he or she loses all points for that round and the dice go to the other player. If a player rolls two 1s in one turn, the player loses control of the dice. The player may voluntarily turn over the dice after each roll. So the player must decide to either roll again (be a pig) and risk losing points, or give up the dice, possibly letting the other player win. Set up the computer player that it always gives up the dice after getting 20 or more points in a round.

3. Senior Member
Join Date
Jan 2011
Location
Bangalore, India
Posts
102
Rep Power
0
First of all I'm not so sure about the rules of this game, but from your comments it seems like when two 1's turn up, then it's the round point which is to be made zero and not the total point.

So in the first if condition, you should remove the line which makes TotalPoints to 0.

And again from your comments it seems like TotalPoints should be calculated when the player voluntarily discontinue.

Java Code:
```if(askContinue != 1)
{
TotalPoints += roundPoints;
break;
}//end```
Now you have to modify this part
Java Code:
```if (humanTurn=true)
{
humanTotal += roundPoints; //this is not needed
humanTurn=false; //I dont understand why you are setting it to false. I think if you set it to false, human and computer will play alternate rounds
roundPoints=0;
}
else//computer got round
{
compTotal+=roundPoints;
humanTurn=true;
roundPoints=0;
}```
And I don't get this part in first if condition
Java Code:
`humanTurn=false;`
Instead it should be
Java Code:
`humanTurn=!humanTurn;`

4. Member
Join Date
Apr 2011
Location
United Arab Emirates
Posts
1
Rep Power
0

анаболически

Доброго времени суток!

Скоро лето,и многие хотят привести свое тело в порядок.
На этом сайте, dopingshop.ru можно купить
ПРЕПАРАТЫ для наращивания мышечной массы
и спортивное питание для восстановления после тренировок

купить стероиды в киеве

5. Member
Join Date
Jan 2014
Location
Eritrea
Posts
1
Rep Power
0

Мастер татуаж

перманентный макияж брови растушевка под карандаш
лучший мастер по перманентному макияжу губы

Частный мастер Марина Флерко есть профессионалом своего дела. Она получила художественное образование, получила необходимую подготовку. Мастер больше 6 лет работает в сфере татуажа. За это время она провела около трёхсот процедур.
Все клиенты, пользовавшиеся услугами данного мастера, остались целиком довольными. Потому как она применят исключительно индивидуальный подход к любому своему клиенту, предлагает оптимальные цены, постоянно проводит разнообразные акции и предлагает скидки постоянным клиентам. Бесплатные советы и профессиональная поддержка гарантируется до и после проведения мероприятия. Все это создаёт атмосферу доверия, удобства и понимания между клиентами и мастером.
За услугами к Марине Флерко приходят люди очень разного возраста. Но их объединяет единое желание – выглядеть больше привлекательнее, они хотят стать совершеннее и красивей. Марина может выполнить все их пожелания в области внешности. Благодаря её услугам клиентки чувствуют себя самыми прекрасными и счастливыми.
Мастер прошла необходимое обучение татуажу в лучших студиях Минска и Питера, закончила БГПУ им. М.Танка (г. Минск, Беларусь) на кафедре изобразительного искусства и черчения.

фото перманентный макияж
какая техника татуажа бровей мне подойдет

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•