Need guidance on a simple pig game that terminates and ends - java

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;

Related

How to update data in array with user input values with java?

I am trying to create a garage with three floors and three lots on each floor. I am fairly new to java, so I am really having trouble with this. I want to ask the user if they are leaving (0) or parking (1), then which floor they were on or want to be on, and which lot they were in or want to be in. Then I want to use that data and update the array to show Reserved for that spot. But what I have isn't working. Any help would be appreciated.
import java.util.Scanner;
public class Parking {
public static void main(String[] args) {
String parkingspace[][] = new String[3][3];
for(int floor=0; floor<parkingspace[0].length; floor++) {
for(int lot=0; lot<parkingspace[floor].length; lot++) {
parkingspace[floor][lot]="Empty";
}
}
Scanner scan = new Scanner(System.in);
while(true){
for(int floor=0; floor<parkingspace[0].length; floor++) {
for(int lot=0; lot<parkingspace[floor].length; lot++) {
parkingspace[floor][lot]="Empty";
System.out.print("Floor "+floor + ": Lot #" +lot +": [" + parkingspace[floor][lot]+"] ");
}
System.out.println();
}
System.out.println("Are you leaving(0) or parking(1)?");
int input = scan.nextInt();
System.out.println("Which floor (0, 1, 2)?");
int floor = scan.nextInt();
System.out.println("Which lot (0, 1, 2)?");
int lot = scan.nextInt();
if(input==1) {
if(parkingspace[floor][lot].equals("Empty")) {
if(input==1) {
parkingspace[floor][lot]="Reserved";
System.out.print("Floor "+ floor + ": Lot #" +lot +": [" + parkingspace[floor][lot]+"] ");
}
}else if(input==0){
parkingspace[floor][lot]="Empty";
System.out.print("Floor "+ floor + ": Lot #" +lot +": [" + parkingspace[floor][lot]+"] ");
}
}
}
}
You are close. You need to delete the part where you reset all the parking spaces. Also, you probably don't need to print anything after the user has input their choice.
For extra credit, you need to add error checking. What if the user enters space #12345? Or "Hello"? You should handle these cases.
Here's your code, slightly modified:
public static void main(String[]args) {
String parkingspace[][] = new String[3][3];
// Make these variables to be consistent
final String empty = "EMPTY";
final String reserved = "RSRVD";
// Initialize
for (int floor = 0; floor < parkingspace.length; floor++) {
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
parkingspace[floor][lot] = empty;
}
}
Scanner scan = new Scanner(System.in);
while (true) {
// Print the parking lot
for (int floor = 0; floor < parkingspace.length; floor++) {
System.out.print("Floor " + floor + ": ");
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
System.out.print("Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
System.out.println();
}
// Get user input
System.out.println("Are you leaving(0) or parking(1)?");
int input = scan.nextInt();
System.out.println("Which floor (0, 1, 2)?");
int floor = scan.nextInt();
System.out.println("Which lot (0, 1, 2)?");
int lot = scan.nextInt();
// Update parking lot
if (input == 1 && parkingspace[floor][lot].equals(empty)) {
parkingspace[floor][lot] = reserved;
}
else if (input == 0 && parkingspace[floor][lot].equals(reserved)) {
parkingspace[floor][lot] = empty;
}
}
}
You have a redundant if(input == 1) check. It could just be:
if (input == 1 && parkingSpace[floor][lot].equals("Empty")) {
parkingSpace[floor][lot] = "Reserved";
}
Also, your code works for me. I did have to add several brackets to close off methods and the class, though.
import java.util.Scanner;
public class Parking {
public static void main(String[] args) {
String parkingspace[][] = new String[3][3];
for (int floor = 0; floor < parkingspace[0].length; floor++) {
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
parkingspace[floor][lot] = "Empty";
}
}
Scanner scan = new Scanner(System.in);
while (true) {
for (int floor = 0; floor < parkingspace[0].length; floor++) {
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
parkingspace[floor][lot] = "Empty";
System.out.print(
"Floor " + floor + ": Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
System.out.println();
}
System.out.println("Are you leaving(0) or parking(1)?");
int input = scan.nextInt();
System.out.println("Which floor (0, 1, 2)?");
int floor = scan.nextInt();
System.out.println("Which lot (0, 1, 2)?");
int lot = scan.nextInt();
if (input == 1) {
if (parkingspace[floor][lot].equals("Empty")) {
if (input == 1) {
parkingspace[floor][lot] = "Reserved";
System.out.print(
"Floor " + floor + ": Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
} else if (input == 0) {
parkingspace[floor][lot] = "Empty";
System.out.print(
"Floor " + floor + ": Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
}
}
}
}

Called function result

Here in main method I want to call num value from number() and result from finger()
So I can use them in main method by adding:
if (the sum was even) {
print out even if (the user chose evens) { the user wins }
else { the computer wins }
Here is my Game class:
import java.util.*;
public class Game {
public static void main(String[] args) {
number();
finger();
/*
if (the sum was even) {
print out even if (the user chose evens) { the user wins }
else { the computer wins }
*/
}
public static void number() {
Scanner input = new Scanner(System.in);
System.out.print("Lets's play a Game \"Odd and Even\" " +
"\nWhat is your name?\t ");
String name = input.nextLine();
System.out.print("Hi " + name +" Welcome to the Game, Please
choose (O)dds or (E)vens ?");
String num = input.next();
if (num.equalsIgnoreCase("O") || num.equalsIgnoreCase("E")) {
if (num.equalsIgnoreCase("E")) {
System.out.println(name + " has choosen Evens! The computer will be Odds");
} else {
System.out.println(name + " has choosen Odds ! The Computer will be Even");
}
} else {
System.out.println("Please choose the correct one");
}
}
public static void finger() {
Scanner input = new Scanner(System.in);
System.out.print("How many fingers do you put out?\t");
int fing = input.nextInt();
Random ran = new Random();
int computer = ran.nextInt(9);
System.out.println("The Computer plays " + computer);
int result = fing + computer;
System.out.println(fing + " + " + computer + " = " + result);
if (result % 2 == 0) {
System.out.print(" .........is Even!");
} else {
System.out.print("........ is Odd!");
}
}
}

I cant figure out to implement -1 as a sentinel value using a while loop.

I can't figure out to implement -1 as a sentinel value using a while loop. Note that the program needs to be running all times except when the users enter the value -1 it should stop. Technically the program should stop at any time when the user enters the sentinal value(-1).
import java.util.Scanner;
import java.util.Random;
public class Multi {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int randomOne, randomTwo, product, userInput;
while(true) {
randomOne = Math.abs(rand.nextInt()%10);
randomTwo = Math.abs(rand.nextInt()%10);
product = randomOne * randomTwo;
System.out.println("How much is " + randomOne + " times " + randomTwo
+ "?");
userInput = scan.nextInt();
if (product == userInput) {
System.out.println("Very Good!");
}
else {
while (product != userInput) {
System.out.println("No. Please try again.");
System.out.println("How much is " + randomOne + " times " +
randomTwo + "?");
userInput = scan.nextInt();
if (product == userInput) {
System.out.println("Very Good!");
}
}}
}
}
}
So at all times when we ask input from the user, if they enter -1 the program should stop.
You could check if the value is -1 upon every iteration and then write a break statement, but below is a slightly cleaner implementation.
import java.util.Scanner;
import java.util.Random;
public class Multi {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int randomOne, randomTwo, product, userInput;
boolean playingGame = true;
while (playingGame) {
randomOne = Math.abs(rand.nextInt() % 10);
randomTwo = Math.abs(rand.nextInt() % 10);
product = randomOne * randomTwo;
System.out.println("How much is " + randomOne + " times " + randomTwo + "?");
userInput = scan.nextInt();
while (userInput != -1 && product != userInput) {
System.out.println("No. Please try again.");
System.out.println("How much is " + randomOne + " times " +
randomTwo + "?");
userInput = scan.nextInt();
}
if (product == userInput) {
System.out.println("Very Good!");
} else {
playingGame = false;
}
}
scan.close();
}
}

Making a Pig Game using Object Oriented Programming (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");
}
}

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