Reputation: 31
I've done quite a bit of digging and can't seem to find the answer I'm looking for, I may be asking the question wrong because I'm pretty nooby.
Anyway I'm trying to build a simple Pokemon style game for practice and I can't seem to get the opponent or player hit points to change during the combat event..
I have it so you select 1. to attack with the following code:
if(select == 1){
System.out.println("You strike at the raccoon!");
System.out.println("You deal " + play1.atk + " damage!");
Math.subtract(raccoon1.hp, play1.atk);
the Math.subtract class is just
public static int subtract(int x, int y){
return (x-y);
}
Where it pulls raccoon1.hp from an object I built from an 'Opponent' class that just has:
public class Opponent {
public int hp = 5;
public int def = 0;
public int atk = 1;
}
The player is set up the same way.
I'm sure I'm just missing and/or doing something dumb but any help to a new programmer would be greatly appreciated.
Thanks!
Upvotes: 0
Views: 272
Reputation: 1041
I suggestions you todo somethings like that
public class Opponent {
public int hp = 5;
public int def = 0;
public int atk = 1;
public void attack(Opponent target){
target.hp -= atk;
}
}
After you can simply do
Opponent player = new Opponent ();
Opponent badGuy = new Opponent ();
player.attack(badGuy);
Upvotes: 0
Reputation: 881
This is a question of proper object-oriented programming. Instead of thinking about it in terms of variables, think about it in terms of methods. Don't try to manipulate the variable directly, try to manipulate it through operations done by the class.
In your case...
if(select == 1){
System.out.println("You strike at the raccoon!");
System.out.println("You deal " + play1.atk + " damage!");
//reduce the health by the current attack value of the player
racoon.reduceHealth(play1.getAttackValue());
In your Pokemon
class, or whatever you named the class that you instantiate an instance of when creating a new Pokemon, create a method like this...
public void reduceHealth(int attackValue){
this.hp = this.hp - attackValue;
}
In your Player
class, or whatever you named that class that you instantiate an instance of when creating a new Player, create a method like this...
public int getAttackValue(){
return this.atk;
}
This way, operations done on your objects are done so by its own class, not other classes. When getting information, create methods that return the information you want. When manipulating a variable of an object, use methods of the object to do the manipulation.
Upvotes: 1
Reputation: 61
Racoon1.hp = Math.subtract(raccoon1.hp, play1.atk)
You have to set the returned value equal to raccoon.hp
, or else there's no point in returning a value.
Upvotes: 1