problems with dice game - java

whenever the code goes through the compiler it prints out the same number an infinite amount of times, i need it to compile random numbers several times. I tried to use the while loop to print out more times. However it just prints out the same number. The purpose of the game is for two players (and AI and one person), to compete to first reach 100 points, whenever a player gets two 1's the points will reset.
class piggame {
public static void main(String[] args) {
Dice d1 = new Dice();
d1.rolls();
int dave = d1.rolls();
Dice d2 = new Dice();
d2.rolls();
int joe = d2.rolls();
Dice d3 = new Dice();
d3.rolls();
int kurt = d1.rolls() + d2.rolls();
int sum1 = d1.rolls() + d2.rolls();
sum1 += d1.rolls() + d2.rolls();
while (dave != 1 && joe != 1){
System.out.println("you have rolled " + kurt);
}
}
}
class Dice {
public int rolls() {
Random r = new Random();
return r.nextInt(6) +1;
}
}

You should call rolls() inside loop. At snippet you pasted rolls are made once before the loop and then inside it you just printing this one roll result (which indeed will be infinite loop OR won't execute in case of rolls being ones right away, as rolls are never made again when you inside this while).

This code is not perfect, but it should solve your problem.
public static void main(String[] args) {
int dave = 0;
int joe = 0;
int kurt = 0;
while (dave != 1 && joe != 1){
Dice d1 = new Dice();
d1.rolls();
dave = d1.rolls();
Dice d2 = new Dice();
d2.rolls();
joe = d2.rolls();
Dice d3 = new Dice();
d3.rolls();
kurt = d1.rolls() + d2.rolls();
int sum1 = d1.rolls() + d2.rolls();
sum1 += d1.rolls() + d2.rolls();
System.out.println("you have rolled " + kurt);
}
}

import java.util.Random;
class PigGame
{
public static void main(String[] args)
{
int dave = 0;
int joe = 0;
int kurt = 0;
int roll_count = 0;
while (dave != 1 && joe != 1)
{
System.out.println("-----------------------------------------------");
System.out.println("Roll number: " + roll_count++);
System.out.println("-----------------------------------------------");
dave = new Dice().roll();
joe = new Dice().roll();
kurt = new Dice().roll();
System.out.println("Dave rolled: " + dave);
System.out.println("Joe rolled: " + joe);
System.out.println("Kurt rolled: " + kurt);
System.out.println("");
}
}
}
class Dice {
public int roll() { return new Random().nextInt(6) + 1; }
}

I don't think you're providing a solution to the given requirement:
Two players (but you have included three players - Joe, Dave and Kurt).
If a player rolls two consecutive ones, that player's score is reset (e.g. if player Dave rolls a one and then rolls another one on his next turn, his score is reset to 0).
In my previous answer, I was only trying to tidy up your code. I wasn't looking at the actual requirement.
You haven't mentioned if a player gets a single point per roll of the dice, or if the value of what they roll is added to their score. I'm going to assume it's the latter.
You should include another class called "Player". The Player class would contain variables to store what the current roll was, what the previous roll was, and the player's current score. It should also include methods to roll the dice, check if the player has reached a score of 100, check if a player has rolled two consecutive ones.
Here's a very simple implementation (that will tell you which player wins at the end, and how many points the winner has won by):
import java.util.Random;
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class PigGame
{
public static void main(String[] args)
{
Player player1 = new Player("Dave");
Player player2 = new Player("Joe");
int roll_count = 0;
while (!player1.reachedFinishingScore() && !player2.reachedFinishingScore())
{
int p1_roll = player1.roll();
int p2_roll = player2.roll();
System.out.println("-----------------------------------------------------");
System.out.println("Roll number: " + roll_count++);
System.out.println("-----------------------------------------------------");
System.out.println(player1.get_name() + " rolled: " + p1_roll + ". Total Score: " + player1.get_score());
System.out.println(player2.get_name() + " rolled: " + p2_roll + ". Total Score: " + player2.get_score());
System.out.println("");
}
if (player1.get_score() == player2.get_score())
System.out.println("It was a draw!");
else if (player1.get_score() > player2.get_score())
System.out.println(player1.get_name() + " wins by " + (player1.get_score() - player2.get_score()) + " points!");
else
System.out.println(player2.get_name() + " wins by " + (player2.get_score() - player1.get_score()) + " points!");
System.out.println("");
}
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Dice {
public int roll() { return new Random().nextInt(6) + 1; }
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Player
{
private String name; // Player's name.
private int prev_roll = 0; // Value of Player's previous roll.
private int curr_roll = 0; // Value of Player's current roll.
private int score = 0; // The Player's score.
public Player(String name) { this.name = name; }
public int roll()
{
int curr_roll = new Dice().roll();
this.prev_roll = this.curr_roll; // Make previous roll value of last current roll.
this.curr_roll = curr_roll; // Set value of current roll to what was just rolled.
this.score += curr_roll;
if (rolledTwoOnes()) this.score = 0;
return curr_roll;
}
private boolean rolledTwoOnes() { return (this.prev_roll == 1 && this.curr_roll == 1); }
public boolean reachedFinishingScore() { return this.score >= 100; }
public int get_score() { return score; }
public String get_name() { return this.name; }
}
The above implementation could be improved by not "hard-coding" player1 and player2. Instead, you could use an array of players, which would make it easier to not limit the number of players (i.e. you could have 100 players).

Okay, last one (I promise):
import java.util.Random;
import java.util.Arrays;
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Config
{
public static final int NUM_OF_PLAYERS = 10;
public static final int NUM_OF_DICE_FACES = 6;
public static final int WINNING_SCORE = 100;
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class PigGame
{
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void create_players(Player[] p, int num_players)
{
for (int i = 0; i < num_players; i++)
p[i] = new Player("Player " + String.format("%02d", i + 1));
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void all_players_roll_dice(Player[] p)
{
for (int i = 0; i < p.length; i++)
p[i].roll();
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static boolean no_winners(Player[] p)
{
int i = 0;
boolean bWinner = false;
while (i < p.length && (bWinner = !p[i].reachedFinishingScore()))
i++;
return bWinner;
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void display_roll_details(Player[] p, int current_roll)
{
System.out.println("\n--------------------------------------------------------");
System.out.println("CURRENT ROLL: " + (current_roll + 1));
System.out.println("--------------------------------------------------------");
for (int i = 0; i < p.length; i++)
System.out.println(p[i].get_name() + " rolled: " + p[i].get_roll() +
". Score: " + p[i].get_score());
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void display_final_scores(Player[] p, int roll_count)
{
System.out.println("\n\n**********************************************************");
System.out.println("FINAL SCORES AFTER " + roll_count + " ROLLS (HIGHEST TO LOWEST):");
System.out.println("**********************************************************\n");
for (int i = 0; i < p.length; i++)
{
Arrays.sort(p);
System.out.println(p[i].get_name() + " scored: " + p[i].get_score());
}
System.out.println("\n\nDon't be a player hater!\n\n");
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void main(String[] args)
{
Player[] players = new Player[Config.NUM_OF_PLAYERS];
create_players(players, Config.NUM_OF_PLAYERS);
int roll_count = 0;
while (no_winners(players))
{
all_players_roll_dice(players);
display_roll_details(players, roll_count++);
}
display_final_scores(players, roll_count);
}
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Dice {
public int roll() { return new Random().nextInt(Config.NUM_OF_DICE_FACES) + 1; }
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Player implements Comparable<Player>
{
private String name; // Player's name.
private int prev_roll = 0; // Value of Player's previous roll.
private int curr_roll = 0; // Value of Player's current roll.
private int score = 0; // The Player's score.
public Player(String name) { this.name = name; }
public int roll()
{
int curr_roll = new Dice().roll();
this.prev_roll = this.curr_roll; // Make previous roll value of last current roll.
this.curr_roll = curr_roll; // Set value of current roll to what was just rolled.
this.score += curr_roll;
if (rolledTwoOnes()) this.score = 0;
return curr_roll;
}
private boolean rolledTwoOnes() { return (this.prev_roll == 1 && this.curr_roll == 1); }
public boolean reachedFinishingScore() { return this.score >= Config.WINNING_SCORE; }
public int get_score() { return this.score; }
public int get_roll() { return this.curr_roll; }
public String get_name() { return this.name; }
// For sorting the array (from highest scores to lowest).
#Override
public int compareTo(Player p)
{
return ((Integer)p.get_score()).compareTo(((Integer)get_score()));
}
}
Using the above, you can easily alter the number of players, number of dice faces, and the score that needs to be reached for a win.

Related

While loop not terminating when an array equals the terminate condition array. Java. First java class please be patient. Thank you

Was wondering if there was a reason that the while loop was not terminating if the arrays equal eachother, the one condition was an array set to all 2s and then when the Die array reaches all 2s I wanted the while loop to terminate. Thank you for any help.
Stuck in the mud dice game, 2 players will roll 5 dice each, and the person with the highest total wins, if one player rolls a 2
they are stuck in the mud and unable to continue rolling for the rest of the game
import java.util.*;
public class StuckInTheMud {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is player ones name?");
String firstPlayer = keyboard.nextLine();
System.out.println("What is player twos name?");
String secondPlayer = keyboard.nextLine();
Player playerOne = new Player(firstPlayer);
Player playerTwo = new Player(secondPlayer);
while (playerOne.getDice() != playerOne.endGame() || playerTwo.getDice() != playerTwo.endGame()) // this is the while loop that wont terminate
{
pressEnterKeyToContinue(firstPlayer); // these are the turns looping
playerOne.playerTurn(firstPlayer);
pressEnterKeyToContinue(secondPlayer);
playerTwo.playerTurn(secondPlayer);
}
}
public static void pressEnterKeyToContinue(String playerName) // using a continue method so the game doesn't contine on its own
{
System.out.println("\n" + playerName + ", press Enter key when you are ready to roll!");
Scanner nextTurn = new Scanner(System.in);
nextTurn.nextLine();
}
}
import java.util.*;
public class Player { // this is the player class
private int score;
private Die[] dice = new Die[6];
private String playerName;
private int roundScore;
private int totalScore;
public Player(String playerAlias) {
playerAlias = playerName;
score = 0;
for (int i = 0; i != dice.length; i++) {
dice[i] = new Die(6);
dice[i].setValue(1);
}
}
public void playerTurn(String playerName) {
roundScore = 0;
int twoRoll = 0;
System.out.print(playerName + " it is your turn, here come the dice.\n");
for (int i = 0; i != dice.length; i++) // This for loop will add random dice roll integers into the players array
{
if (dice[i].getValue() != 2) {
dice[i].roll();
if (dice[i].getValue() != 2) {
System.out.println("For roll number " + (i + 1) + " you got a " + dice[i].getValue() + "!");
roundScore(dice[i].getValue());
} else {
System.out.println("For roll number " + (i + 1) + ", you got a 2! Die " + (i + 1) + " is now stuck in the mud!");
twoRoll = 1;
}
} else {
System.out.println("Die " + (i + 1) + " is stuck in the mud since you rolled a 2, it cannot be used for the rest of the game!");
}
}
if (twoRoll == 0) {
System.out.println("\nYour total score this round was " + getRoundScore() + ".");
totalScore(roundScore);
System.out.println(playerName + ", your total score for the game is " + getTotalScore() + "!");
} else {
System.out.println("\nSince you rolled a 2, the score for this round is 0");
roundScore = 0;
totalScore(roundScore);
System.out.println(playerName + ", your total score for the game is " + getTotalScore() + "!");
}
}
public void roundScore(int singleRoll) {
roundScore += singleRoll;
}
public int getRoundScore() {
return roundScore;
}
public void totalScore(int roundScore) {
totalScore += roundScore;
}
public int getTotalScore() {
return totalScore;
}
public Die[] getDice() {
return dice;
}
public Die[] endGame() {
Die[] endGame = new Die[6];
for (int i = 0; i != endGame.length; i++) {
endGame[i] = new Die(6);
endGame[i].roll();
endGame[i].setValue(2);
}
return endGame;
}
}
// Die Class
// 4/21/22
// Zachary Strickler
import java.util.Random;
/**
The Die class simulates a six-sided die.
*/
public class Die // this is the die class
{
private int sides; // Number of sides
private int value; // The die's value
/**
The constructor performs an initial
roll of the die.
#param numSides The number of sides for this die.
*/
public Die(int numSides) {
sides = numSides;
roll();
}
/**
The roll method simlates the rolling of
the die.
*/
public void roll() {
// Create a Random object.
Random rand = new Random();
// Get a random value for the die.
value = rand.nextInt(sides) + 1;
}
/**
getSides method
#return The number of sides for this die.
*/
public int getSides() {
return sides;
}
/**
getValue method
#return The value of the die.
*/
public int getValue() {
return value;
}
public int setValue(int setValue) {
value = setValue;
return value;
}
}
You while loop test includes
playerTwo.getDice() != playerTwo.endGame()
By using the = operator, you are saying 'are these two arrays the same array object?'. Looking at the endGame method you can see that can never be true, you are creating a new array object every time you call that method, so could never be the same one as
playerTwo.getDice().
Instead of checking to see if they are the same object, you really want to know if they have the same values. There are some other ways of doing that. I'll give you a hint, look at java.util.Arrays package.
https://www.geeksforgeeks.org/java-util-arrays-equals-java-examples/
https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
https://www.geeksforgeeks.org/compare-two-arrays-java/

Creating an array of objects but it doesn't find the symbols

I am creating an array of Players in a minigame in Java. There is a class called Players and one called Game.
In the Main we scan two names and send them to the Game
game.createPlayer(name1, name2);
and later on try to get some information back
playerArray[(game.getPlayerTurn() % 2)].getPlayerName();
The Player gets constructed in the Game as an array:
public class Game
{
private Player[] playerArray;
[...]
public void createPlayer(String name1, String name2)
{
Player[] playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}
with the Player as a standard class:
public class Player
{
private String playerName;
public Player( String playerName )
{
this.playerName = playerName;
}
public String getPlayerName()
{
return playerName;
}
}
This however returns multiple errors saying it cannot find the symbol wherever i try to find out the name of the player. Did I not properly instanciate them?
Additional code (as per request):
package oop.nimspiel;
import java.util.Scanner;
import java.util.Arrays;
public class Game
{
private int take;
private int turn;
private int playerTake;
private int playerTurn;
protected Player[] playerArray;
public Game(int turn, int playerTurn)
{
this.turn = turn;
this.playerTurn = playerTurn;
}
protected void setPlayerTake(int take)
{
this.playerTake = take;
}
public int getPlayerTake()
{
return playerTake;
}
public void incrementTurns()
{
turn = turn + 1;
playerTurn = playerTurn + 1;
}
public int getTurn()
{
return turn;
}
public int getPlayerTurn()
{
return playerTurn;
}
public void createPlayer(String name1, String name2)
{
this.playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}
public String getPlayer()
{
String playerName = playerArray[(getPlayerTurn() % 2)].getPlayerName();
return playerName;
}
public void checkTake(int take)
{
Scanner input = new Scanner(System.in);
this.take = take;
boolean rightInput = false;
do {
if (take < 1 || take > 3)
{
System.out.println("Your input was wrong, please use a number between 1 and 3.");
System.out.println("How many stones would you like to take?");
take = input.nextInt();
rightInput = false;
}
else if (stoneheap.getStones() < take) {
System.out.println("There are only " + stoneheap.getStones() + " stones left.");
System.out.println("Please take less.");
System.out.println("How many stones would you like to take?");
take = input.nextInt();
rightInput = false;
}
else
{
rightInput = true;
}
} while (rightInput == false);
}
}
and the Main:
package oop.nimspiel;
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
private int take;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String nextRound;
do
{
int maxPlayers = 2;
int startTurn = 1;
Game game = new Game ( startTurn, (1 + (int)(Math.random() * ((maxPlayers - 1) + 1)) ) );
int minStones = 20;
int maxStones = 30;
Stoneheap stoneheap = new Stoneheap((minStones + (int)(Math.random() * ((maxStones - minStones) + 1)) ) );
System.out.println("Rules: Two players take stones from a heap of 20 to 30 until there are no more left. The one to take the last stone loses. Each round you can only take between 1 - 3 stones. Have fun!"); // Rules
System.out.println("");
System.out.println("Hello Player 1, what is your name?");
String name1 = input.next();
System.out.println("");
System.out.println("Hello Player 2, what is your name?");
String name2 = input.next();
game.createPlayer(name1, name2);
System.out.println("");
System.out.println("Number of stones: " + stoneheap.getStones());
System.out.println("The first to draw is Player " + game.getPlayerTurn());
System.out.println("The game starts now!");
while (stoneheap.getStones() > 0)
{
if ((game.getPlayerTurn() % 2) > 0) // Turn Player 1
{
System.out.println("It is your turn " + playerArray[(game.getPlayerTurn() % 2)].getPlayerName() + ".");
System.out.println("How many stones would you like to take?");
int take = input.nextInt();
game.checkTake(take);
game.setPlayerTake(take);
stoneheap.currentStones();
System.out.println("There are " + stoneheap.getStones() + " stones left.");
}
else // Turn Player 2
{
System.out.println("It is your turn " + playerArray[(game.getPlayerTurn() % 2)].getPlayerName() + ".");
System.out.println("How many stones would you like to take?");
int take = input.nextInt();
game.checkTake(take);
game.setPlayerTake(take);
stoneheap.currentStones();
System.out.println("There are " + stoneheap.getStones() + " stones left.");
}
game.incrementTurns();
}
System.out.println("The game has ended and the winner is ...");
System.out.println(playerArray[(game.getPlayerTurn() % 2)].getPlayerName());
System.out.println("It took " + (game.getTurn() - 1) + " turns." );
System.out.println("");
System.out.println("Do you want to play another round? Y for yes, anything else for no");
String userInput = input.next();
nextRound = userInput.toUpperCase();
} while (nextRound.equals("Y"));
}
}
In your createPlayer method, you should access playerArray by this keyword (this.playerArray = new Player[2]).
Currently you are creating an array on the fly, and the class variable is untouched, that's why you are getting an exception.
public class Game
{
private Player[] playerArray;
[...]
public void createPlayer(String name1, String name2)
{
this.playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}

Java dice game counter unable to add correctly

I wrote a dice game in java that rolls two dice and keeps score.
The entire game has a total of four classes but the problem I am facing is in my EyesHaveIt class.
It adds each turn to a total score but it is not calculating the math correctly.
I've tried to find what is causing it but with no success.
Can anyone help me find where the problem is?
public class EyesHaveIt {
Scanner kb = new Scanner(System.in);
private int turnScore;
private int computerTotalScore;
private int playerTotalScore;
private int computerTurnNumber;
private int playerTurnNumber;
public int roundPoints;
private String userName;
//Accepts a name value from PlayGame class.
public void init(String name) {
userName = name;
}
//This method starts the game with a computer turn.
public void playGame() {
computerTurn();
}
//Computers turn to roll the dice.
public void computerTurn() {
turnScore = 0;
System.out.println("Computer's turn: ");
while (turnScore < 20) {
rollTheDice();
computerTurnNumber++;
setComputerTotalScore(turnScore);
}
getGameScore();
enterToContinue();
}
//Checks users input(enter) to continue player turn.
public void enterToContinue() {
System.out.print("\nPress ENTER to continue ...");
try {
System.in.read();
} catch (Exception e) {
e.printStackTrace();
}
playerTurn();
}
//Players turn to roll the dice.
public void playerTurn() {
turnScore = 0;
System.out.println(userName + "'s turn:");
for (int i = 0; i < 5; i++) {
rollTheDice();
playerTurnNumber++;
getPlayerTotalScore(turnScore);
System.out.println("Roll again? (y/n) ");
char continueGame = kb.next().charAt(0);
continueGame = Character.toUpperCase(continueGame);
if (continueGame == 'Y') {
int test = 0;
} else {
getGameScore();
}
}
getGameScore();
computerTurn();
}
//Creates two dice from PairOfDice class and prints values rolled.
public void rollTheDice() {
PairOfDice dieOne = new PairOfDice();
PairOfDice dieTwo = new PairOfDice();
int die1 = dieOne.getDieOneValue();
int die2 = dieTwo.getDieOneValue();
System.out.println("\tRolled: " + die1 + " and " + die2);
whatWasRolled(die1, die2);
}
//Accepts int from rollTheDie and checks the value.
public void whatWasRolled(int die1, int die2) {
if (die1 == 1 && die2 == 1) {
System.out.println("\t Rolled snake eyes! All turn points will be doubled.");
roundPoints = (die1 + die2 * 2);
setScore(roundPoints);
} else if (die1 == 6 && die2 == 6) {
System.out.println("\t Rolled box cars! All points are gone now!");
roundPoints = 0;
setScore(roundPoints);
} else if (die1 == die2) {
System.out.println("\t Rolled double. . . lose all turn points.");
roundPoints = 0;
setScore(roundPoints);
} else {
roundPoints = die1 + die2;
setScore(roundPoints);
getTurnScore();
}
}
//Sets turnScore from whatWasRolled.
public void setScore(int roundPoints) {
turnScore = turnScore + roundPoints;
}
//Sets computer game score.
public void setComputerTotalScore(int turnScore) {
computerTotalScore = turnScore + computerTotalScore;
}
//Sets player game score.
public void setPlayerTotalScore(int turnScore) {
playerTotalScore = turnScore + playerTotalScore;
}
//computerTotalScore accesor returns an int.
public int getComputerTotalScore() {
return computerTotalScore;
}
//playerTotalScore accesor returns an int.
public int getPlayerTotalScore(int turnScore) {
playerTotalScore = turnScore + playerTotalScore;
return playerTotalScore;
}
//Returns turnScore after roll.
public int getTurnScore() {
System.out.println("\tCurrent score for this turn:" + turnScore);
return turnScore;
}
//How the game ends and current game score is displayed.
public void getGameScore() {
System.out.println(
"CURRENT GAME SCORE: Computer: " + computerTotalScore + "\t" + userName + ": " + playerTotalScore);
if (computerTotalScore >= 150) {
System.out.println("Sorry, " + userName + " you got beat by the computer!");
System.exit(0);
} else if (playerTotalScore > 150) {
System.out.println(userName + ", Congratulations! You beat the computer!");
System.exit(0);
}
}
}
how are you?
I have made 3 alterations in 2 classes.
have a look to see if it will work for you.
//Computers turn to roll the dice.
public void computerTurn() {
computerTurnNumber = 0; // here
turnScore = 0;
System.out.println("Computer's turn: ");
while (computerTurnNumber < 20) { // here is the amount of time the dice will be rolled
rollTheDice();
computerTurnNumber++;
setComputerTotalScore(turnScore);
}
getGameScore();
enterToContinue();
}
and
//Sets turnScore from whatWasRolled.
public void setScore(int roundPoints) {
turnScore = roundPoints; //here, before it was accumulating the points of each turn
}

Having trouble solving logic of random number game

I am relatively new to java programming. I am currently working on building a mini guessing game, as a project to learn more Java. I am having some issues with the following:
Here are the 4 main things I am having trouble solving.
Record the answer for each user, if incorrect.
If the user was correct, skip them in subsequent rounds.
Once all players have guessed their correct number, print out the number of guesses it took for each one to guess correctly, the incorrect responses, and show a ranking of the players.
Ask if the user(s) wish to play again. If so, reset all values.
Here are the methods that I have written;
import java.io.*;
public class MultiPlayerRandomGame {
// this method asks how many users will be playing and returns the number of users
public static int howManyUsers() {
System.out.println("How many users will be playing?");
int players = IO.readInt();
return players;
}
// this method generates and returns a random number
public static int generateRandomNumber() {
int randomNumber = (int) (Math.random() * 100);
return randomNumber;
}
// this method compares user's entered guess and the generated random number then returns true/false
public static boolean compareGuess(int guess, int randomNumbers) {
boolean isGuessCorrect = false;
if (guess == randomNumbers) {
System.out.println("CORRECT!");
isGuessCorrect = true;
} else if (guess > randomNumbers) {
System.out.println("Too High");
} else if (guess < randomNumbers) {
System.out.println("Too Low");
}
System.out.println("test1");
return isGuessCorrect;
}
// this method determines whether Player N is correct or incorrect
public static boolean nextPlayer(int numOfUsers, int[] numberOfGuesses, int[] randomNumbers, int[][] numberBoard) {
for (int n = 0; n < numOfUsers; n++) {
int guessedNumber = numberOfGuesses[n];
/* if (guessedNumber == 0) {
return false;
}*/
if (numberBoard[n][guessedNumber] != randomNumbers[n]) {
return false;
}
}
return true;
}
/* this method is supposed to print out the number of guesses it took each player to guess their correct number
* CORRECTION: change the logic of this method to printing the number of guesses for one player then
* in the main method or wherever, make a for loop that prints out the number of guesses for each player
*/
public static void amountOfGuesses(int numOfUsers, int [] numberOfGuesses, int [][] numberBoard) {
int n = 0;
for ( int i = 0; i < numOfUsers; i++ ) {
n = n + 1;
System.out.println("Player " + n + " guessed " + numberOfGuesses[i]+ " time(s)");
}
}
// this method determines whether the user(s) would like to play again
public static boolean playAgain(String answer) {
boolean userWillPlayAgain;
if (answer.compareToIgnoreCase("no") == 0) {
userWillPlayAgain = false;
}
else {
userWillPlayAgain = true;
}
return userWillPlayAgain;
}
// this method controls the entire game
public static boolean playGame(){
boolean gameTerminate = false;
int numOfUsers = howManyUsers();
int [] randomNumbers = new int[numOfUsers];
int [] numberOfGuesses = new int [numOfUsers];
int [][] numberBoard = new int [numOfUsers][100];
// this for loop assigns the n random number(s) to the n player(s)
for (int n = 0; n < numOfUsers; n++){
randomNumbers[n] = generateRandomNumber();
System.out.println("PLAYER " + (n+1) + "'s RANDOM NUMBER: " + randomNumbers[n]);
}
do {
for (int i = 0; i < numOfUsers; i++) {
int guessedNumber = numberOfGuesses[i];
if (guessedNumber == 0 || numberBoard[i][guessedNumber-1] != randomNumbers[i]) {
System.out.println("Enter your guess Player " + (i+1) + ":");
int enteredGuess = IO.readInt();
numberBoard[i][guessedNumber] = enteredGuess;
numberOfGuesses[i] = guessedNumber + 1;
if(compareGuess(enteredGuess, randomNumbers[i])){
return true;
}
}
}
/* int n = 0;
* for ( int j = 0; j < numOfUsers; j++ ) {
n = n + 1;
System.out.println("Player " + n + " guessed " + numberOfGuesses[j]+ " time(s)"); }
*/
} while (nextPlayer(numOfUsers, numberOfGuesses, randomNumbers, numberBoard) == false);
// System.out.println("test");
return gameTerminate;
}
public static void main(String[] args){
boolean playing = true;
while (playing) {
playGame();
System.out.println("Would you like to play again?");
String answer = IO.readString();
playing = playAgain(answer);
}
System.out.println("OK, goodbye!");
}
}
Main issue as of right now: The game terminates and asks if user would like to play again after a player guesses their number, rather than after every player guesses their number.
Do I need actual Objects to make this happen and track every player or can this still be solved without objects? This is a territory I am unfamiliar with.
Right now your playGame method returns true back to main whenever any guess returns correct from compareGuess.
I would recommend setting up another array boolean[] correctGuess in playGame and mark the player number index as true if a player guesses correctly. You can use this new array to skip players who have guessed correctly, also. Once all players are marked true you can return to main.
This won't help improve your current code, but the same game can easily implemented using objects. In my opinion, the code is cleaner and easier to read.
Objects allow you to encapsulate the data required by each class. The target, number of guesses, and whether they were correct is stored in the Person object instead of in a multi-dimensional array. The values can be accessed by referencing the Person object - e.g. person.numGuesses or person.target.
By using objects, you can keep specific functionality scoped out of the main class. i.e. abstract away the implementation. In a future version of the game, you may want to change the way the target value is incremented; by using objects, the change can be made in the class which sets and checks the value - without affecting any other classes.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Game {
private final List<Person> personList = new ArrayList<>();
private Game(int numPlayers) {
for (int i = 0; i < numPlayers; i++) {
personList.add(new Person(i)); // Fill the player list
}
}
public static void main(String[] args) {
System.out.print("Enter the number of players: ");
Scanner sc = new Scanner(System.in);
int numPlayers = sc.nextInt();
// Initialise with the number of players
Game g = new Game(numPlayers);
g.mainLoop(); // Play the game
boolean playAgain = false;
do {
System.out.print("Do you wish to play again?: ");
String in = sc.next();
playAgain = "yes".equals(in);
if (playAgain) {
g.resetAll();
g.mainLoop();
}
} while (playAgain); // Only loop if they answered "yes"
}
private boolean allCorrect() {
// Check if all players have answered correctly
return personList.stream().allMatch(p -> p.correct);
}
private void resetAll() {
for (Person p : personList) {
p.reset(); // Reset each person
}
}
private void mainLoop() {
while (!allCorrect()) {
for (Person p : personList) {
p.doGuess(); // Ask for the guess
}
}
// Everyone is correct, print the scores.
for (Person p : personList) {
System.out.println("Player " + p.id + " => " + p.numGuesses + " guesses");
}
}
}
class Person {
final int id;
int numGuesses;
boolean correct;
private int target;
Person(int id) {
this.id = id;
target = new Random().nextInt(100); // Each player has a random target between 0-100
}
void doGuess() {
if (correct) {
// Skip turn if they're already correct
return;
}
numGuesses++;
System.out.print("Player " + id + " guess " + numGuesses + "(" + target + "): ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt(); // Read the guess
if (i == target) {
correct = true;
System.out.println("Correct!");
}
}
void reset() {
target = new Random().nextInt(100); // New target between 0-100
numGuesses = 0; // Reset the counter
correct = false;
}
}

How to compare variables in a loop, java

I have to design a program to simulate players rolling three dice for a number of rounds. Each dice throw is given points. I have to diplay for each round the dice values, and number of points for each player for those values and the winner of each round (the player with the highest points for that round, or no-one if they are the same).
I have implemented the points calculator, but I dont know how to display the winner of each round. Also, I am displaying the output vertically when it is supposed to be horizontally.
I think maybe comparing the values inside the loop in the game class may work. P.S. I am new in java, please make any suggestions to change the code if there is a better solution.
This is waht my program is displaying
round 1--> player 1: 2 4 5 points: 11
round 2--> player 1: 2 3 5 points: 10
round 3--> player 1: 2 4 6 points: 12
round 4--> player 1: 4 4 6 points: 34
round 5--> player 1: 3 4 5 points: 52
.
round 1--> player 2: 3 5 5 points: 33
round 2--> player 2: 3 6 6 points: 35
round 3--> player 2: 2 3 4 points: 49
round 4--> player 2: 1 1 3 points: 25
round 5--> player 2: 1 2 4 points: 7
This is what it is supposed to display
Round 1 Player 1: 1 3 3 points: 27 Player 2: 1 4 5 points: 10 Round winner is player 1
Round 2 Player 1: 1 2 5 points: 8 Player 2: 1 3 6 points: 10 Round winner is player 2
Round 3 Player 1: 1 4 4 points: 29 Player 2: 4 5 6 points: 55 Round winner is player 2
Round 4 Player 1: 1 3 5 points: 9 Player 2: 1 5 5 points: 31 Round winner is player 2
Round 5 Player 1: 3 6 6 points: 35 Player 2: 2 2 4 points: 28 Round winner is player 1
Total wins: Player 1: 2/ Player 2: 3
Total points: Player 1: 108/ Player 2: 134
Average points per round: Player 1: 21.6/ Player 2: 26.8
Overall points winner is player 2.
Main code
import java.util.Scanner;
public class Game {
// ------------------- FIELDS ------------------------
// Create instance of Scanner class
public static Scanner input = new Scanner(System.in);
// variables
public static ThreeDiceScorer thrdiesc;
public static int diceArray [];
// ------------------ METHODS ------------------------
public static void main(String[] args) {
int rounds; // input by user
int players; // input by user
System.out.print("Please input number of rounds (grater or equal than 0) --> ");
rounds = input.nextInt();
System.out.print("\n");
System.out.print("Please input number of rounds (grater or equal than 0) --> ");
players = input.nextInt();
System.out.print("\n");
for (int p = 0; p < players; p++) { //loop for players
for (int r = 0; r < rounds; r++) { // loop for number of rounds
int diceArray [] = new int [3];
for (int i = 0; i < diceArray.length; i++) { // loop for random Array
diceArray [i] = 1 + (int)(6 * Math.random());
}
// Create new ThreeDice and calculator instances
thrdiesc = new ThreeDiceScorer(diceArray [0], diceArray [1], diceArray [2]);
//Calculate
thrdiesc.getDie1();
thrdiesc.getDie2();
thrdiesc.getDie3();
thrdiesc.threeSame();
thrdiesc.runOfThree();
thrdiesc.pair();
thrdiesc.allDifferent();
thrdiesc.calcTotalPoints();
thrdiesc.printResult(p,r);
}
System.out.print("\n");
}
}//end Main Method
}// end Class
ThreeDice class
public class ThreeDice {
// ---------------------- ATTRIBUTES ---------------------
protected int die1;
protected int die2;
protected int die3;
// ------------------ CONSTRUCTOR -------------------
public ThreeDice(int s1, int s2, int s3) {
// This puts the three dice values in ascending order.
int tmp;
if (s2 < s1) {
tmp = s2;
s2 = s1;
s1 = tmp;
}
if (s3 < s2) {
tmp = s3;
s3 = s2;
s2 = tmp;
}
if (s2 < s1) {
tmp = s2;
s2 = s1;
s1 = tmp;
}
die1 = s1;
die2 = s2;
die3 = s3;
}
// --------------------- METHODS ---------------------
// Accessor methods
public int getDie1() {
return die1;
}
public int getDie2() {
return die2;
}
public int getDie3() {
return die3;
}
public boolean threeSame() {
return (die1 == die3);
}
public boolean runOfThree() {
return (( (die1 + 1) == die2) && ( (die2 + 1) == die3));
}
public boolean pair() {
return (((die1 == die2) || (die2 == die3)) && (die1 != die3));
}
public boolean allDifferent() {
return (!runOfThree() && (die1 != die2) && (die2 != die3));
}
public void printResult() {
if (threeSame())
System.out.println("The roll is all the same.");
else if (runOfThree())
System.out.println("The roll is a run.");
else if (pair())
System.out.println("The roll is a pair.");
else if (allDifferent())
System.out.println("The roll is all different.");
}
}
ThreeDiceScorer (Calculator) Class
public class ThreeDiceScorer extends ThreeDice {
int total;
public ThreeDiceScorer(int s1, int s2, int s3) {
super(s1, s2, s3);
}
public void calcTotalPoints() {
int sumOfDice = die1 + die2 + die3;
if (threeSame()){
total= sumOfDice + 60;
}
else if (runOfThree()){
total= sumOfDice + 40;
}
else if (pair()){
total= sumOfDice + 20;
}
else if (allDifferent()){
total= sumOfDice;
}
}
public void printResult(int p,int r) {
System.out.println("round "+ (r+1)+ "--> " + "player "+ (p+1) + " "+ die1 + " " + die2 + " " + die3 + " " + "points: "+ total);
}
}
Sol
Switch player loop and rounds loop.
In each round loop maintain a max and update it with max value and player.
Modify printresult a little to remove round.
Loop and max:
for (int r = 0; r < rounds; r++) { // loop for number of rounds
int max = 0;
int max_p = 0;
System.out.println("Round " + r + ": ");
for (int p = 0; p < players; p++) { //loop for players
int diceArray[] = new int[3];
//...
thrdiesc.printResult(p, r);
if (thrdiesc.total > max) {
max = thrdiesc.total;
max_p = p;
}
}
System.out.println("Winner is player " + (max_p + 1) + "\n");
}
PrintResult Method:
public void printResult(int p, int r) {
System.out.println("player " + (p + 1) + " " + die1 + " " + die2 + " " + die3 + " " + "points: " + total);
}
Misc
Indent Code properly.
Be careful while copying. (See the prompt)
While looking at your code, I have a feeling you might be able to make this much easier for yourself by creating some simple classes, five or six to be exact.
First I would break up some parts into classes. The two main classes I am thinking of are a simple Die class that is simply an immutable Die that when created sets the die value to a random number between 1 and 6. Once you create the Die object it cannot be changed. Your ThreeDice class is narrow and is really unnecessary as the three dice should really be a part of the Player object (next class) as a simple array of 3 Die objects and as an array of Die objects we can sort the dice from low to high.
A sample of a “Die” class is below:
Public final class Die implements Comparable<Die>
{
private int dieNumber;
// default constructor
public Die()
{
RollDie();
}
public int GetDieNumber()
{
return dieNumber;
}
public int compareTo(Die otherDie)
{
return this.dieNumber - otherDie.dieNumber;
}
private void RollDie()
{
dieNumber = 1 + (int)(6 * Math.random());
}
}
The next class to help would be a Player class. The important parts of this class will be a player name, then a Die object array (of size 3 in your case) to hold the players random dice. In this class you could also have methods to get the total value of the 3 dice, along with a method/variable to get the extra points the user gets if the 3 dice are the same number, if there is a pair, etc. Here we can take advantage of the sorting of the dice array from low to high when the dice array is created. This will make checking for straights easier.
A Player class example is below.
public class Player implements Comparable<Player>
{
private String playerName;
private Die[] diceArray;
private int diceTotal = 0;
private int extraPoints = 0;
private int overallTotal = 0;
private String extraPointsString = "";
public Player(String inName, Die[] inDiceArray)
{
playerName = inName;
diceArray = inDiceArray;
SetDiceTotals();
}
public String GetPlayerName()
{
return playerName;
}
public int GetExtraPoints()
{
return extraPoints;
}
public int GetDiceTotal()
{
return diceTotal;
}
public int GetOverallTotal()
{
return overallTotal;
}
public String GetExtraPointsString()
{
return extraPointsString;
}
public Die[] GetDiceArray()
{
return diceArray;
}
public String toString()
{
String playerString = playerName + " Dice values: ";
for (int i = 0; i < diceArray.length; i++)
{
if (i < (diceArray.length - 1))
playerString = playerString + diceArray[i].GetDieNumber() + ", ";
else
playerString = playerString + diceArray[i].GetDieNumber();
}
playerString = playerString + " Total: " + GetDiceTotal();
playerString = playerString + " - Special Points added: " + GetExtraPoints() + " for having " + GetExtraPointsString();
return playerString + " Total Points: " + GetOverallTotal();
}
public int compareTo(Player otherPlayer)
{
int thisTotal = this.GetDiceTotal() + this.GetExtraPoints();
int otherTotal = otherPlayer.GetDiceTotal() + otherPlayer.GetExtraPoints();
return otherTotal - thisTotal;
}
// private internal method to set dice totals, extra points and extra points string
private void SetDiceTotals()
{
int total = 0;
for (int i = 0; i < diceArray.length; i++)
{
total = total + diceArray[i].GetDieNumber();
}
diceTotal = total;
if (is3OfAKind())
{
extraPoints = 60;
extraPointsString = "Three of a Kind";
}
else
{
if (isPair())
{
extraPoints = 40;
extraPointsString = "Pair";
}
else
{
if (isStraight())
{
extraPoints = 20;
extraPointsString = "Straight";
}
else
{
extraPoints = 0;
extraPointsString = "All die are different";
}
}
}
overallTotal = extraPoints + diceTotal;
}
private boolean is3OfAKind()
{
if (diceArray[0].GetDieNumber() == diceArray[1].GetDieNumber() &&
diceArray[0].GetDieNumber() == diceArray[2].GetDieNumber())
return true;
return false;
}
private boolean isPair()
{
if (diceArray[0].GetDieNumber() == diceArray[1].GetDieNumber() ||
diceArray[0].GetDieNumber() == diceArray[2].GetDieNumber() ||
diceArray[1].GetDieNumber() == diceArray[2].GetDieNumber() )
return true;
return false;
}
// this method needs to have the diceArray sorted from low to high
private boolean isStraight()
{
if (diceArray[1].GetDieNumber() == (diceArray[0].GetDieNumber() + 1) &&
diceArray[2].GetDieNumber() == (diceArray[1].GetDieNumber() + 1) )
return true;
return false;
}
}
Then, since you want to keep totals for all the rounds, I figure you may need a Round class. This class will consist of an array of Player objects for a round. Also a round number, total points of the round from all players, an average of points for the round and a string to indicate which player won the round.
A Round class example is below.
public class Round
{
private Player[] playerArray;
private int roundNumber = 0;
private int totalPointsForRound = 0;
private double roundAveragePoints = 0;
private String roundWinnerName = "";
public Round(int inRoundNumber, Player[] inPlayerArray)
{
playerArray = inPlayerArray;
roundNumber = inRoundNumber;
totalPointsForRound = SetAllPointsForRound();
roundAveragePoints = SetAveragePoints();
roundWinnerName = SetRoundWinnerName();
}
public int GetTotalPointsForRound()
{
return totalPointsForRound;
}
public double GetAveragePointsForRound()
{
return roundAveragePoints;
}
public String GetRoundWinnerName()
{
return roundWinnerName;
}
public Player[] GetPlayerArray()
{
return playerArray;
}
public int GetRoundNumber()
{
return roundNumber;
}
private String SetRoundWinnerName()
{
// sort the array from high to low - if the first two total are equal then its a tie
Player[] tempArray = playerArray;
Arrays.sort(tempArray);
if (tempArray[0].GetOverallTotal() == tempArray[1].GetOverallTotal())
return "Tie";
if (tempArray[0].GetOverallTotal() > tempArray[1].GetOverallTotal())
return tempArray[0].GetPlayerName();
return "Unknown Winner???";
}
private double SetAveragePoints()
{
double totalPoints = GetTotalPointsForRound();
double average = totalPoints/playerArray.length;
return Math.round(average*100.0)/100.0;
}
private int SetAllPointsForRound()
{
int allPoints = 0;
for (int i = 0; i < playerArray.length; i++)
{
allPoints = allPoints + playerArray[i].GetOverallTotal();
}
return allPoints;
}
}
Then since you want to keep totals for all the players, you may want to make a small PlayerTotals class. This class will simply consist of a player name, total wins for all rounds and total points for all rounds. Keep in mind these are totals for ALL rounds not for a single round as each Player object in the Round's playerArray will contain totals for that particular round.
A PlayerTotals class example is below
public class PlayerTotals implements Comparable<PlayerTotals>
{
String playerName;
int totalWins = 0;
int totalPoints = 0;
public PlayerTotals(String inPlayerName)
{
playerName = inPlayerName;
}
public int GetTotalPoints()
{
return totalPoints;
}
public void SetTotalPoints(int inPoints)
{
totalPoints = inPoints;
}
public int GetTotalWins()
{
return totalWins;
}
public void SetTotalWins(int inWins)
{
totalWins = inWins;
}
public int compareTo(PlayerTotals otherPlayerTotals)
{
int thisTotalPoints = this.GetTotalPoints();
int otherTotalPoints = otherPlayerTotals.GetTotalPoints();
return otherTotalPoints - thisTotalPoints;
}
}
Then two more classes which you could actually combine into one class. One is a static GameUtils class that helps do some global things like: GetPlayerArray, this method gets an array of Player objects. Each Player object will contain an array of the 3 dice each player rolled. This dice array will be sorted from low to high. This is the method that gets your initial random rolls for each player for each round. Also here we can GetPlayerOverallWins where we can loop through all rounds and total up how many wins each player had. A method called GetTotalTies to get the total number of ties from all the rounds. And a method GetPlayerOverallPoints to get a total of all players points from all rounds. Also here I placed your prompts for the user to enter the number of players and number of rounds with a check to make sure the user input is valid.
A GameUtils example is below:
public final class GameUtils
{
public static Player[] GetPlayerArray(int numOfPlayers, int numOfDice)
{
Player[] playerArray = new Player[numOfPlayers];
for (int i = 0; i < numOfPlayers; i++)
{
Die[] diceArray = new Die[numOfDice];
for (int j = 0; j < numOfDice; j++)
{
diceArray[j] = new Die();
}
Arrays.sort(diceArray);
playerArray[i] = new Player("Player " + (i + 1), diceArray);
}
return playerArray;
}
public static int GetNumberOfPlayers(Scanner input)
{
return GetValidInteger("Please input number of players (greater than 0) --> ", input);
}
public static int GetNumberOfRounds(Scanner input)
{
return GetValidInteger("Please input number of rounds (greater than 0) --> ", input);
}
private static int GetValidInteger(String prompt, Scanner input)
{
boolean done = false;
int validInt = -1;
String userInput = "";
while (!done)
{
System.out.print(prompt);
userInput = input.nextLine();
try
{
validInt = Integer.parseInt(userInput);
done = true;
}
catch (NumberFormatException e)
{
System.out.println("Invalid Input: " + userInput + " Try again!");
}
}
return validInt;
}
public static int GetPlayerOverallWins(String playerName, Round[] allRounds)
{
int totalWins = 0;
for (int i = 0; i < allRounds.length; i++)
{
Round curRound = allRounds[i];
String roundWinner = curRound.GetRoundWinnerName();
if (playerName.equals(roundWinner))
{
totalWins++;
}
}
return totalWins;
}
public static int GetTotalTies(Round[] allRounds)
{
int totalTies = 0;
for (int i = 0; i < allRounds.length; i++)
{
Round curRound = allRounds[i];
String roundWinner = curRound.GetRoundWinnerName();
if (roundWinner.equals("Tie"))
{
totalTies++;
}
}
return totalTies;
}
public static int GetPlayerOverallPoints(String player, Round[] allRounds)
{
int totalPoints = 0;
for (int i = 0; i < allRounds.length; i++)
{
Round curRound = allRounds[i];
for (int j = 0; j < curRound.GetPlayerArray().length; j++)
{
Player curPlayer = curRound.GetPlayerArray()[j];
if (player.equals(curPlayer.GetPlayerName()))
{
totalPoints = totalPoints + curPlayer.GetOverallTotal();
break;
}
}
}
return totalPoints;
}
}
Lastly a DiceGame class with a main entry to put it all together. A dice game class will consist of global variables numberOfPlayers. numberOfRounds, numberOfDice, and a playerArray to use for each round, then an array of Rounds to hold all the rounds for totaling after all the rounds have been run. The example below starts by setting a loop for the number of rounds, in this loop we create all the players and dice values for them then save the round information into a new Round object then place each new Round object into an array. Then the results from the current round is output to the user. Once the loop on the number of rounds finishes, we should then have an array of Round objects. Here is where the PlayerTotals class helps as we can create another array of PlayerTotals objects for all rounds. This uses some methods from GameUtils and these methods could just a well be placed into this main class. After all player totals for all rounds have been added up, the results are output to the user.
Main DiceGame class example:
public class DiceGame
{
public static Scanner input = new Scanner(System.in);
static int numberOfPlayers;
static int numberOfRounds;
static int numberOfDice = 3;
static Player[] playerArray;
static Round[] allRounds;
public static void main(String[] args)
{
numberOfPlayers = GameUtils.GetNumberOfPlayers(input);
numberOfRounds = GameUtils.GetNumberOfRounds(input);
System.out.println("");
allRounds = new Round[numberOfRounds];
// for each round - we want to create players with the proper number of random dice
for (int i = 0; i < numberOfRounds; i++)
{
// get an array of players with random dice
playerArray = GameUtils.GetPlayerArray(numberOfPlayers, numberOfDice);
Round currentRound = new Round(i, playerArray);
allRounds[i] = currentRound;
// print the results of this round
System.out.println("Round " + (i + 1) + " Results - Winner is: " + currentRound.GetRoundWinnerName()
+ " -- Average score for this round: " + currentRound.GetAveragePointsForRound());
for (int j = 0; j < playerArray.length; j++)
{
System.out.println(playerArray[j].toString());
}
System.out.println("---------------------------------------");
}
// now get totals for all rounds
// first create an array of PlayerTotals
PlayerTotals[] allPlayersTotals = new PlayerTotals[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++)
{
PlayerTotals curPlayer = new PlayerTotals(playerArray[i].GetPlayerName());
curPlayer.SetTotalPoints(GameUtils.GetPlayerOverallPoints(curPlayer.playerName, allRounds));
curPlayer.SetTotalWins(GameUtils.GetPlayerOverallWins(curPlayer.playerName, allRounds));
allPlayersTotals[i] = curPlayer;
}
// print the overall results
System.out.println("");
System.out.println(" -- Overall Results --");
System.out.println("Ties: " + GameUtils.GetTotalTies(allRounds));
Arrays.sort(allPlayersTotals);
PlayerTotals curPlayer;
for (int i = 0; i < allPlayersTotals.length; i++)
{
curPlayer = allPlayersTotals[i];
System.out.println(curPlayer.playerName + " Won " + curPlayer.totalWins + " times - Total Points: " + curPlayer.totalPoints);
}
}
}
Hope these make things easier. Good Luck!

Categories