So what im trying to do is to call an external method upon an object, its a bit trickier than I expected and am having problems properly implementing it.
The method is:
attack(Player victim)
The method needs to call a hit() method on an object; then if the hit() method was successful (test this through a boolean?):
use an if statement to call a damage() method upon the object to determine the damage
call takeDamage() upon (PlayerVictim) to inflict the damage.
Here's the player class that ive coded so far; the attack() method is at the bottom.
My main question is how to use an external method(s) damage() on the currentWeapon and takeDamage() on Player Victim
public class Player
{
private String myPlayerName;
private Weapon myWeapon;
private int myCurrentHealth;
private int myMaxHealth;
private int myNumPotions;
/**
* Constructor initializing class Player
* Parameters of the player should be:
* player name, players initial health, the players weapon.
*/
public Player(String myPlayer, int initialHealth, Weapon currentWeapon) {
myPlayerName = myPlayer;
this.myWeapon = currentWeapon;
myMaxHealth = 30;
myCurrentHealth = initialHealth;
myNumPotions = 0;
}
/**
* Attack method which attacks opposing player
* with current equipped weapon.
*/
public void attack(Player victim) {
currentWeapon.hit();
if (boolean currentWeapon.hit() = true) {
currentWeapon.damage(int dam);
return dam;
}
Player victim.takeDamage(int damage);
}
}
and the weapon class:
import java.util.Random;
public class Weapon
{
private int myHitProb;
private int myMaxDamage;
private Random myRNG;
/**
* Create a new weapon with a hit probability and damage
*/
public Weapon(int hitProb, int damage) {
myHitProb = hitProb;
myMaxDamage = damage;
myRNG = new Random();
}
public boolean hit() {
int r = myRNG.nextInt(100);
if (r < myHitProb) {
return true;
}
else {
return false;
}
}
public int damage() {
int dam = myRNG.nextInt(myMaxDamage) + 1;
return dam;
}
}
Your attack() method may be many things, but compilable java it is not.
Perhaps this is what you meant:
public void attack(Player victim) {
if (currentWeapon.hit()) {
victim.takeDamage(currentWeapon.damage());
}
}
Try to remember this guideline: If it seems hard, you're probably doing it the wrong way (unless you're working on the Mars Lander program :) )
Related
how can I use the constructor from another class in java to make an object through a method in separate class. For example below is a constructor in a player class
public class Player extends Entity {
public Player(int maxEnergy, int x, int y) {
this.maxEnergy = maxEnergy;
this.energy = maxEnergy;
carryingGhost = false;
xPos = x;
yPos = y;
}
Which I want to use and create objects (player) through a method called
private Player createPlayer() {
and the above method is in separate class as
public class GameEngine {
**The method must return a Player object that represents the player in the
game. it must set the maxEnergy for the player, and the
X and Y positions corresponding to a tile position in the current level.
I have tried to initialize player within method with parameters and
without parameters as**
Player player = new Player(int maxEnergy, int x, int y);
this.player.getEnergy();
this.player.getMaxEnergy();
this.player.setPosition(x, y);
return player;
}
But it give errors.Any help will be appreciated.I am quite close to assume its not possible to have created objects like this.
below I share the complete game engine which is working with other classes as well .
import java.awt.Point;
import java.util.ArrayList;
import java.util.Random;
public enum TileType {
WALL, FLOOR1, FLOOR2, BANK, BREACH, DOOR;
}
public static final int LEVEL_WIDTH = 35;
public static final int LEVEL_HEIGHT = 18;
private Random rng = new Random();
private int levelNumber = 1; //current level
private int turnNumber = 1;
private GameGUI gui;
private TileType[][] level;
private ArrayList<Point> spawnLocations;
private Player player;
private Ghost[] ghosts;
public GameEngine(GameGUI gui) {
this.gui = gui;
}
private TileType[][] generateLevel() {
//YOUR CODE HERE
return null; //change this to return the 2D arrayof TileType
//values that you create above
}
private ArrayList<Point> getSpawns() {
ArrayList<Point> s = new ArrayList<Point>();
// YOUR CODE HERE
return s;
}
private Ghost[] addGhosts() {
//YOUR CODE HERE
return null; //change this to return an array of ghost objects
}
**/**
* Creates a Player object in the game. The method instantiates
* the Player class and assigns values for the energy and position.
* The first version of this method should use fixed a fixed position
for the player to start, by setting fixed X and Y values when calling
the constructor in the Player class. The second version of this method
should use the spawns ArrayLis to select a suitable location to spawn
the player and removes the Point from the spawns ArrayList. This will
prevent the Player from being added to the game inside a wall, bank or
breach for example.
#return A Player object representing the player in the game
*/**
private Player createPlayer() {
//YOUR CODE HERE
return null; //change this to return a Player object
}
public void movePlayerLeft() {
}
public void movePlayerRight() {
}
public void movePlayerUp() {
}
public void movePlayerDown() {
}
private void hitGhost(Ghost g) {
}
private void moveGhosts() {
}
private void moveGhost(Ghost g) {
}
private void cleanDefeatedGhosts() {
}
private void nextLevel() {
}
private void placePlayer() {
}
public void doTurn() {
cleanDefeatedGhosts();
moveGhosts();
gui.updateDisplay(level, player, ghosts);
}
public void startGame() {
level = generateLevel();
spawnLocations = getSpawns();
ghosts = addGhosts();
player = createPlayer();
gui.updateDisplay(level, player, ghosts);
}
}
I have used below method and its not showing error so far.
private Player createPlayer() {
int energy=player.getEnergy();
int maxEnergy=player.getMaxEnergy();
int xPos=player.xPos;
int yPos=player.yPos;
return new Player(maxEnergy,xPos,yPos);
}
The following should do it:
private Player createPlayer() {
int defaultMaxEnergy = 10; // Whatever value it should have
int initialX = 1; // Whatever value it should have
int initialY = 1; // Whatever value it should have
return new Player(defaultMaxEnergy, initialX, initialY);
}
Since the values are not in your descriptions I just selected a random number but you can pick whatever integers you want and that makes sense.
Does something like this work for your case?
public class GameEngine {
private Player createPlayer() {
return new Player(1,2,3);
}
}
Add a default no-args constructor in the player class. Once you create a constructor with Arg, java will not auto provide default one.
You have already declared Player
private Player player;
So you must not try to reinitialize using same variable name, rather
private Player createPlayer() {
Player newPlayer = new Player();
// set the different props of the Player obj
return newPlayer ;
}
What is the error which you are facing ? Can you share that ?
This question already has answers here:
How to make a method in a class, manipulate variables in another class?
(2 answers)
Closed 5 years ago.
I created a simple method in my CardGames class that replicates a card game to play around with conditional statements. I call the method from a separate Player class because the player earns/loses points based on the card. I want the method to be able to change the player objects points variable.
What I want to have happen is when the playSimpleCardGame gets called by the Player object, the method changes the Player object's points.
But when I run it the points do not change. I've tried extending/implementing both classes (i.e. shooting in the dark). I also created an instance variable points in the CardGames class but then the Player object does not have points as a variable. What am I missing?
public class Player
{
private int points;
public static void main(String[] args)
{
CardGames steve = new CardGames();
System.out.println(steve.playSimpleCardGame("red"));
System.out.println(steve.playSimpleCardGame("red"));
System.out.println(steve.playSimpleCardGame("black"));
System.out.println(steve.playSimpleCardGame("black"));
System.out.println(steve.points);
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color)
{
if (color.equalsIgnoreCase("red"))
return points = points + 1;
else
return points = points - 2;
}
}
public class Player
{
private int points;
public Player(){
points=0;
}
public static void main(String[] args)
{
CardGames game = new CardGames();
Player steve = new Player();
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(steve.points);
}
public int getPoints() {
return points;
}
public void addPoints(int p) {
this.points = points + p;
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color, Player player)
{
if (color.equalsIgnoreCase("red"))
{
player.addPoints(1);
return player.getPoints();
}
else
{
player.addPoints(-2);
return player.getPoints();
}
}
}
Firstly, there is no need to extend CardGames class by the Player class. Secondly, even if you wish to do it, it will be a bad design. I won't go into the design part. The following code should answer your problem :
public class Player
{
public Integer points;
public Player(){
points=0;
}
public static void main(String[] args)
{
CardGames game = new CardGames();
Player steve = new Player();
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(steve.points);
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color, Player player)
{
if (color.equalsIgnoreCase("red"))
return player.points = player.points + 1;
else
return player.points = player.points - 2;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have got some code and it all seems to work apart from one error that appears. This stops the whole program running. Please could you have a look at the code and see what the issue is. This is a space invaders game and this is the class that contains the public static void main.
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25;
public static int ALIEN_WIDTH = 15;
private int leftPosition = 0;
private int heightPosition = 0;
private boolean hitState = false;//Whether this alien has already been shot
private Image alienImage = null;
SpaceInvaders spaceInvaders = null;
/**
*
*/
public Alien(Image ai, SpaceInvaders si) {
alienImage = ai;
spaceInvaders = si;
}
/**
* Returns whether ythe alien had been hit
*/
public boolean hasBeenHit() {
return hitState;
}
/**
* Check if a shot fired hit an alien
*/
public boolean hitAlien(int x, int y) {
//Is the alien currently alive?
if (hitState) {
//If it's alreay been shot then return false;
return false;
}
//First lets check the X range
if ((x >= leftPosition) && (x <= (leftPosition+ALIEN_WIDTH))) {
//X is ok, now lets check the Y range
if ((y >= heightPosition) && (y <= (heightPosition+ALIEN_HEIGHT))) {
//We shot an alien!
hitState = true;
return true;
}
}
return false;
}
/**
* Set the position of the alien on the screen
*/
public void setPosition(int x, int y) {
leftPosition = x;
heightPosition = y;
}
/**
* Returns the current x position of the alien
*/
public int getXPos() {
return leftPosition;
}
/**
* Returns the current x position of the alien
*/
public int getYPos() {
return heightPosition;
}
/**
* Draw the image of the Alien
*/
public void drawAlien(Graphics g) {
if (!hitState) {
g.setColor(Color.red);
g.fillRect(leftPosition, heightPosition, ALIEN_WIDTH, ALIEN_HEIGHT);
}
}
}
}
}
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "}" to complete MethodBody
at Alien.main(Alien.java:3)
You seem to be mis-understanding the basics of Java syntax. Specifically, you cannot define your class's members and methods inside main() the way you are attempting to do:
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25; // you can't put this here
public static int ALIEN_WIDTH = 15; // you can't put this here
private int leftPosition = 0; // you can't put this here
private int heightPosition = 0; // you can't put this here
//etc
To get this to compile, you need to close main() and delete all the extra } you have at the end of your code:
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25;
public static int ALIEN_WIDTH = 15;
//etc
You'll also need to add some code to main() before your program actually does anything.
I would suggest that before you continue your current program you read some of the excellent tutorials online. A good place to start is The Java™ Tutorials on the oracle website.
Look at the Trails Covering the Basics section and work your way through Getting Started and Learning the Java Language before doing anything else.
Basically I made I class to extend the grid to 11 by 11, the constructor is being called however its not changing the grid. Any input or information on why would be greatly appreciated. I've posted my code below:
import info.gridworld.actor.*;
import info.gridworld.grid.BoundedGrid;
public class ChangeGrid extends ActorWorld{
private static final int SIZEROW = 11;
private static final int SIZECOL = 11;
public ChangeGrid()
{
super(new BoundedGrid<Actor>(SIZEROW, SIZECOL));
System.out.println("test");
}
}
import info.gridworld.actor.Bug;
public class XBug extends Bug {
/**
* A <code>BoxBug</code> traces out a square "box" of a given size. <br />
* The implementation of this class is testable on the AP CS A and AB exams.
*/
private int steps;
private int sideLength;
private int x = 0;
private static ChangeGrid object = new ChangeGrid();
/**
* Constructs a box bug that traces a square of a given side length
* #param length the side length
*/
public XBug(int length)
{
steps = 0;
sideLength = length;
}
/**
* Moves to the next location of the square.
*/
public void act()
{
if (steps < sideLength && canMove())
{
if(x==0)
{
turn();
}
move();
steps++;
x++;
}
else
{
turn();
steps = 0;
}
}
}
Your constructor is not being called when you create the world. You are calling it inside of an Actors class, then you don't even call the .show() method. You just need to change your runner class to call ChangeWorld instead of ActorWorld.
Here's an example for your code.
public class Runner
{
public static void main(String[]args)
{
ChangeWorld world = new ChangeWorld();
XBug bug = new XBug();
world.add(bug);
world.show();
}
}
I am trying to test my player class properly, I have almost done it but I am having issues with my p1.setPlayerHand method. This is the following code I have used for my player class:
Player Class:
package model;
public class Player
{
private String PlayerName;
private Hand PlayerHand;
private boolean Dealer;
public Player(String name)
{
PlayerName = name;
PlayerHand = new Hand();
Dealer = false;
}
public void setName (String name)
{
this.PlayerName = name;
}
public String getName()
{
return PlayerName;
}
public void setDealer (Boolean dealer)
{
this.Dealer = dealer;
}
public boolean getDealer()
{
return Dealer;
}
public void setPlayerHand (Hand hand)
{
this.PlayerHand = hand;
}
public void getHand()
{
PlayerHand.displayCardsinHand();
}
public static void main (String [] args)
{
Player p1 = new Player("player1");
Hand h = new Hand();
//System.out.println(p1);
p1.setName("BARRY");
System.out.println(p1.getName());
p1.setDealer(false);
System.out.println(p1.getDealer());
//this is the error that is preventing my program to run
p1.setPlayerHand(h.addCard(new Card(Suit.CLUBS, CardRank.ACE)));
p1.getHand();
}
}
The following error I receive (after testing the Player Class) is this:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method setPlayerHand(Hand) in the type Player is not applicable for the arguments (void)
at model.Player.main(Player.java:57)
This is the Hand Class underneath (that is linked to the Player Class):
Hand Class:
package model;
import java.util.Vector;
import java.util.Random;
public class Hand
{
private Vector<Card> hand;
public Hand()
{
hand = new Vector<Card>();
}
public void addCard(Card c)
{
hand.add(c);
}
public void displayCardsinHand()
{
for (int card = 0; card < hand.size(); card++)
{
System.out.println(hand.elementAt(card));
}
}
public int getCardsinHand()
{
return hand.size();
}
public Card getCard(int position)
{
if(position >= 0 && position < hand.size())
return (Card)hand.elementAt(position);
else
return null;
}
public int getScore()
{
int value = 0;
boolean ace = false;
for (int i = 0; i < hand.size(); i++)
{
Card c;
c = getCard(i);
value = value + c.getRankValue();
if(c.getRankValue() == 1)
{
ace = true;
}
}
if(ace == true && value + 10 <= 21)
{
value = value + 10;
}
return value;
}
public static void main (String [] args)
{
Hand h = new Hand();
System.out.println(h);
h.displayCardsinHand();
System.out.println(h.getCardsinHand());
h.addCard(new Card(Suit.HEARTS, CardRank.ACE));
System.out.println(h.getCardsinHand());
h.addCard(new Card(Suit.SPADES, CardRank.JACK));
System.out.println(h.getCardsinHand());
h.addCard(new Card(Suit.DIAMONDS, CardRank.QUEEN));
System.out.println(h.getCardsinHand());
h.addCard(new Card(Suit.CLUBS, CardRank.KING));
System.out.println(h.getCardsinHand());
System.out.println(h.getCardsinHand());
h.displayCardsinHand();
h.getCard(1);
System.out.println(h.getScore());
}
}
I have tried modifying the p1.setPlayerHand testing numerous times. I appreciate any advice and tips on how to solve this issue, thank you.
If my code is too long for this post then I will gladly accept any advice on what I should do to cut it short (for future reference).
If anyone here required to see any other classes that I wrote (that may help them help me solve this error) then please notify me on here, thank you.
The method addCard doesn't return anything (void). So you can't pass the result of this method to setPlayerHand(Hand). That's what you're doing.
The code should compile and run if you change
p1.setPlayerHand(h.addCard(new Card(Suit.CLUBS, CardRank.ACE)));
to
h.addCard(new Card(Suit.CLUBS, CardRank.ACE));
p1.setPlayerHand(h);
This is because the setPlayerHand method needs to be passed an object of type Hand, but the addCard method doesn't return anything (it's declared as void).