Making a Pig Game using Object Oriented Programming (Java) - java

Hey guys so I made a Pig Game in Java for my CS project. I didn't have too much trouble with it because I only used one class. However, my professor now is making us implement OOP, and I'm having a lot of trouble. Here is my working Pig Game:
package edu.bsu.cs121.zmbarnes;
import java.util.Random;
import java.util.Scanner;
public class PigGame {
public static void main(String[] args) {
int player1TurnScore = 0;
int player1TotalScore = 0;
int player2TurnScore = 0;
int player2TotalScore = 0;
int dice;
int dice2;
String input = "r";
char repeat;
Scanner keyboard = new Scanner(System.in);
Random diceRoll = new Random();
System.out.println("Welcome to the game of Pig!\n");
while(player1TotalScore < 100 || player2TotalScore < 100){
// human's turn
System.out.println();
System.out.println("It is Player 1's turn.");
do{
dice = diceRoll.nextInt(6) + 1;
System.out.println("You rolled a " + dice);
if(dice == 1){
player1TurnScore = 0;
System.out.println("You lose your turn!");
System.out.println("Your total score is " + player1TotalScore);
break;
}else{
player1TurnScore += dice;
System.out.println("Your turn score is " + player1TurnScore);
System.out.println("And your total score is " + player1TotalScore);
System.out.println("If you hold, " + player1TurnScore + " points will be added to your total score.");
System.out.println("Enter 'r' to roll again, or 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h'){
break;
}
}
}while(input.equalsIgnoreCase("r") || dice != 1);
player1TotalScore += player1TurnScore;
System.out.println("Your score is " + player1TotalScore);
player1TurnScore = 0;
if(player1TotalScore >= 100){
System.out.println("Your total score is " + player1TotalScore);
System.out.println("PLAYER 1 WINS!");
break;
}
// Player 2's turn
System.out.println();
System.out.println("It is Player 2's turn.");
do{
dice2 = diceRoll.nextInt(6) + 1;
System.out.println("You rolled a " + dice2);
if(dice2 == 1){
player2TurnScore = 0;
System.out.println("You lose your turn!");
System.out.println("Your total score is " + player2TotalScore);
break;
}else{
player2TurnScore += dice2;
System.out.println("Your turn score is " + player2TurnScore);
System.out.println("And your total score is " + player2TotalScore);
System.out.println("If you hold, " + player2TurnScore + " points will be added to your total score.");
System.out.println("Enter 'r' to roll again, or 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h'){
break;
}
}
}while(input.equalsIgnoreCase("r") || dice2 != 1);
player2TotalScore += player2TurnScore;
System.out.println("Your score is " + player2TotalScore);
player2TurnScore = 0;
if(player2TotalScore >= 100){
System.out.println("Your total score is " + player2TotalScore);
System.out.println("PLAYER 2 WINS!");
break;
}
}
keyboard.close();
}
}
I must use a Dice class with a roll() method, a Player class with void takeTurn(), void bankPoints(), void makeChoice(), and boolean hasWon() methods, a GameOfPig class with , and Project class with void play() method, and the main Project class with main().
I'm just having trouble conceptualization how I can move my code into those methods so the game will work the exact same way. Any help would be appreciated!

I'm also new to OOD. My brief answer is highly borrowed from your code. I hope other one could correct me. Any suggestion is appreciated.
public class PigGame {
Dice dice;
Player player1;
Player player2;
public PigGame() {
this.player1 = new Player("Player1");
this.player2 = new Player("Player2");
this.dice = new Dice();
}
public void play() {
while (!player1.hasWon() && !player2.hasWon()) {
player1.takeTurn(dice);
if (!player1.hasWon())
player2.takeTurn(dice);
}
if (player1.hasWon()) {
System.out.println("Player1 won!");
} else {
System.out.println("Player2 won!");
}
}
public static void main(String[] args) {
PigGame pg = new PigGame();
pg.play();
}
}
class Dice {
private static Random diceRoll = new Random();
public int roll() {
return diceRoll.nextInt(6) + 1;
}
}
class Player {
private int currentRoundScore = 0;;
private int totalScore = 0;
private String playerName;
public Player(String name) {
this.playerName = name;
}
public void takeTurn(Dice dice) {
currentRoundScore = 0;
System.out.println("-------It's " + playerName + "'s turn.--------");
Scanner keyboard = new Scanner(System.in);
String input = "r";
int diceValue = 0;
do {
diceValue = dice.roll();
System.out.println("You rolled a " + diceValue);
if(diceValue == 1){
currentRoundScore = 0;
System.out.println("You lose your turn!");
System.out.println("Your total score is " + totalScore);
break;
}else{
currentRoundScore += diceValue;
System.out.println("Your turn score is " + currentRoundScore);
System.out.println("If you hold, " + currentRoundScore + " points will be added to your total score. And your total score would be " + currentRoundScore + totalScore);
System.out.println("Enter 'r' to roll again, or 'h' to hold.");
input = keyboard.nextLine();
char repeat = input.charAt(0);
if(repeat == 'h'){
break;
}
}
} while (input.equalsIgnoreCase("r") || diceValue != 1);
bankPoints();
}
public boolean hasWon() {
return totalScore >= 100;
}
public void bankPoints() {
totalScore += currentRoundScore;
System.out.println(playerName + "'s total score is " + totalScore + "\n");
}
}

Related

My pig dice game in JAVA won't save each player's score and the game doesn't stop even after reaching the score

My pig dice game for my computer science class won't save each individual score after each turn, and my game won't stop even after a player reaches the max score( I know boo leans are the cause but, I don't know what else to use). Also when a player declines to roll again the score goes back to zero. If anyone help me with this, it would be really nice!! Thank youu.
import java.util.*;
import java.util.Random;
public class PigDiceGamebyJian {
public static Scanner sc = new Scanner(System.in);
public static Random gen = new Random();
public static void main(String[] args) {
//char repeat;
System.out.println(" Welcome to the Pig Dice Game ");
System.out.println("This game requires two players");
System.out.println("How to play: each player will take turn rolling the dice (adding up the turns) until the sum is 30");
System.out.println("First one to get to 30 wins, though if on a turn, if you roll a 1, ");
System.out.println("you will give the dice to the other player, and you will not add anything to your score because 1 = 0");
System.out.println("Enough with the boring rules.");
String p1 = getName();
String p2 = getName();
System.out.println("Hello " + p1 + " and " + p2 + ".");
System.out.println("Please enter a score that you would like to play up to");
final int fin = sc.nextInt();
System.out.println(p1 + " will be going first.");
int p1score = roll(p1, 0, fin);
int p2score = roll(p2, 0, fin);
while (p1score < fin && p2score < fin ) {
p1score += roll(p1, 0, fin);
p2score += roll(p2, 0, fin);
}
}
private static int roll(String player, int score, int fin) {
boolean go = true;
int counter = 0;
while(go) {
int dice = gen.nextInt(6) + 1;
if (dice == 1) {
System.out.println(player + " You rolled 1, your turn is over.");
System.out.println(player + " your total is " + counter);
return 0;
}
System.out.println(player + " you rolled a " + dice);
counter = counter + dice;
System.out.println(player + " Your turn score is " + counter + " Do you want to roll again? (y)es (n)o");
String ans = sc.next();
if (ans.equals("n")) {
go = false;
System.out.println(player + " your score is " + score);
return score;
}
if (score > fin) {
go = false;
System.out.println(player + " you've won the PIG DICE GAME!!");
}
}
return score;
}
private static String getName() {
System.out.println("Enter the name for a player.");
String player = sc.next();
return player;
}
}
There is a logical flaw in your program. You are calling your roll function with a score = 0 as your parameter.
int p1score = roll(p1, 0, fin);
int p2score = roll(p2, 0, fin);
while (p1score < fin && p2score < fin ) {
p1score += roll(p1, 0, fin);
p2score += roll(p2, 0, fin);
}
In your roll method, you either return 0 or you return score which is 0 everytime. So your p1score and p2score which is determinted based on what the roll function returns will both always forever be 0.
This is why your game doesn't stop because it is stuck in the while loop.
You need to change the roll function to return the score + the value that you have rolled.

trying to understand my error in my pig java game

I am working on my final project for my intro to java class and i am having a hard time understanding the errors in my project and why it will not run if you could tell me why i would greatly appreciate it
public static void main(String[] args) {
Scanner scanner1;
int dice, dice2;
int pScore, cScore = 0;
int pTotalScore = 0;
int cTotalScore = 0;
final int maxScore = 750;
String input = "R";
String input2 = "R";
char repeat;
Random randomNumbers = new Random();
System.out.println("Welcome to Our version of the dice game Pig");
System.out.println("Here are the instructions");
System.out.println("On a turn, the player or computer rolls the die repeatedly");
System.out.println("Until either a 1,7,12, or 17 is rolled");
System.out.println("or the player or computer holds");
System.out.println("If a 1,7,12, or 17 is rolled, that player's turn ends");
System.out.println("and no points are earned");
System.out.println("If the player chooses to hold, all of the points rolled during");
System.out.println("that turn are added to his or her score.");
System.out.println("First player to 750 points or more WINS!");
System.out.print("\nPlease enter your name: ");
scanner1 = new Scanner(System.in);
String pName = scanner1.nextLine();
System.out.print("\nI Hope You have fun," + pName);
do { // run at least once. Start of loop
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.printf("%s you rolled a %d %n", pName, dice);
if (dice == 1 || dice == 7 || dice == 12 || dice == 17) // if these numbers, end
{
pScore = 0;
System.out.println("Turn over.");
System.out.println(" " + pName + " total is " + pScore + " ");
break;
} else { // else ask for re-roll
pScore = dice;
pTotalScore += pScore;
System.out.print(+pScore + " Your turn total is " + pTotalScore + " ");
System.out.print("Enter (R) to roll or (H)to hold: ");
input = scanner1.nextLine();
repeat = input.charAt(0);
}
if (repeat != 'R') { // if something other than R, end
break;
}
} while (pTotalScore < 750 || cTotalScore < 750); // allow repeat so long as scores are less than 750
if (repeat == 'H') {
System.out.println("Turn over.");
System.out.print("Current score: " + pname + " has " + pTotalScore);
System.out.println("The Computer has " + cTotalScore);
break;
}
while (input.equalsIgnoreCase("R"));
if (pTotalScore >= maxScore) {
System.out.println("Your total Score is " + totalScore);
System.out.println(+pname + "WINS!");
break;
}
System.out.println();
System.out.println("It is the Computer's turn.");
do {
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The Computer rolled: " + dice2);
if (dice2 == 1 || dice2 == 7 || dice2 == 12 || dice2 == 17) {
cScore = 0;
System.out.print("Turn over");
System.out.println("The Computer total is " + cTotalScore);
break;
} else {
cScore = dice2;
cTotalScore += cScore;
System.out.print("The Computer's total is " + cTotalScore + " ");
System.out.print("Enter (r) to Roll or (H)to Hold: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
if (repeat == 'H') {
System.out.println("Turn over");
System.out.print("Current score:" + pName + " has " + pTotalScore);
System.out.println(", The Computer has " + cTotalScore);
break;
}
} while (input2.equalsIgnoreCase("R"));
if (cTotalScore >= maxScore) {
System.out.println("The Computer's score is " + cTotalScore + "\n");
System.out.println("The Computer wins!!!!");
System.out.printl("Run The uprisng has begun!!!!!!");
break;
}
Final3.java:112: error: reached end of file while parsing } ^ 1 error
now the problem is i get the error basically means im missing a } but i cant see where it would be nd no matter where i put it it still says
Final3.java:112: error: reached end of file while parsing } ^ 1 error
You have one while loop that does nothing - while (input.equalsIgnoreCase("R")); - and you didn't close your main method. Add } at the end.
Add a closing brace "}" in the end.I hope this will solve your purpose.

Rock paper scissors, play again?

For my assignment I'm supposed make the program rock paper scissors which I figured that out my main problem is I can't get the program to play again right or get the program to calculate the game scores correctly pleas help I'm going crazy trying to figure this out?!
//Tayler Dorsey
import java.util.Random;
import java.util.Scanner;
public class PRS {
static Scanner keyboard = new Scanner(System. in );
public static void instructions() {
System.out.println("This is the popular game of paper, rock, scissors. Enter your\nchoice by typing the word \"paper\", the word \"rock\" or the word\n\"scissors\". The computer will also make a choice from the three\noptions. After you have entered your choice, the winner of the\ngame will be determined according to the following rules:");
System.out.println("Paper wraps rock (paper wins)\nRock breaks scissors (rock wins)\nScissors cuts paper (scissors wins)");
System.out.println("If both you and the computer enter the same choice, then the game is tied.");
}
public static int playGame() {
int ties = 0, wins = 0, losts = 0;
String userchoice, computerchoice;
System.out.println("Enter your choice: ");
userchoice = keyboard.next();
computerchoice = computerChoose();
System.out.println("You entered: " + userchoice);
System.out.println("Computer choose: " + computerchoice);
if ((userchoice.equals("paper") && computerchoice.equals("paper")) || (userchoice.equals("rock") && computerchoice.equals("rock")) || (userchoice.equals("scissors") && computerchoice.equals("scissors"))) {
System.out.println("IT'S A TIE!");
ties++;
return 3;
} else if ((userchoice.equals("paper") && computerchoice.equals("rock")) || (userchoice.equals("rock") && computerchoice.equals("scissors")) || (userchoice.equals("scissors") && computerchoice.equals("paper"))) {
System.out.println("YOU WIN!");
wins++;
return 1;
} else {
System.out.println("YOU LOSE!");
losts++;
return 2;
}
}
public static String computerChoose() {
Random generator = new Random();
String[] answer = new String[3];
answer[0] = "paper";
answer[1] = "rock";
answer[2] = "scissors";
return answer[generator.nextInt(3)];
}
public static void main(String[] args) {
String play;
Scanner keyboard = new Scanner(System. in );
System.out.println("The Game of Paper, Rock, Scissors");
System.out.println("Do you need instructions (y or n)?");
String help = keyboard.nextLine();
if (help.equals("y")) instructions();
int result = playGame();
System.out.println("Play again (y or n)?");
play = keyboard.nextLine();
if (play.equals("y"));
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
do {} while (play == "y"); {
playGame();
int count = 0;
count++;
}
}
}
There are two issues here:
The code isn't inside the do-while loop, it's after it.
String equality should be checked with equals not with ==.
So:
int count = 0;
do { // Note the code inside the do-while block
playGame();
count++;
} while (play.equals("y")); // Note the use of equals
Do the following:
do {
play = keyboard.nextLine();
if (play.equals("y")){
}
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
} while (play.equals("y"));
In order to calculate the games scores make those variable global.
public class PRS {
static Scanner keyboard = new Scanner(System. in );
int ties = 0, wins = 0, losts = 0;

Need guidance on a simple pig game that terminates and ends

I am trying to create a simple Pig game.. The problem that i have is that the program terminates.
For example, when i run it, entering two players and two names works perfectly, and so does the first round.. as soon as i enter n, and the turn goes to player 2, the program just stops.. I would like it to continue until the score is reached..
Below is my code.. I would appreciate ANY help.. I am totally lost on this one..
And yes... I am a beginner..
Thank you!!
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class PigGame {
public static void main(String[] args) {
ArrayList<Player> users = initialize();
for (Player p : users) {
System.out.println(p.getNick() + "'s turn!");
System.out.println("Your score is: " + p.getScoreTotal() + "!");
takeTurn(p);
if (p.getScoreTotal() >= 100) {
System.out.println(p.getNick() + "wins! Congratulations");
return;
}
}
}
private static ArrayList<Player> initialize() {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Pig!");
System.out.println("How many will play the game?");
int qusers = sc.nextInt();
sc.nextLine();
ArrayList<Player> users = new ArrayList();
for (int i = 1; i <= qusers; i++)
{
System.out.println("Enter the name of player " + i + ":");
users.add(new Player(sc.nextLine(), 1, 6));
}
return users;
}
private static void takeTurn(Player p) {
String input = "";
int currentScore = 0;
Scanner sc = new Scanner(System.in);
do {
p.rollDice();
currentScore += p.getDieWorth();
System.out.println(p.getNick() + "'s dice rolled " + p.getDieWorth());
if (p.getDieWorth() != 1) {
System.out.println("Your score is: " + currentScore + " for this round.");
System.out.println("Do you want to roll again? (j/n)");
input = sc.nextLine();
} else {
System.out.println("Sorry");
currentScore = 0;
}
}
while ((input.equals("j")) && (p.getDieWorth() != 1));
p.increaseScore(currentScore);
}
}
Here's your code.
for (Player p : users) {
System.out.println(p.getNick() + "'s turn!");
System.out.println("Your score is: " + p.getScoreTotal() + "!");
takeTurn(p);
if (p.getScoreTotal() >= 100) {
System.out.println(p.getNick() + "wins! Congratulations");
return;
}
}
This only goes through the users once. for goes through each user and then it's done. You need a while loop.
//this is somewhat messy, but it gets the point across
Player p = users.get(0);
int playerIndex = users.size();
while(p.getScoreTotal() < 100) {
if(playerIndex == users.size()) {
playerIndex = 0;
}
p = users.get(playerIndex);
playerIndex++;
System.out.println(p.getNick() + "'s turn!");
System.out.println("Your score is: " + p.getScoreTotal() + "!");
takeTurn(p);
}
System.out.println(p.getNick() + "wins! Congratulations");
return;

exit or continue the game in java

afer program outputs a winner, i ask if user wants to play again or exit but for some reason scanner doesn't read this input(continue or not). I even put prompt for continuation outside the while loop but still no luck:
"|XXX|
| O |
| O|
Player X is a winner!
Do you want to play again? Enter Y for yes or N for no!
BUILD SUCCESSFUL (total time: 26 seconds)
"
This is code:
public class TicTacToeRunner
{
public static void main(String[] args)
{
int row;
int column;
Scanner in = new Scanner(System.in);
TicTacToe game = new TicTacToe();
String player = "X";
boolean done = false;
int moveCounter = 0;
String answer;
int noMovement = -2;
int toQuit = -1;
int movesToCheckWins = 5;
int movesToCheckTies = 7;
while (!done)
{
do
{
row = column = noMovement;
System.out.print("\n" + game);
System.out.print("Please make a move " + (moveCounter + 1) + "(" + player + ")\nRow for " + player.toUpperCase() + " (or -1 to exit): ");
if (in.hasNextInt()) //check if input is an integer
{
row = in.nextInt();
}
if (row == toQuit) //if entered -1 quit the game
{
done = true;
System.out.println("Player " +player.toUpperCase() + " ended the game !");
System.exit(0); //game termination
}
else
{
System.out.print("Column for " + player.toUpperCase() + ": ");
if(in.hasNextInt()) //check if input is an integer
{
column = in.nextInt();
}
}
}while(!game.checkForValidMove(row, column)); //end of do-while loop if checkForValidMove is false
moveCounter++;
game.set(row, column, player);
if (moveCounter >= movesToCheckWins) //check wins after 5 moves
{
if (game.checkForWin(row, column, player)) //if a winner
{
done = true;
System.out.println("\n" + game);
System.out.println("Player " + player.toUpperCase() + " is a winner!");
}
}
if (moveCounter >= movesToCheckTies) //Check for ties after 7 moves
{
if (game.checkForEarlyTie()) //check for early tie
{
done = true;
System.out.println("\n" + game);
System.out.println("Tie Game after " + moveCounter + " moves!");
}
}
// Switching players
if (player.equals("X"))
{
player = "O";
}
else
{
player = "X";
}
}
System.out.println("Do you want to play again? Enter Y for yes or N for no!");
answer = in.nextLine();
answer = answer.toLowerCase(); //change input to lowercase for bullet proofing
if(answer.equals("y"))
{
done = false;
player = "X";
moveCounter = 0;
game.resetTheGame();
}
else
{
System.exit(0); //program termination
}
}
}
using a do while loop. your work is easy..
import java.util.Scanner;
public class TicTacToeRunner {
public static void main(String[] args) {
int row;
int column;
Scanner in = new Scanner(System.in);
TicTacToe game = new TicTacToe();
String player = "X";
boolean done = false;
String choice = "";
int moveCounter = 0;
String answer;
int noMovement = -2;
int toQuit = -1;
int movesToCheckWins = 5;
int movesToCheckTies = 7;
do{
while (!done) {
do {
row = column = noMovement;
System.out.print("\n" + game);
System.out.print("Please make a move " + (moveCounter + 1) + "(" + player + ")\nRow for " + player.toUpperCase() + " (or -1 to exit): ");
if (in.hasNextInt()) // check if input is an integer
{
row = in.nextInt();
}
if (row == toQuit) // if entered -1 quit the game
{
done = true;
System.out.println("Player " + player.toUpperCase() + " ended the game !");
System.exit(0); // game termination
} else {
System.out.print("Column for " + player.toUpperCase() + ": ");
if (in.hasNextInt()) // check if input is an integer
{
column = in.nextInt();
}
}
} while (!game.checkForValidMove(row, column)); // end of do-while
// loop if
// checkForValidMove
// is false
moveCounter++;
game.set(row, column, player);
if (moveCounter >= movesToCheckWins) // check wins after 5 moves
{
if (game.checkForWin(row, column, player)) // if a winner
{
done = true;
System.out.println("\n" + game);
System.out.println("Player " + player.toUpperCase() + " is a winner!");
}
}
if (moveCounter >= movesToCheckTies) // Check for ties after 7 moves
{
if (game.checkForEarlyTie()) // check for early tie
{
done = true;
System.out.println("\n" + game);
System.out.println("Tie Game after " + moveCounter + " moves!");
}
}
// Switching players
if (player.equals("X")) {
player = "O";
} else {
player = "X";
}
}
System.out.println("Do you want to play again? Enter Y for yes or N for no!");
choice = in.nextLine();
}while(choice.equals("y")||choice.equals("Y"));
}
}

Categories

Resources