I'm trying to make a turn based fighting game in Java Eclipse. Right now there's nothing wrong with my code but I just needed help figuring out a way to add multiple attacks to each of my characters in the game.
This is my main method
public class Main {
public static Random generator = new Random();
public static void main(String[] args) {
String answer = "yes";
while(answer.equals("yes")) {
Character player1 = new Wraith();
Character player2 = new Paladin();
Scanner charInput = new Scanner(System.in);
System.out.println("Player1, Choose your character");
String choice = charInput.nextLine();
if(choice.equals("Paladin")) {
player1 = new Paladin();
}
if(choice.equals("Wizard")) {
player1 = new Wizard();
}
if(choice.equals("Wraith")) {
player1 = new Wraith();
}
System.out.println("Player2, Choose your character");
String choice2 = charInput.nextLine();
if(choice2.equals("Paladin")) {
player2 = new Paladin();
}
if(choice2.equals("Wizard")) {
player2 = new Wizard();
}
if(choice2.equals("Wraith")) {
player2 = new Wraith();
}
//player1.name = input("Player1 pick your character(Paladin, Wraith, Wizard)", charInput);
//player2.name = input("Player2 pick your character(Paladin, Wraith, Wizard)", charInput);
System.out.println(player1.name + " vs. " + player2.name);
System.out.println(player1.health + " vs. " + player2.health);
while (player1.isAlive() && player2.isAlive()) {
System.out.println(player1.name + ": " + player1.health);
System.out.println(player2.name + ": " + player2.health);
int damage;
damage = player1.attack(player2);
System.out.println(player1.name + " hits " + player2.name + " for " + damage);
damage = player2.attack(player1);
System.out.println(player2.name + " hits " + player1.name + " for " + damage);
}
if(player1.isAlive()) {
System.out.println(player1.name + " wins!");
} else if (player2.isAlive()) {
System.out.println(player2.name + " wins!");
} else {
System.out.println("It's a draw!");
}
}
}
private static String input(String string, Scanner charInput) {
return null;
}
}
This is one of my character classes
public class Wizard extends Character {
public int dexterity = 25;
public static Random generator = new Random();
public Wizard(){
super();
this.name = "Wizard";
this.strength = 10;
this.defense = 8;
this.health = 95;
}
public int attack(Character target){
boolean criticalHit =Main.generator.nextInt(150) < dexterity;
int damage = this.strength * 2;
if(criticalHit){
damage *= 2;
System.out.println("*** Critical Hit ***");
}
int damageDealt = target.takeDamage(damage);
return damageDealt;
}
}```
And this is my main character class
public class Character {
public String name;
public int strength;
public int health;
public int defense;
public int takeDamage(int damage){
int damageTaken = damage - this.defense;
this.health -= damageTaken;
return damageTaken;
}
public int attack(Character target){
int damage = this.strength * 2;
int damageDealt = target.takeDamage(damage);
return damageDealt;
}
public boolean isAlive(){
return health > 0;
}
}```
also I'm new to coding and stack overflow so and suggestions on how to make my posts make more sense or something like that is much appreciated
nice implemention of a battle system.
when a Character performs an attack you choose which attack that should be and execute:
public int attack(Character target){
AttackMode mode = determineAttackMode(target); // the charater chooses what kind of attack he will execute during this attack
switch(mode){
case AttackMode.DOUBLESTRIKE: return attackDoubleStrike(target);
case AttackMode.BURST: return attackBurst(target);
default: return attackDefault(target); // your previously implemented method attack(target)
}
}
The AttackMode is an Enum class:
enum AttackMode {DEFAULT, DOUBLESTRIKE, BURST}
i'm not sure how double damage is dealt, so this is a guess here
public int attackDoubleStrike(Character target){
int firstStrike = attackDefault(target);
int secondStrike = attackDefault(target);
return firstStrike + secondStrike;
}
Related
I'm trying to run the constructor with:
Main fight1 = new Main("Homeless Man", "Rusty Fork", 100, 110, 30);
I Want it to deal a random amount of damage (within a specified range), save that value for the next stage of combat, and then for the players health to drop and be stored respectively. I also want it to repeat until the enemy no loner has health. I can update the code below with the rest of the program if you want to try it yourself. The current output is:
Will you:
-Attack (1)
-Consume Item (2)
-Run (3)
1
Homeless Man hits you with a Rusty Fork, Dealing 54 damage!
You now have 903 HP left!
You hit Homeless Man With an attack using your Fists dealing 42 damage!
Homeless Man now has 60 HP left!
The actual program:
private static int playerMaxDam = 75;
private static int playerMinDam = 30;
private static int damageDelt;
private static int playerHP = 1000;
private static String currentWeapon = "Fists";
//default enemy variables
private static String enemyName;
private static String enemyItem;
private static int enemyHP;
private static int enemyMaxDam;
private static int enemyMinDam;
private static int damageTaken;
//enemy health
public int getDamageTaken() {
Random rand = new Random();
damageTaken = rand.nextInt(enemyMaxDam - enemyMinDam + 1) + enemyMinDam;
return damageTaken;
}
public int getDamageDelt(){
Random rand = new Random();
damageDelt = rand.nextInt(playerMaxDam = playerMinDam + 1) + playerMinDam;
return damageDelt;
}
public Main(String _enemyName, String _enemyItem, int _enemyHP, int _enemyMaxDam, int _enemyMinDam) {
enemyName = _enemyName;
enemyItem = _enemyItem;
enemyHP = _enemyHP;
enemyMaxDam = _enemyMaxDam;
enemyMinDam = _enemyMinDam;
}
public String getPlayerWeapon() {
String playerWeapon = null;
String fists = "1";
String bloody_Spoon = "0";
if(fists.equals("1")) {
playerMaxDam = 75;
playerMinDam = 30;
playerWeapon = "Fists";
}else {
if(bloody_Spoon.equals("1")) {
playerMaxDam = 100;
playerMinDam = 75;
playerWeapon = "Bloody Spoon";
}
}
return playerWeapon;
}
public void displayCombat() {
//enemy
int enemyHealth = (enemyHP - getDamageDelt());
//player
int playerHealth = (playerHP - getDamageTaken());
//player armor
int clothes = 1;
int tux = 0;
//player weapon
String playerWeapon = currentWeapon;
int fists = 1;
int bloody_Spoon = 0;
Scanner in = new Scanner(System.in);
System.out.println("Will you:\n -Attack (1)\n -Consume Item (2) \n -Run (3)");
String userInput = in.nextLine();
if(userInput.equals("1")) {
System.out.println(enemyName + " hits you with a " + enemyItem + ", Dealing " + getDamageDelt() + " damage!");
System.out.println("You now have " + playerHealth + " HP left!");
System.out.println("You hit " + enemyName + " With an attack using your " + playerWeapon + " dealing " + getDamageDelt() + " damage!");
System.out.println(enemyName + " now has " + (enemyHP - getDamageDelt()) + " HP left!");
}else {
if(userInput.equals("3")) {
System.out.println("You managed to escape the fight with " + playerHP + " left!");
}
}
}
In your displayCombat method, you never actually subtract the damage dealt to the enemy from his health. In this method you shouldn't initialize a new variable (int enemyHealth = (enemyHP - getDamageDelt());). Instead you should have something like enemyHP -= getDamageDelt();, so that the damage is acutually subtracted from the enemies health.
Im writing a program similar to a game called shut the box. The game asks the player to roll 2 die, and then the player chooses to cover both numbers individually (in the boolean array), or the total of the two.
I'm having difficulty returning two values of the int method roll() which is supposed to roll two die.
Heres my code for the main class:
public class clacker {
private int play;
private int die1;
private int die2;
private boolean[] table;
private final int high = 6;
private final int low = 1;
private int range;
public clacker()
{
range = high-low+1;
table = new boolean[13];
play = 0;
}
public void roll()
{
die1 = (int)(Math.random()*range+low);
die2 = (int)(Math.random()*range+low);
}
public void value(char ch)
{
if(ch == 'i' || ch == 'I')
{
table[die1] = true;
table[die2] = true;
displayBoard();
}
else if(ch == 'T' || ch == 't')
{
table[die1+die2] = true;
displayBoard();
}
else
{
roll();
}
}
public void displayBoard()
{
for(int i = 1; i<table.length; i++)
{
if(table[i] == false)
{
System.out.print(" " + i + " ");
}
else
{
System.out.print(" / ");
}
}
}
}
and for the test class:
public class clackerTest {
public static void main(String[] args) {
clacker oo = new clacker();
EasyReader kboard = new EasyReader();
System.out.println("Press anything to roll the dice. ");
char roll= kboard.readChar();
int dice1 = oo.roll();
int dice2 = oo.roll();
System.out.println("You rolled " + dice1 + " and a " + dice2 + "!");
System.out.println("Cover Individual or Total: (enter i or t)");
char roll2 = kboard.readChar();
}
}
Why don't you just roll() twice? Modify roll() to return one int.
public int roll() {
return (int)(Math.random()*range+low);
}
And now, from within clackerTest (java conventions dictates you name this ClackerTest):
int dice1 = oo.roll();
int dice2 = oo.roll();
So I'm trying to write the most simple game , everytime "the monster" attacks "the player" I want the variable "int totalHealth" to be lowered .
public void attack(Player somePlayer) {
int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
int remainingHealth = totalHealth - damage;
if (remainingHealth == 0 || remainingHealth < 0) {
System.out.println("Your player died");
} else {
System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
System.out.println("Your remaining health is - " + (remainingHealth - somePlayer.getStrength()));
}
}
But the problem is that variable "remainingHealth" stays same , only the first time when I run the code it lowers , every next time it stays same, I guess the problem is in this line :
int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
I guess everytime I run the code
somePlayer.getHitpoints()
takes the inserted integer from constructor and that's the problem.
I need to figure out the way to store the remaining health in a variable somehow
Player class :
public class Player implements ISavable{
private String name;
private int hitPoints ;
private int strength ;
private String weapon;
private int damage;
private int totalHealth = hitPoints + strength;
public Player(String name, int damage , int hitPoints , int strength) {
this.name = name;
this.damage = damage;
this.weapon = "Sword";
this.hitPoints = hitPoints;
this.strength = strength;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHitPoints() {
return hitPoints;
}
public void setHitPoints(int hitPoints) {
this.hitPoints = hitPoints;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public String getWeapon() {
return weapon;
}
public void setWeapon(String weapon) {
this.weapon = weapon;
}
public int getTotalHealth() {
return totalHealth;
}
public void setTotalHealth(int totalHealth) {
this.totalHealth = totalHealth;
}
#Override
public String toString() {
return "Player{" +
"name='" + name + '\'' +
", hitPoints=" + hitPoints +
", strength=" + strength +
", weapon='" + weapon + '\'' +
'}';
}
#Override
public List<String> write() {
List<String> values = new ArrayList<String>();
values.add(0, this.name);
values.add(1, "" + this.hitPoints);
values.add(2, "" + this.strength);
values.add(3, "" + this.weapon);
values.add(4,"" + this.damage);
return values;
}
#Override
public void read(List<String> savedValues) {
if (savedValues != null && savedValues.size()>0){
this.name = savedValues.get(0);
this.hitPoints = Integer.parseInt(savedValues.get(1));
this.strength = Integer.parseInt(savedValues.get(2));
this.weapon = savedValues.get(3);
}
}
public void attack(Monster someMonster){
int health = someMonster.getHitPoints();
int remainingHealth = health - damage;
if (remainingHealth == 0 || remainingHealth < 0) {
System.out.println("You killed the monster !!!");
} else {
System.out.println("You attacked the monster " + " and made " + this.damage + " damage");
System.out.println("Monsters remaining health is - " + remainingHealth);
}
if (someMonster.isDead()){
this.hitPoints = 100;
this.strength = 50;
}
}
public void healPlayer(Player somePlayer){
int hp = somePlayer.getHitPoints();
hp += 10;
System.out.println("You healed the player for 10hp , your current hp is " + hp);
}
}
You are not updating the value of totalHealth, you initialize it everytime that attack() method is called, so you always have the same Health.
You can solve it putting out of the attack() method the line:
int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
EDIT:
public void attack(Player somePlayer) {
somePlayer.totalHealth = somePlayer.totalHealth - this.damage;
if (somePlayer.totalHealth.equals(0) || somePlayer.totalHealth < 0) {
System.out.println("Your player died");
} else {
System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
System.out.println("Your remaining health is - " + (somePlayer.totalHealth - somePlayer.getStrength()));
}
}
On Player create a function updateHealth(int newHealth) that sets the variable returned from getHitPoints() to newHealth. Then just append somePlayer.updateHealth(somePlayer.getHitPoints() - damage); at the end of the attack function.
You should have a representation of health, defining in Player totalHealth.
You may use a method which calculate the total health (cause your player could get an item that increases strenght or an item that allow heal you).
Then you should use another variable in Player, remainingHealth and initialize it as remainingHealth = totalHealth
public class Player {
float totalHealth;
float remainingHealth;
...
public Player(...) {
this.remainingHealth = this.totalHealth;
...
}
...
}
When you want decrease the health of your player you should use remainingHealth.
public void attack(Player somePlayer) {
somePlayer.remainingHealth -= this.damage;
if (somePlayer.remainingHealth <= 0) {
System.out.println("Your player died");
} else {
System.out.println("The monster attacked ...");
System.out.println("Your remaining health is - " + somePlayer.remainingHealth);
}
}
I am a beginner in Java. I am making a basic turn-based game, but I have problems with the fight system. I attack the randomly selected enemy with the chosen weapon until it dies, however I can't figure out how to decrease my HP.
I tried the following method in the Character class:
public void attack(int damageAmount, int myHealth) {
if (damageAmount >= this.health || myHealth<=0) {
this.health = 0;
System.out.println( this.name + " is dead!");
this.dead = true;
} else {
this.health -= damageAmount;
System.out.println("The remaining life of " + this.name + " is: " + this.health);
player.setHealth(myHealth-this.damage);
System.out.println("Your remaining HP: "+ myHealth);
It doesn't work, because the " player.setHealth()" is not reachable in the Character class.
How could I solve this? Should I make another class for the fight system?
Also, canI make my code simplier by using inheritance or interfaces?
Thanks in advance guys!
MAIN CLASS
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int size = 0;
public static void main(String[] args) {
int myHealth = 1000;
int myDamage = 5;
Scanner sc = new Scanner(System.in);
Character zombie = new Character("Zombie", 500, 10);
Character wolf = new Character("Wolf", 200, 30);
Character dragon = new Character("Dragon", 1000, 200);
Character bigDragon = new Character("Big Dragon", 2000, 400);
Character vampire = new Character("Vampire", 1000, 250);
ArrayList<Character> characterList = new ArrayList<>();
characterList.addAll(Arrays.asList(
zombie,
wolf,
dragon,
bigDragon,
vampire
));
Weapon fist = new Weapon("Fist", 5);
Weapon sword = new Weapon("Sword", 50);
Weapon bow = new Weapon("Bow", 40);
Weapon crossBow = new Weapon("Crossbow", 35);
Weapon revolver = new Weapon("Revolver", 100);
ArrayList<Weapon> weaponList = new ArrayList<>();
weaponList.addAll(Arrays.asList(
fist,
sword,
bow,
crossBow,
revolver
));
size = characterList.size();
int whichCharacter = random();
for (int i = 0; i < characterList.size(); i++) {
System.out.println((i + 1) + ". character: " + characterList.get(random()).getName());
}
System.out.println("Your name!");
String myName = sc.nextLine();
Character player = new Character(myName, 1000, myDamage);
System.out.println("Your name: " + myName);
System.out.println("Your HP: " + myHealth);
System.out.println("Your attack power: " + myDamage);
System.out.println();
System.out.println();
System.out.println("You were attacked by a(n):");
System.out.println("Name: " + characterList.get(whichCharacter).getName());
System.out.println("HP: " + characterList.get(whichCharacter).getHealth());
System.out.println("Attack power: " + characterList.get(whichCharacter).getDamage());
System.out.println();
System.out.println("You attack with...");
System.out.println();
System.out.println("1. fist");
System.out.println("2. sword");
System.out.println("3. bow");
System.out.println("4. crossbow");
System.out.println("5. revolver");
int choice = sc.nextInt();
while (!characterList.get(whichCharacter).isDead()) {
switch (choice) {
case 1:
myDamage = 5;
break;
case 2:
myDamage = sword.getWeaponDamage();
break;
case 3:
myDamage = bow.getWeaponDamage();
break;
case 4:
myDamage = crossBow.getWeaponDamage();
break;
case 5:
myDamage = revolver.getWeaponDamage();
break;
default:
myDamage = 5;
}
while (!characterList.get(whichCharacter).isDead()) {
characterList.get(whichCharacter).attack(myDamage, myHealth);
//characterList.get(whichCharacter).attack(characterList.get(whichCharacter).getDamage(), player.getHealth());
}
}
}
public static int random() {
int szam = (int) (Math.random() * size);
return szam;
}
}
CHARACTER CLASS
package com.company;
/**
* Created by Norbi on 2017.04.29..
*/
public class Character {
private String name;
private int health;
private int damage;
private boolean dead = false;
public boolean isDead() {
return dead;
}
public void setDead(boolean dead) {
this.dead = dead;
}
public Character(boolean dead) {
this.dead = dead;
}
public Character(String name, int health, int damage) {
this.name = name;
this.health = health;
this.damage = damage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 void attack(int damageAmount, int myHealth) {
if (damageAmount >= this.health || myHealth<=0) {
// this.health = 0;
System.out.println(this.name + " is dead!");
this.dead = true;
} else {
this.health -= damageAmount;
System.out.println("The remaining life of " + this.name + " is: " + this.health);
System.out.println("Your remaining HP: "+ myHealth);
}
}}
WEAPON CLASS
package com.company;
/**
* Created by Norbi on 2017.04.29..
*/
public class Weapon {
private String name;
private int weaponDamage;
public Weapon(String name, int weaponDamage) {
this.name = name;
this.weaponDamage = weaponDamage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeaponDamage() {
return weaponDamage;
}
public void setWeaponDamage(int weaponDamage) {
this.weaponDamage = weaponDamage;
}
}
I have made some changes in looping logic, I hope it would help :
while (!characterList.get(whichCharacter).isDead() && !player.isDead()) {
switch (choice) {
case 1:
myDamage = 5;
break;
case 2:
myDamage = sword.getWeaponDamage();
break;
case 3:
myDamage = bow.getWeaponDamage();
break;
case 4:
myDamage = crossBow.getWeaponDamage();
break;
case 5:
myDamage = revolver.getWeaponDamage();
break;
default:
myDamage = 5;
}
while (!characterList.get(whichCharacter).isDead() && !player.isDead()) {
characterList.get(whichCharacter).attack(myDamage, myHealth);
player.attack(characterList.get(whichCharacter).getDamage(), player.getHealth());
//characterList.get(whichCharacter).attack(characterList.get(whichCharacter).getDamage(), player.getHealth());
}
}
Since you need an instance of player to call its methods, you could pass it as an input parameter, for example you could call the attack method like this:
characterList.get(whichCharacter).attack(player);
and modify it like this (simply replacing damageAmount and myHealth with the corresponding methods from Character):
public void attack(Character characterAttacked) {
if (characterAttacked.getDamage() >= this.health || characterAttacked.getHealth() <= 0) {
this.health = 0;
System.out.println( this.name + " is dead!");
this.dead = true;
} else {
this.health -= characterAttacked.getDamage();
System.out.println("The remaining life of " + this.name + " is: " + this.health);
characterAttacked.setHealth(characterAttacked.getHealth() - this.damage);
System.out.println("Your remaining HP: "+ characterAttacked.getHealth());
}
}
As I tried to prepare an answer with a suggestion for a working attack method I found out, that your attack method does not work for me.
So here some general suggestions to improve your code:
Use an instance of Character for the player too.
pass that instance to the attack method.
Improve the use of lists (I will add an example below.)
use a Map with the user entered number as key instead of the switch statement.
Improved use of lists:
// Use the generic interface List instead of implementation class.
// You don't need extra ArrayList, just use the result of Arrays.asList
// - if you don't need to change the list afterwards.
List<Character> characterList =
Arrays.asList(
zombie,
wolf,
dragon,
bigDragon,
vampire);
Use Map for weapons:
Map<Integer, Weapon> weapons = new HashMap<>();
weapons.put(1, fist);
weapons.put(2, sword);
// and so on - you get the idea
while (!characterList.get(whichCharacter).isDead() && !player.isDead()) {
Weapon weapon = weapons.get(choice);
if (null == weapon) {
weapon = fist;
}
myDamage = weapon.getDamage();
// and here you can continue your code
}
Hope that above suggestions also help you a bit further.
import java.util.Random;
import java.lang.Math;
import java.lang.String;
public class GameOfNim
{
private int min,max;
private int turn;
private int firstturn;
private int stupid;
private int smart;
private int computer;
private int user;
private int first;
private int pile;
public GameOfNim(int min, int max ){
pile=(int)(Math.random()*max+min);
smart=(int)(Math.random()*100);
stupid=(int)(Math.random()*100);
System.out.println("Pile size is "+pile);
firstturn=(int)(Math.random()*100 + 1);
computer=0;
user=1;
if(firstturn>50)
{
firstturn=user;
}
else
{
firstturn=computer;
}
firstturn=turn;
}
public void play()
{
if(smart>50)
{
System.out.println("Computer is playing smart");
}
else
{
System.out.println("Computer is playing stupid");
}
if(firstturn==user)
{
System.out.println("You go first");
}
else
{
System.out.println("Computer goes first");
}
turn = firstturn;
while(pile-1>0)
{
if(turn==user)
{
String take = "How many marbles do you want to take away?";
System.out.println(take);
int take2 = Integer.parseInt(take);
while(take2>(int)(pile/2))
{
System.out.println("Only take away half or less from the pile");
take = "How many marbles do you want to take away?";
take2= Integer.parseInt(take);
}
pile= pile-take2;
System.out.println("There are "+pile+" marbles left");
turn=computer;
}
else
{
if(smart>50)
{
pile -= smartTake();
}
else
{
pile -= stupidTake();
}
turn = user;
}
}
}
private int smartTake()
{
int x = (int)(Math.random())*2-1;
int sMarbles= (int)Math.pow(2,x);
while (sMarbles > (.5 * pile) || sMarbles==0)
{
x = (int)(Math.random())*2-1;
sMarbles = (int)Math.pow(2,x);
}
System.out.println("The computer took away " + sMarbles +" marbles");
return sMarbles;
}
private int stupidTake(){
int stMarbles = pile/2;
while (stMarbles > (.5*pile) || pile==0)
{
stMarbles = pile/2;
}
System.out.println("The Computer took away " + stMarbles +" marbles");
return stMarbles;
}
}
this is my game of nim class
public class Project5
{
public static void main(String args[])
{
String k = "yes";
String str;
Scanner console = new Scanner(System.in);
System.out.print("Enter the minimum number of marbles in your pile: ");
int min = console.nextInt();
System.out.print("Enter the maximum number of marbles in your pile: ");
int max= console.nextInt();
GameOfNim game = new GameOfNim(min, max);
game.play();
System.out.println( " Thank you and good bye!");
}
}
and this is my driver class
for some reason everytime i run it it goes all the way to the point where it says "Computer goes first" then nothing else happens. im assuming its stuck in a loop but i cant seem to find out why. any help will be appreciated