Two Players Fighting With Multiple Attack Options Java - java

I am trying to create a game where there is two fighters. A warrior versus gladiator.
Both of the fighters have 1000 health. When the battle starts, player 1 gets to choose between three options: 1 - thrust 2 - slice 3 - drink potion...
Lets say player 1 chooses thrust and attacks 55 (using random) then my code prints player 2's new health which is now 945. Then it's player two's turn and lets say he does the exact same thing and takes off some health from player 1.
Now it will go back to player 1's turn. This is where it gets complicated. Now player 1 attacks for the second time and lets say he does 80 damage. It will print out that player two has 920 health. It doesn't have the previous attack subtracted off. I want them to fight until one of there health goes down to 0 and dies.
So how can I fix my code so the health doesn't restart at 1000 after each attack and it subtracts from the new health that was already been lowered from the previous attacks. Like this: 1000 hp - 55 = 945 hp - 80 = 865 hp etc. I' new to coding. Started in January. Any help would be amazing!
import java.util.Random;
public class Duel
{
Random hit = new Random();
Random hit1 = new Random();
int newHealth, newHealth1;
int outcome, outcome1, outcome2, outcome3;
int attack, attack1;
int defense, defense1;
int health, health1;
void calculateWinner()
{
do
{
outcome = hit1.nextInt(100) - hit1.nextInt(15);
newHealth1 = health1 - outcome;
System.out.println("Your attack does " + outcome + " damage!");
System.out.println("");
System.out.print("Warrior Health: " + newHealth1 + "\n");
break;
}
while(newHealth1 == 0);
//System.out.println("Gladiator is the winner!");
}
void calculateWinner1()
{
do
{
outcome1 = hit.nextInt(100) - hit.nextInt(15);
newHealth = health - outcome1;
System.out.println("Your attack does " + outcome1 + " damage!");
System.out.println("");
System.out.print("Gladiator Health: " + newHealth + "\n\n");
break;
}
while(newHealth == 0);
//System.out.println("Warrior is the winner!");
}
void calculateHealth()
{
do
{
newHealth = health + hit.nextInt(35);
System.out.println("You drink the potion.");
System.out.println("Your health is now at " + newHealth + "!");
break;
}
while(newHealth1 > 0 && newHealth > 0);
}
void calculateHealth1()
{
do
{
newHealth1 = health1 + hit.nextInt(35);
System.out.println("You drink the potion.");
System.out.println("Your health is now at " + newHealth1 + "!");
break;
}
while(newHealth1 > 0 && newHealth > 0);
}
}
import java.util.Random;
import java.util.Scanner;
public class DuelMain
{
public static void main(String[] args)
{
// Random + Scanner
Random hit = new Random();
Random hit1 = new Random();
Scanner input = new Scanner(System.in);
// String + Int
String player1name = "";
String player2name = "";
int restart;
int player1option;
int player2option;
int fight = 0;
Duel warrior = new Duel();
Duel gladiator = new Duel();
gladiator.attack = hit.nextInt(100);
gladiator.defense = hit.nextInt(15);
gladiator.health = 1000;
warrior.attack1 = hit1.nextInt(100);
warrior.defense1 = hit1.nextInt(15);;
warrior.health1 = 1000;
// Printing Names
System.out.print("Gladiator Enter Name: ");
player1name = input.nextLine();
System.out.print("Warrior Enter Name: ");
player2name = input.nextLine();
while(fight == 0)
{
// Choose Moves (Player1)
System.out.printf("%n%s, Choose Your Move! \n", player1name);
System.out.println("1: Thrust 2: Slice 3: Drink Potion");
player1option = input.nextInt();
if(player1option == 1)
{
System.out.printf("You Thrust Your Sword At %s! \n", player2name);
warrior.attack1 = hit1.nextInt(100);
warrior.defense1 = hit1.nextInt(15);
warrior.health1 = 1000;
warrior.calculateWinner();
}
if(player1option == 2)
{
System.out.printf("You Slice Your Sword At %s! \n", player2name);
warrior.attack1 = hit1.nextInt(100);
warrior.defense1 = hit1.nextInt(15);
warrior.health1 = 1000;
warrior.calculateWinner();
}
if(player1option == 3)
{
warrior.calculateHealth();
}
// Choose Moves (Player2)
System.out.printf("%n%s, Choose Your Move! \n", player2name);
System.out.println("1: Thrust 2: Slice 3: Drink Potion");
player2option = input.nextInt();
if(player2option == 1)
{
System.out.printf("You Thrust Your Sword At %s! \n", player1name);
gladiator.attack = hit.nextInt(100);
gladiator.defense = hit.nextInt(15);
gladiator.health = 1000;
gladiator.calculateWinner1();
}
if(player2option == 2)
{
System.out.printf("You Slice Your Sword At %s! \n", player1name);
gladiator.attack = hit.nextInt(100);
gladiator.defense = hit.nextInt(15);
gladiator.health = 1000;
gladiator.calculateWinner1();;
}
if(player2option == 3)
{
gladiator.calculateHealth1();
}
}
}
}

Within the blocks after if(playerXoption == N), you are resetting the character health to 1000 with warrior.health1 = 1000 and gladiator.health = 1000. Removing those lines should allow health to continue to be degraded by further attacks without being reset.

It's really hard to point you in any direction, but I highly suggest you read java and objective oriented progaming tutorials again. Anyhow, I'll try to make it short.
First of all, you need a class for your warriors. Every warrior will be an instance of this class. Each of them will have attributes: health, damage and defense (let's say the damage is going to be constant at the moment).
public class Warrior {
public Warrior(final int health, final int damage, final int defense) {
this.health = health;
this.damage = damage;
this.defense = defense;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
private int health;
private int damage;
private int defense;
}
Then we need a class that will handle the duel. To keep things simple it will be pretty hard-coded. Basically it'll just make two warriors that will smack each other until one drops dead.
public class Duel {
private Warrior warrior;
private Warrior gladiator;
public Duel() {
warrior = new Warrior(1000, 100, 20);
gladiator = new Warrior(1000, 80, 30);
}
public int doDuel() {
while (true) {
if (attack(warrior, gladiator)) {
return 1;
} else if (attack(gladiator, warrior)) {
return 2;
}
}
}
public boolean attack(final Warrior attacker, final Warrior defender) {
defender.setHealth(defender.getHealth() - (attacker.getDamage() - defender.getDefense()));
if (defender.getHealth() <= 0) {
return true;
}
return false;
}
}
In main call:
final Duel duel = new Duel();
if(duel.doDuel() == 1) {
// warrior won
} else {
// gladiator won
}
Have in mind it's very naive and simple implementation. There are milions of ways to implement something like this.

Related

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);
}

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!

update a variable in a different class

How do I make amount() in class Casino.java store the total value and allow it to be returned to the class Roulette.java.
When I use:
int amount = Casino.amount();
It gives me several hundred lines of errors.
What I want done is to run the game number() and store the value into Casino.amount()
Please note in class Roulette.java there is a function called amountUpdate() which should update Casino.amount().
This is class Casino.java
package Casino;
import java.util.*;
public class Casino {
static String player = "";
static int playAmount = 0;
public static void main(String[] args) {
System.out.println("Welcome to Michael & Erics Casino!");
player();
ask();
start();
}
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
player = sc.nextLine();
}
return player;
}
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("How much would you like to play with? ");
playAmount = sc.nextInt();
if (playAmount < 1) {
System.out.println("Please enter a value that is more than $1");
playAmount = 0;
}
System.out.println("You are playing with: $" + playAmount + "\n");
}
public static int amount() {
int amount = playAmount;
if (Roulette.amountUpdate() >= 1) {
amount += Roulette.amountUpdate();
}
return amount;
/*if (Blackjack.amountUpdate() >= 1)
amount += Blackjack.amountUpdate();
return amount;*/
}
public static void start() {
System.out.println("Which table would you like to play at?");
System.out.println("1: Blackjack");
System.out.println("2: Roulette");
System.out.println("3: Check Balance");
System.out.println("4: Exit");
Scanner sc = new Scanner(System.in);
int table = sc.nextInt();
switch (table) {
case 1:
//blackjack.main(new String[]{});
break;
case 2:
Roulette.main(new String[]{});
break;
case 3:
System.out.println("You have : $" + playAmount);
start();
break;
case 4:
System.exit(0);
break;
}
}
}
This is class Roulette.java
package Casino;
import java.util.*;
import java.lang.*;
public class Roulette {
public static void main(String[] args) {
System.out.println("Welcome to the roulette table " + Casino.player());
placeBet();
amountUpdate();
//number();
}
public static int amountUpdate() {
int amount = 0;
if (number() > 0) {
amount += number();
}
if (br() > 0) {
amount += br();
}
if (oe() > 0) {
amount += oe();
}
if (third() > 0) {
amount += third();
}
return amount;
}
public static void placeBet() {
Scanner sc_Choice = new Scanner(System.in);
System.out.println("What would you like to bet on?");
System.out.println("1: Numbers");
System.out.println("2: Black or Red");
System.out.println("3: Odd or Even");
System.out.println("4: One Third");
System.out.println("5: Count Chips");
System.out.println("6: Restart");
int choice = sc_Choice.nextInt();
if (choice > 0 && choice < 7) {
switch (choice) {
case 1:
number();
break;
case 2:
br();
break;
case 3:
oe();
break;
case 4:
third();
break;
case 5:
System.out.println(Casino.amount());
break;
case 6:
Casino.main(new String[]{});
break;
}
} else {
System.out.println("You must choose between 1 and 6");
}
}
public static int number() {
Boolean betting = true;
//int amount = Casino.amount();
int amount = 5000;
int number;
int winnings;
String reply;
int betX;
int betAgain = 1;
Scanner sc_Number = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> bet = new ArrayList<Integer>();
while (betAgain == 1) {
System.out.println("What number would you like to place a bet on?");
int listCheck = sc_Number.nextInt();
if (listCheck >= 0 && listCheck <= 36) {
list.add(listCheck);
} else {
System.out.println("You must choose a number between 0 and 36");
}
System.out.println("How much do you want to bet?");
betX = sc_Number.nextInt();
if (betX > amount) {
System.out.println("You have insufficient funds to make that bet");
number();
} else if (betX < 1) {
System.out.println("You must bet more than 1$");
} else {
bet.add(betX);
amount = amount - betX;
}
System.out.println("Do you want to bet on more numbers?");
reply = sc_Number.next();
if (reply.matches("no|No|false|nope")) {
betAgain = betAgain - 1;
//No - Don't bet again
} else {
betAgain = 1;
//Yes - Bet again
}
int result = wheel();
System.out.println("Spinning! .... The number is: " + result);
for (int i = 0; i < bet.size(); i++) {
if (list.get(i) == result) {
winnings = bet.get(i) * 35;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
}
}
betAgain = betAgain - 1;
}
return amount;
}
public static int wheel() {
Random rnd = new Random();
int number = rnd.nextInt(37);
return number;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int br() {
Scanner sc_br = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Black or Red?");
String replyBR = sc_br.nextLine();
boolean black;
//****************
if (replyBR.matches("black|Black")) {
black = true;
} else {
black = false;
}
System.out.println("How much would you like to bet?");
int betBR = sc_br.nextInt();
if (betBR > amount) {
System.out.println("You have insufficient funds to make that bet");
br();
} else if (betBR < 1) {
System.out.println("You must bet more than 1$");
br();
} else {
amount = amount - betBR;
}
//*****************
boolean resultColour = colour();
if (resultColour == black) {
winnings = betBR * 2;
//PRINT OUT WHAT COLOUR!!!
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
}
System.out.println("Current Balance: " + amount);
return amount;
}
public static boolean colour() {
Random rnd = new Random();
boolean colour = rnd.nextBoolean();
return colour;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int oe() {
Scanner sc_oe = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Odd or Even?");
String replyOE = sc_oe.next();
System.out.println("How much would you like to bet?");
int betOE = sc_oe.nextInt();
if (betOE > amount) {
System.out.println("You have insufficient funds to make that bet");
oe();
}
amount = amount - betOE;
boolean resultOE = oddOrEven();
//PRINT OUT IF IT WAS ODD OR EVEN
if (resultOE == true) {
winnings = betOE * 2;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean oddOrEven() {
Random rnd = new Random();
boolean num = rnd.nextBoolean();
return num;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int third() {
Scanner sc_Third = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on 1st, 2nd or 3rd third?");
String replyT = sc_Third.next();
System.out.println("How much would you like to bet?");
int betT = sc_Third.nextInt();
if (betT > amount) {
System.out.println("You have insufficient funds to make that bet");
third();
}
amount = amount - betT;
boolean resultT = thirdResult();
//PRINT OUT WHAT NUMBER IT WAS AND IF IT WAS IN WHICH THIRD
if (resultT == true) {
winnings = betT * 3;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean thirdResult() {
Random rnd = new Random();
int num = rnd.nextInt(2);
if (num == 0) {
return true;
} else {
return false;
}
}
}
Looks like you're probably running into a StackOverflowException. When you call Casino.amount() inside of Roulette.number(), it then calls Roulette.amountUpdate(), which then calls Roulette.number(). Your methods are stuck in an infinite loop like this. You'll need to redesign your code such that these 3 functions are not all dependent on each other.
Your code is terse, so it's hard to help you fully solve the problem, but I believe you would benefit from splitting up your "amount" variable into separate entities. Keep things like bet amount, winnings, and such separate until you need to combine them.
Another issue you may run into is thatRoulette.amountUpdate() is called twice in Casino.amount(), but Roulette.amountUpdate() will not necessarily return the same thing both times. Consider storing the return value from the first call instead of calling it twice.

Randomly generated numbers won't work after while loop is applied

I am trying to make a combat sequence, but I need to repeat the actual combat. Yet, the HP and enemyHP won't seem to subtract from the randomly generated numbers to give the total after first loop.
I am sorry, if this doesn't make sense. I'm not really good at explaining things...
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class Hayyan {
public int hp = 100;
public int choice = 0;
public static void main(String[] args) {
combatHayyan bob = new combatHayyan();
Hayyan junl = new Hayyan();
while(junl.choice < 10){
System.out.println("Choose a weapon to attack with, type sword for a sword, or axe for an axe ");
bob.attack();
bob.defend();
System.out.println();
if(junl.hp < 0 || bob.enemyHP < 0){
junl.choice = 10;
}
}
}
}
class combatHayyan {
public int enemyHP = 50;
public int yourTotal;
public void attack(){
weapons weapon = new weapons();
Scanner bob = new Scanner(System.in);
switch(bob.nextLine()){
case "sword":
weapon.sword();
System.out.println("Enemy now has " + weapon.total + "HP left!");
break;
case "axe":
weapon.axe();
System.out.println("Enemy now has " + weapon.total + "HP left!");
break;
}
}
public void defend(){
Hayyan lost = new Hayyan();
Random bob = new Random();
int randomness = bob.nextInt(11) + 10;
yourTotal = lost.hp - randomness;
System.out.println("You now have " + yourTotal + "HP left!");
}
}
class weapons {
public int total;
public void sword(){
int bob = 5 + (int)(Math.random() * ((10 - 5) + 1));
combatHayyan llama = new combatHayyan();
total = llama.enemyHP - bob;
}
public void axe(){
int randomGenerate = 5 + (int)(Math.random() * ((10 - 5) + 1));
combatHayyan llama = new combatHayyan();
total = llama.enemyHP - randomGenerate;
}
}
Your question is little broad, but I believe you need to change this:
total = llama.enemyHP - bob;
with this:
total = total - bob;
Just initialize total to llama.enemyHP first. Same thing for defend, you are doing:
yourTotal = lost.hp - randomness;
and I believe you'd rather want:
yourTotal = yourTotal - randomness;
Otherwise, your variables are always recalculated at every pass in the loop.
With my recommandation, you need to refactore your code for it to make sense, but basically, you are not keeping the value modified with the random value, so you are re-doing the random calculation over and over.
EDIT:
You should consider refactoring your code and use a little more OO concepts. Take a look at this, I've refactored it without going too far from your design, so you can follow it and compare to your solution:
class Hayyan {
public static void main(String[] args) {
CombatHayyan combatHayyan = new CombatHayyan();
Scanner scanner = new Scanner(System.in);
while (combatHayyan.bothCombatantsAlive()) {
System.out.println("Choose a weapon to attack with, type sword for a sword, or axe for an axe ");
combatHayyan.attack(scanner);
combatHayyan.defend();
System.out.println();
}
scanner.close();
combatHayyan.printWinner();
}
}
class CombatHayyan {
public int enemyHP = 50;
public int yourHp = 100;
Weapons weapon = new Weapons();
public void attack(Scanner scanner) {
int damage = 0;
switch (scanner.nextLine()) {
case "sword":
damage = weapon.sword();
break;
case "axe":
damage = weapon.axe();
break;
}
enemyHP = enemyHP - damage;
System.out.println("Enemy now has " + enemyHP + "HP left!");
}
public void printWinner() {
String winner = yourHp>0?"You":"The enemy";
int hp = yourHp>0?yourHp:enemyHP;
System.out.println(winner + " won! with " + hp + "HP remaining");
}
public boolean bothCombatantsAlive() {
return enemyHP > 0 && yourHp > 0;
}
public void defend() {
Random random = new Random();
int randomness = random.nextInt(11) + 10;
yourHp = yourHp - randomness;
System.out.println("You now have " + yourHp + "HP left!");
}
}
class Weapons {
public int sword() {
return 5 + (int) (Math.random() * ((10 - 5) + 1));
}
public int axe() {
return 5 + (int) (Math.random() * ((10 - 5) + 1));
}
}

BlackJack in Java with same Deck(s) for Dealer-Player

I am writing a program in Java that is a classic BlackJack Game.
The rules are the same,and we make choices as players and the dealer(CPU) plays under some rules.
My code, that is beneath, makes 2 seperate stacks of Deck(s),one for Player and one for Dealer and each one draws from a different Deck but i want to make them both(Player and Dealer) draw from the same Deck(s).
Any suggestions/corrections on my Code ?
import java.util.Random;
import java.util.Scanner;
public class River
{
private int CardNumber;
private int BeginCards;
private int Decks;
private int[] PartialSumArray = {4,8,12,16,20,24,28,32,36,52};
private int[] BeginPartialSumArray = {4,8,12,16,20,24,28,32,36,52};
private int PickedCard;
private Random randomGenerator = new Random();
//Constructor without definition
public River()
{
CardNumber = 52;
BeginCards = 52;
}
//Constructor with definition
public River(int Decks)
{
CardNumber = Decks * 52;
BeginCards = CardNumber;
this.Decks = Decks;
//Initialize partial sum array for many decks of cards
for (int i=0; i<10; i++)
{
PartialSumArray[i] = PartialSumArray[i] * Decks;
BeginPartialSumArray[i] = PartialSumArray[i] * Decks;
}
System.out.println();
}
//Create random numbers
private int computeRandomSteps(int CardNumber)
{
//System.out.print("stin random , cardnumber is" + CardNumber);
int randomSteps = randomGenerator.nextInt(CardNumber-1);
return randomSteps;
}
public int nextCard()
{
int steps = computeRandomSteps(CardNumber);
int position=0;
for (int i=0; i<CardNumber; i++)
{
if (steps<= PartialSumArray[i])
{
position = i+1;
break;
}
}
CardNumber--;
return position;
}
public int start()
{
int ShuffleLimit;
PickedCard = nextCard();
System.out.println("Picked card is :" + PickedCard);
int HelpVariable = PickedCard-1;
for (int i=0; i<10; i++)
{
if (i >= HelpVariable)
{
PartialSumArray[HelpVariable] = PartialSumArray[i]-1;
HelpVariable++;
}
}
ShuffleLimit = BeginCards/4;
if (CardNumber<ShuffleLimit)
{
for (int i=0; i<9; i++)
{
BeginPartialSumArray[i] = BeginPartialSumArray[i] * Decks;
}
}
return PickedCard;
}
public int ReturnCardNumber()
{
System.out.println("return cardnumber is " + CardNumber);
return CardNumber;
}
}
class Hand
{
private int points;
private int SumPoints=0;
private boolean Ace = true;
Scanner input = new Scanner(System.in);
//Scanner input3 = new Scanner(System.in);
//int Decks = input3.nextInt();
River myRiver = new River();
//River myRiver = new River(Decks);
public int getPoints()
{
points = myRiver.start();
if (points == 1 && Ace)
{
System.out.println("It is an Ace. Do you want to count 1 or 11?");
points = input.nextInt();
Ace = false;
}
SumPoints += points;
System.out.println("Points are : " + SumPoints);
return SumPoints;
}
public int getPointsDealer()
{
points = myRiver.start();
if (points == 1 && Ace)
{
if (SumPoints + 11 > 21)
{
points = 1;
}
else
{
points = 11;
}
Ace = false;
}
SumPoints += points;
System.out.println("Points are : " + SumPoints);
return SumPoints;
}
}
class Player
{
private int points;
private double account=0;
private double bet;
private boolean WinOrLose;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
public double placeBet()
{
System.out.println("How much do you want to bet?");
bet = input1.nextDouble();
return bet;
}
public double profit(boolean WinOrLose)
{
if (WinOrLose)
{
account += bet;
return account;
}
else
{
account -= bet;
return account;
}
}
public int play(River other)
{
Hand myHand = new Hand();
bet = placeBet();
points = myHand.getPoints();
boolean end = true;
String Choice;
while (end)
{
System.out.println("Make a choice");
Choice = input2.nextLine();
switch(Choice)
{
case "DoubleBet":
bet = bet *2;
points = myHand.getPoints();
if (points > 21)
{
System.out.print("Burned!");
WinOrLose = false;
account = profit(WinOrLose);
end = false;
break;
}
else if (points == 21)
{
System.out.print("You won!");
WinOrLose = true;
account = profit(WinOrLose);
end = false;
break;
}
else
{
System.out.println("Your points are :" + points);
end = false;
break;
}
case "stop":
System.out.println("Your points are :" + points);
end = false;
break;
case "Hit":
points = myHand.getPoints();
if (points > 21)
{
System.out.print("Burned!");
WinOrLose = false;
account = profit(WinOrLose);
end = false;
break;
}
else if (points == 21)
{
System.out.print("You won!");
WinOrLose = true;
account = profit(WinOrLose);
end = false;
break;
}
break;
default:
System.out.println("That is not a choice.");
end = false;
break;
}
}
return points;
}
}
class BlackJack
{
public static void main(String args[])
{
int SumPointsPlayer;
int SumPointsDealer;
boolean WinOrLose = true;
double account;
int Decks;
int BeginCards;
int ThisMomentCards;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
System.out.println("How many decks do you want to begin with?");
Decks = input1.nextInt();
River myRiver = new River(Decks);
Player myPlayer = new Player();
//Calculate the cards we have when the game starts
BeginCards = 52 * Decks;
System.out.println("Do you want to start the game? Yes or No.");
String Repeat;
Repeat = input2.nextLine();
while (Repeat.equals("Yes"))
{
ThisMomentCards = myRiver.ReturnCardNumber();
System.out.println("Cards are : " + ThisMomentCards);
//Player's points for 1 round
SumPointsPlayer = myPlayer.play(myRiver);
//If player catches 21 he wins instantly
if(SumPointsPlayer == 21)
{
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//If player catches >21 he loses instantly
else if(SumPointsPlayer > 21)
{
WinOrLose = false;
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//Compare the hand of player and dealer and the bigger wins
else
{
//Dealer's points for 1 round
SumPointsDealer = playDealer(myRiver);
//If dealer catches >21 he loses instantly
if(SumPointsDealer>21)
{
System.out.println("Player wins!");
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//Hand of player bigger than the hand of the dealer , player wins
else if (SumPointsPlayer>SumPointsDealer)
{
WinOrLose = true;
account = myPlayer.profit(WinOrLose);
System.out.println("Player wins. Your account has :" + account + "dollars!");
}
//Hand of player smaller than the hand of the dealer , dealer wins
else if (SumPointsPlayer<SumPointsDealer)
{
WinOrLose = false;
account = myPlayer.profit(WinOrLose);
System.out.println("Player lost. Your account has :" + account + "dollars!");
}
//Hand of player is equal with the hand of the dealer , it is tie
else
{
System.out.println("Player and Dealer are tie!!");
}
}
System.out.println("Do you want to continue the game? Yes or No.");
Repeat = input2.nextLine();
}
}
public static int playDealer(River other)
{
boolean bountry = true;
System.out.println("Dealer plays :");
Hand myHand = new Hand();
int SumPointsDealer = myHand.getPointsDealer();
while (bountry)
{
if (SumPointsDealer<17)
{
SumPointsDealer = myHand.getPointsDealer();
}
else if (SumPointsDealer>21)
{
System.out.println("Dealer burned!");
bountry = false;
}
else
{
bountry = false;
}
}
return SumPointsDealer;
}
}
Some Clarifications:
1) The way we draw randomly a card is based on a strange way but this is not the problem its ok the way the program Does draw randomly cards from the Decks
2) Another problem that i noticed is that in class Hand the code that i have in // is not working as it doesnt allow me to have a System.out.println()
Scanner input = new Scanner(System.in);
//Scanner input3 = new Scanner(System.in);
//int Decks = input3.nextInt();
River myRiver = new River();
//River myRiver = new River(Decks);
I wanted to do this so that i will say with how many Decks the user wants to play
You can do better and easier of code is oriented into objects.
i.e. Collections.shuffle(Deck) replaces that whole random conundrum
where Deck is your created Object made of such attributes as LinkedList and a counter[deck value]
hope that helps.
remove object Card from linked list of main deck and move it into the deck of a player. and yes, you can create as many decks as you want that way.
object Card has attributes Value and Suit.

Categories