Java program to play Pig. Pig is a two player game where the players take turns
ID: 3550563 • Letter: J
Question
Java program to play Pig.
Pig is a two player game where the players take turns repeatedly rolling a single 6 sided die. A player repeatedly rolls the die untill one of two events happen:
Either the player chooses to stop rolling, in which case the sum of that player's rolls are added to his total points; or if the player rolls a 1 at any time, all points for that turn are lost and the turn ends immediately. The first player to reach a score of at least 100 wins.
Rules: Do not use Scanner to get any sort of input, instead simulate the appropriate input values using Random. You will also need to use Random to simulate playing the game.
Explanation / Answer
please rate - thanks
partial run
import java.util.*;
public class pig {
public static void main(String[] args)
{
int player1=0,player2=0;
Random r=new Random();
while(player1<100&&player2<100)
{player1+=play(r,"player 1");
player2+=play(r,"player 2");
System.out.println(" Current score Player 1: "+player1);
System.out.println("Player 2: "+player2);
}
if(player2>player1)
System.out.println("player 2 Wins");
else
System.out.println("player 1 Win ");
}
public static int play(Random r,String person)
{boolean hold=false;
int rorh,thisturn=0,die;
System.out.println(" "+person+" rolls:");
do
{
die=r.nextInt(6)+1;
System.out.println(person+" rolled a: "+die);
thisturn+=die;
System.out.println("for a total of: "+thisturn);
if(die!=1)
{System.out.print("roll(0) or hold(1)? ");
rorh=r.nextInt(2);
System.out.println(rorh);
if(rorh==1)
hold=true;
}
}while(!hold&&die>1);
if(die==1)
thisturn=0;
return thisturn;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.