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

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

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/

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
}

problems with dice game

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.

Two Players Fighting With Multiple Attack Options 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.

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