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));
}
}
Related
My first class that creates the ArrayList and populates it with the Skill objects
import java.util.ArrayList;
public class Skill {
String skillName;
int skillValue;
public static ArrayList<Skill> skillList = new ArrayList<Skill>();
public Skill(String newSkillName, int newSkillValue){
setSkillName(newSkillName);
setSkillValue(newSkillValue);
}
public static void initializeSkillList(){
//Creating the Skill obj's
Skill str = new Skill("Str", 1);
Skill dex = new Skill("Dex", 1);
Skill intl = new Skill("Int", 1);
Skill con = new Skill("Con", 3);
//Adding them to the Skill ArrayList
skillList.add(str);
skillList.add(dex);
skillList.add(intl);
skillList.add(con);
//Debug statement to check if the values are correct
System.out.println(skillList.get(1).skillValue);
}
}
I am attempting to access the objects skillValue and skillName from the ArrayList in my Main.java class. I have setters and getters.
This is the Main class
import java.util.Scanner;
public class Main {
static Character playerCharacter;
static boolean charCreationComplete = false;
static boolean endGame = false;
static Scanner scnr = new Scanner(System.in);
public static void main(String[] args){
System.out.println("\n\nWelcome to Garterra!\n\n");
Archetype.initializeArchetypeList();
Skill.initializeSkillList();
if (!charCreationComplete){
charCreation(scnr);
charCreationComplete = true;
}
charCreation(scnr); then accesses the skillList through getters and setters
charCreation() Method:
private static void charCreation(Scanner scnr){
System.out.println("\nEnter player name:\n\n");
String newName = scnr.nextLine();
System.out.println("You Entered " + newName + " for your name!\n");
System.out.println("Next, Choose your Archetype: 0 = Ranger\n");
int archetypeIndex = scnr.nextInt();
Character.currArchetype = Archetype.archetypeList.get(archetypeIndex);
Character.archetypeName = Archetype.archetypeList.get(archetypeIndex).getArchetypeName();
System.out.println("You have chosen " + Character.archetypeName + ".\nThis gives you " + Character.currArchetype.totalSpendableSkillPoints + " total spendable skill points!\n");
System.out.println("Now, spend those skill points.\n");
if (Character.currArchetype.getArchetypeName().contains("Ranger")){
Ranger.dexModifierCalc(1);
Ranger.conModifierCalc(1);
}
while (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Strength?\nThis impacts your melee weapon damage and carry weight.\n");
int strAddPoints = scnr.nextInt();
Skill.skillList.get(0).setSkillValue(Skill.skillList.get(0).getSkillValue() + strAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - strAddPoints);
strAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(0).getSkillValue() + "\n");
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Dexterity?\nThis impacts your ranged weapon damage.\n");
int dexAddPoints = scnr.nextInt();
Skill.skillList.get(1).setSkillValue(Skill.skillList.get(1).getSkillValue() + dexAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - dexAddPoints);
dexAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(1).getSkillValue() + "\n");
}
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Intelligence?\nThis impacts your magic damage.\n");
int intAddPoints = scnr.nextInt();
Skill.skillList.get(2).setSkillValue(Skill.skillList.get(2).getSkillValue() + intAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - intAddPoints);
intAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(2).getSkillValue() + "\n");
}
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Strength?\nThis impacts your melee weapon damage and carry weight.\n");
int conAddPoints = scnr.nextInt();
Skill.skillList.get(3).setSkillValue(Skill.skillList.get(3).getSkillValue() + conAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - conAddPoints);
conAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(3).getSkillValue() + "\n");
}
}
int newHealthPoints = Character.healthPointsCalc();
System.out.println("You have " + newHealthPoints + " health points!\n\n");
int newTotalCarryWeight = Character.carryWeightCalc(Character.currArchetype.getLevel());
System.out.println("Your total carry weight is " + newTotalCarryWeight + ".\n");
int newExperince = 0;
playerCharacter = new Character(newName, newHealthPoints, newExperince, 1, Archetype.archetypeList.get(archetypeIndex), newTotalCarryWeight);
}
If you create a getter for "skillList" then you can just say
Skill.getSkillList();
And then do whatever you want with this list.
To make your code a little better, change this
public static ArrayList<Skill> skillList = new ArrayList<>();
to this
public static List<Skill> skillList = new ArrayList<>();
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.
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!
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.
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.