This site requires JavaScript, please enable it in your browser!
Greenfoot back
Ac951
Ac951 wrote ...

2020/3/22

Need help with my java code

1
2
3
Ac951 Ac951

2020/3/22

#
Hellooo!! im trying to make a game for greenfoot. Right now, the character shoots bomb at lobsters falling from the sky and they disappear and also is supposed to press space and make a "shelter" that can only be hit by 10 lobsters then disappear. ive gotten the shelter to appear but i cant seem to figuer out how to make the life decrease. Helppppppp!!! My World code. public class MyWorld extends World { int sheltersLeft = 3; /** * Constructor for objects of class MyWorld. */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(800, 600, 1); prepare(); act(); } private void prepare() { Player player = new Player(); addObject(player, 400, 575); ScoreBoard scoreboard = new ScoreBoard(); addObject(scoreboard,400, 10); addObject(new Lobstrosity(),400,Greenfoot.getRandomNumber(240)+40); } /** * getScoreBoard gives us the Scoreboard found in the world * NOTE ---> YOU ***MUST*** CODE THIS !!! * * @return the ScoreBoard object seen in the world */ public ScoreBoard getScoreBoard() { ScoreBoard scoreboard = new ScoreBoard(); return scoreboard; } public void act() { if (Greenfoot.isKeyDown("n") && getObjects(Lobstrosity.class).isEmpty()) { Player player = new Player(); addObject(player, 400, 575); ScoreBoard scoreboard = new ScoreBoard(); addObject(scoreboard,400, 10); Lobstrosity lobstrosity = new Lobstrosity(); addObject(lobstrosity,400,Greenfoot.getRandomNumber(240)+40); } } /** * containsShelter tells us whether or not a shelter * is already in the world. * @return true if there is a shelter, false if not */ //public boolean containsShelter() //{ //} /** * containsBomb tells us whether or not a bomb * is already in the world. * @return true if there is a bomb, false if not */ public boolean containsBomb() { // fairly inelegant and inefficient way to code this // but avoids the need for code elsewhere. return (!getObjects(PoisonBomb.class).isEmpty()); } /** * lobstrosityCount tells us how man lobstrosities are * in the World. * @return the number of lobstrosities in the world */ public int lobstrosityCount() { return getObjects(Lobstrosity.class).size(); } } Shelter code public class Shelter extends Actor { private int strengthLeft; // remaining strength private int initialStrength = 10; // dimensions of the shelter object. Note that these are // private as there is no reason to utiize these outside // of this class. private static final int SHELTER_WIDTH = 225; private static final int SHELTER_HEIGHT = 25; public void act() { /** * Constructor for a shelter. * * @param initialStrength is the starting strength of * this shelter */ if (isTouching(Lobstrosity.class)) { initialStrength--; } if (initialStrength==0) { getWorld().removeObject(this); } } public Shelter(int initialStrength) { strengthLeft = initialStrength; // remember initial strength redraw(); // redraw the shelter } // redraw simply rebuilds the image for the shelter. // note that methods outside this class should not call // redraw, so it is private. private void redraw() { // (re)build image if necessary GreenfootImage img = getImage(); if (img==null || img.getWidth()!=SHELTER_WIDTH || img.getHeight()!=SHELTER_HEIGHT) { img = new GreenfootImage(SHELTER_WIDTH, SHELTER_HEIGHT); setImage(img); } // set background to light gray img.setColor(Color.LIGHT_GRAY); img.fill(); // add text repressenting the strength left in black img.setColor(Color.BLACK); img.drawString(""+ strengthLeft, SHELTER_WIDTH/2-10, SHELTER_HEIGHT-8); } /** * reduceStrngth reduces this shelter's strength by 1 unit */ public void reduceStrength() { reduceStrength(1); // use the other reduceStrength method } /** * reduceStrength reduces the strength of the shelter by a * requested amount. * @param byVal is the amount to reduce this shelter's strength */ public void reduceStrength(int byVal) { strengthLeft-=byVal; // reduce the strength // if shelter is still strong enough to function ... if (strengthLeft>0) redraw(); // ... redisplay the shelter else // shelter not strong enough to function getWorld().removeObject(this); // remove this shelter } } Player Class import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Player extends Actor { private Shelter placeShelt= new Shelter(10); private int speedX; private int speedY; int Ammo = 10; int sheltersLeft = 3; int initialStrength=10; private ScoreBoard score = new ScoreBoard(); /** * Act - do whatever the Player wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { int deltaX=getX(); int deltaY=getY(); if (Greenfoot.isKeyDown("left") ) { deltaX-=1; } if (Greenfoot.isKeyDown("right") ) { deltaX+=1; } setLocation(deltaX, deltaY); if(isTouching(Lobstrosity.class) || getWorld().getObjects(Lobstrosity.class).isEmpty()) { getWorld().removeObjects(getWorld().getObjects(null)); } if ("space".equals(Greenfoot.getKey())&& getWorld().getObjects(Shelter.class).isEmpty()) //&& score.getShelterCount()>=0)) { placeShelt(); } /** * fire the PoisonBomb */ if ("b".equals(Greenfoot.getKey())) { if(Ammo>0) { PoisonBomb poisonbomb = new PoisonBomb(); getWorld().addObject(poisonbomb, getX(), getY()); Ammo--; } else { } } } public void placeShelt() { //Shelter shelter = new Shelter(); getWorld().addObject(placeShelt, getX(), getY()-50); } } Lobster class import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Lobstrosity extends Actor { private int touching; private int count=1; /** * Act - do whatever the Lostrosity wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { setRotation(90); move(1); //if (isTouching(Shelter.class)) //{ //removeTouching(Lobstrosity.class); // getWorld().removeObject(this); //} if (isAtEdge()) { getWorld().addObject(new Lobstrosity(),Greenfoot.getRandomNumber(800)+1, Greenfoot.getRandomNumber(240)+40); setLocation(Greenfoot.getRandomNumber(800)+1, Greenfoot.getRandomNumber(240)+40); getWorld().addObject(new Lobstrosity(),Greenfoot.getRandomNumber(800)+1, Greenfoot.getRandomNumber(240)+40); setLocation(Greenfoot.getRandomNumber(800)+1, Greenfoot.getRandomNumber(240)+40); } if (isTouching(Shelter.class)==true) { getWorld().removeObject(this); //placeShelt.reduceStrength(-1); } } }
danpost danpost

2020/3/22

#
The Shelter class act method should: (1) deal with strengthLeft, not initialStrength; (2) call reduceHealth, not decrease it directly; and (3) should not need the final check to remove the actor. Actually, (2) removes the variable referred to in (1), making (1) a moot point.
Ac951 Ac951

2020/3/22

#
public class Shelter extends Actor { private int strengthLeft; // remaining strength private int strength = 10; // dimensions of the shelter object. Note that these are // private as there is no reason to utiize these outside // of this class. private static final int SHELTER_WIDTH = 225; private static final int SHELTER_HEIGHT = 25; public void act() { /** * Constructor for a shelter. * * @param initialStrength is the starting strength of * this shelter */ } public Shelter(int initialStrength) { strengthLeft = initialStrength; // remember initial strength redraw(); // redraw the shelter } // redraw simply rebuilds the image for the shelter. // note that methods outside this class should not call // redraw, so it is private. private void redraw() { // (re)build image if necessary GreenfootImage img = getImage(); if (img==null || img.getWidth()!=SHELTER_WIDTH || img.getHeight()!=SHELTER_HEIGHT) { img = new GreenfootImage(SHELTER_WIDTH, SHELTER_HEIGHT); setImage(img); } // set background to light gray img.setColor(Color.LIGHT_GRAY); img.fill(); // add text repressenting the strength left in black img.setColor(Color.BLACK); img.drawString(""+ strengthLeft, SHELTER_WIDTH/2-10, SHELTER_HEIGHT-8); } /** * reduceStrngth reduces this shelter's strength by 1 unit */ public void reduceStrength() { reduceStrength(1); // use the other reduceStrength method } /** * reduceStrength reduces the strength of the shelter by a * requested amount. * @param byVal is the amount to reduce this shelter's strength */ public void reduceStrength(int byVal) { strengthLeft-=byVal; // reduce the strength // if shelter is still strong enough to function ... if (strengthLeft>0) redraw(); // ... redisplay the shelter else // shelter not strong enough to function getWorld().removeObject(this); // remove this shelter } } i changed some of it but i need to figure out how to get it in my player class correctly i dont think i did that correctly
danpost danpost

2020/3/22

#
The following might work better for placing the shelter:
1
if (Greenfoot.isKeyDown("space") && placeShelt.getWorld() == null && placeShelt.hasHealth()) placeShelt();
with the following method added to the Shelter class:
1
2
3
4
public boolean hasHealth()
{
    return strengthLeft > 0;
}
( I am not sure what score.getShelterCount() actually does )
Ac951 Ac951

2020/3/22

#
ok i added both of those but my player doesnt seem to move now public class Player extends Actor { private Shelter placeShelt= new Shelter(10); private int speedX; private int speedY; int Ammo = 10; int sheltersLeft = 3; int initialStrength=10; private ScoreBoard score = new ScoreBoard(); /** * Act - do whatever the Player wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if (Greenfoot.isKeyDown("left") ) { move(-1); } if (Greenfoot.isKeyDown("right") ) { move(1); } this.setLocation(getX(), getY()); if(isTouching(Lobstrosity.class) || getWorld().getObjects(Lobstrosity.class).isEmpty()) { getWorld().removeObjects(getWorld().getObjects(null)); } if (Greenfoot.isKeyDown("space") && placeShelt.getWorld() == null && placeShelt.hasHealth()) { placeShelt(); } /** * fire the PoisonBomb */ if ("b".equals(Greenfoot.getKey())) { if(Ammo>0) { PoisonBomb poisonbomb = new PoisonBomb(); getWorld().addObject(poisonbomb, getX(), getY()); Ammo--; } else { } } } public void placeShelt() { getWorld().addObject(placeShelt, getX(), getY()-50); } }
danpost danpost

2020/3/22

#
I do not see why your player would not move. As coded, the left and right arrow keys, individually, should make the player move. However, the last line in your movement code -- this:
1
this.setLocation(getX(), getY());
does absolutely nothing. It just sets the location of the player to where it is already at (no positional change at all). You can, with confidence, remove that line.
Ac951 Ac951

2020/3/22

#
Ok i fixed the movement of my player but i cant seem to get the shelter to disappear after 10 hits still
Ac951 Ac951

2020/3/22

#
public class ScoreBoard extends Actor { private int gameScore; // current game score private int highScore; // high score so far private int sheltersLeft; // number of shelters left private int bombsLeft; // number of bombs left // "global" representing the height (bottom to top) of a // ScoreBoard public static final int SCOREBOARD_HEIGHT = 25; /** * Constructor for ScoreBoard to build starting scoreboard. */ public ScoreBoard() { gameScore=0; // no game started yet, so score is 0 highScore=0; // no game started yet, so high score is 0 bombsLeft=10; // no game started yet, so all bombs available sheltersLeft=3; // no game started yet, so all shelters available } // Greenfoot trick to draw image ater object added to world. protected void addedToWorld(World toWorld) { redraw(); } // redraws scoreboard, updating values displayed as we go // we don't want this called from outside the class, so // it is private in this case. private void redraw() { // needs regular access to world, so store in a variable. MyWorld placedIn = (MyWorld) getWorld(); // check to see if image is valid. If not, rebuild it. GreenfootImage img = getImage(); if (img==null || img.getWidth()!= placedIn.getWidth() || img.getHeight()!=SCOREBOARD_HEIGHT) { img = new GreenfootImage(placedIn.getWidth(), SCOREBOARD_HEIGHT); setImage(img); } // fill image with gray background img.setColor(Color.LIGHT_GRAY); img.fill(); // draw scores, etc. in black img.setColor(Color.BLACK); img.drawString("Score:"+ gameScore, 600, SCOREBOARD_HEIGHT-8); img.drawString("High Score:"+ highScore, 400, SCOREBOARD_HEIGHT-8); // draw in shelter and bomb stats img.drawString("Shelters:"+ sheltersLeft, 100, SCOREBOARD_HEIGHT-8); img.drawString("Bombs:"+ bombsLeft, 300, SCOREBOARD_HEIGHT-8); } /** * incScore - adds something to score * @param byVal - value to add to the score. */ public void incScore(int byVal) { gameScore+=byVal; redraw(); } /** * getScore - returns the current score * @return the current game score */ public int getScore() { return gameScore; } /** * decBombCount - decrease the number of bombs by 1, but only * if there are any bombs left * @return true when there was at least 1 bomb left, * false otherwise */ public boolean decBombCount() { // if there are bombs left if (bombsLeft>0) { bombsLeft--; // reduce bomb count redraw(); // redraw image to see updated bomb count return true; // we succeeded! } return false; // not enough bombs to do this! } /** * decShelterCount - decrease the number of shelters by 1, but * only if there are any shelters left * @return true when there was at least 1 shelter left, * false otherwise */ public boolean decShelterCount() { // if there are shelters left if (sheltersLeft>0) { sheltersLeft--; // now there's one less shelter redraw(); // redraw to reflect change return true; // we had a shelter left! } return false; // no shlters left! } /** * getShelterCount returns how mny shelters are available * * @return the current number of shelters */ public int getShelterCount() { return sheltersLeft; } /** * getHighScore returns the current value of high score * * @return the current high score */ public int getHighScore() { return highScore; } /** * setHighScore gives high score a new value * * @param newScore the intended new value of high score */ public void setHighScore(int newScore) { highScore = newScore; // store the new high score redraw(); // redisplay scoreboard } /** * resetForNewGame resets the scoreboard data for a new game * * note that this does NOT reset high score */ public void resetForNewGame() { // games start with 3 shelters, 10 bombs, and a score of 0 sheltersLeft=3; bombsLeft=10; gameScore=0; redraw(); // redisplay the scoreboard. } } also here is my scoreboard class that i am having issues with as well. when the lobster hits the bottom of the screen the score is supposed to go up by one. Also, theres a limit if 3 shelters per game and 10 bombs per game as well.
danpost danpost

2020/3/22

#
Ac951 wrote...
Ok i fixed the movement of my player but i cant seem to get the shelter to disappear after 10 hits still
Last line in Lobstrosity class (the one commented out) can be:
1
((Shelter)getOneIntersectingObject(Shelter.class)).reduceStrength();
However, it needs to be switched with the line before it -- otherwise, they would no longer be touching.
Ac951 Ac951

2020/3/22

#
wow!!! thank you that worked!!! Could you help me with the scoreboard by chance??
danpost danpost

2020/3/22

#
Ac951 wrote...
wow!!! thank you that worked!!! Could you help me with the scoreboard by chance??
In general, you should not have fields in multiple classes representing the same value. However, if you do, then you must ensure that when you change one you change the other.
Ac951 Ac951

2020/3/22

#
((MyWorld) getWorld().getScoreBoard().addScore(1)); would it. be something like this??? i added that into the isAtEdge code in the lobster class
danpost danpost

2020/3/22

#
Ac951 wrote...
((MyWorld) getWorld().getScoreBoard().addScore(1)); would it. be something like this??? i added that into the isAtEdge code in the lobster class
Not quite. Only that which is returned by getWorld is of type MyWorld:, so
1
((MyWorld)getWorld()).getScoreBoard().addScore(1);
and the method in your MyWorld class should be just:
1
2
3
4
public ScoreBoard getScoreBoard()
{
    return scoreboard;
}
Also, the third line in the prepare method -- this one:
1
ScoreBoard scoreboard = new ScoreBoard();
needs to be moved to outside the method.
Ac951 Ac951

2020/3/22

#
i get an error with the first one saying the method getScore in class ScoreBoard cannot be applied to given types
danpost danpost

2020/3/22

#
Ac951 wrote...
i get an error with the first one saying the method getScore in class ScoreBoard cannot be applied to given types
Where are you referring to? I never used getScore.
There are more replies on the next page.
1
2
3