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

2016/12/17

IndexOutOfBound error

1
2
3
rkr rkr

2016/12/17

#
Im getting a indexoutofbound error when i return damage to my enemy if the enemy is within the radius of bomb and i dont know y it is giving me this error: Hero Code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Hero here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Hero extends Actor
{
    GreenfootSound shootSFX = new GreenfootSound("Tear.mp3");
    GreenfootSound backgroundMusic = new GreenfootSound("dipterasonata.mp3");  
    int moveRight = 5, moveLeft = 5, moveUp = 5, moveDown = 5;
    int numKey = 0;
    double health;
    private int wait = 100;
    private final int waitTime = 100;
    public boolean placeBomb = false;
    String v = "null";
    boolean movingRight = false, movingLeft = false, movingUp = false, movingDown = false;
    double shootSpeed = 600; //can shoot every 600 miliseconds
    int damage = -1;
    GreenfootImage image1 = new GreenfootImage("hero1.png");
    GreenfootImage image2 = new GreenfootImage("hero2.png");
    GreenfootImage image3 = new GreenfootImage("hero3.png");
    GreenfootImage image4 = new GreenfootImage("hero4.png");
    GreenfootImage image5 = new GreenfootImage("hero5.png");
    GreenfootImage image6 = new GreenfootImage("hero6.png");
    GreenfootImage image7 = new GreenfootImage("hero7.png");
    GreenfootImage image8 = new GreenfootImage("hero8.png");
    GreenfootImage image9 = new GreenfootImage("hero9.png");
    private SimpleTimer timer = new SimpleTimer();

    /**
     * Act - do whatever the Hero wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() {
        removeDoor();
        headOnCollision();
        sideCollision();
        movement();
        pickDmgUp();
        shoot();
        pickKey();
        checkDeath();
        //backgroundMusic.playLoop();
        backgroundMusic.setVolume(50);
        bomb();
        checkBombStatus();
    }

    //basic movement
    public void movement() {
        //had to make these exceptions since otherwise the hero would get stuck at the walls.
        //basically if it comes into contact with a wall from a specific direction (let's say to the right), the movement to the right is set to 0
        //but you can still move left
        if (moveRight == 0) {
            moveLeft = 5;
        } else if (moveLeft == 0) {
            moveRight = 5;
        } else {
            moveLeft = moveRight;
        }

        //same here but vertically
        if (moveDown == 0) {
            moveUp = 5;
        } else if (moveUp == 0) {
            moveDown = 5;
        } else {
            moveDown = moveUp;
        }

        //basic movement
        if (Greenfoot.isKeyDown("w")) {
            setLocation(getX(), getY() - moveUp);
            animateUp();
            movingUp = true;
            movingDown = false;
            movingLeft = false;
            movingRight = false;
        } else if (Greenfoot.isKeyDown("s")) {
            setLocation(getX(), getY() + moveDown);
            animateDown();
            movingUp = false;
            movingDown = true;
            movingLeft = false;
            movingRight = false;
        } else if (Greenfoot.isKeyDown("d")) {
            setLocation(getX() + moveRight, getY());
            movingRight = true;
            movingLeft = false; 
            movingUp = false;
            movingDown = false;
            animateRight();
        } else if (Greenfoot.isKeyDown("a")) {
            setLocation(getX() - moveLeft, getY());
            movingLeft = true;
            movingRight = false;
            movingUp = false;
            movingDown = false;
            animateLeft();
        } else {
            setImage(image1);
            movingLeft = false;
            movingRight = false;
            movingUp = false;
            movingDown = false;
        }
    }

    public boolean movingDirection(int i) {
        if (i == 1) {
            return movingRight;
        } else if (i == 2){
            return movingLeft;
        } else if (i == 3) {
            return movingUp;
        } else if (i == 4) {
            return movingDown;
        } else {
            return false;
        }
    }

    //checks if the hero is colliding with specific parts of the wall and sets the speed of the hero accordingly (speed at 0 if colliding)
    public void sideCollision() {
        Obstacle wCheck = (Obstacle)getOneObjectAtOffset(getImage().getWidth()/2, 0, Obstacle.class);
        Obstacle wCheck2 = (Obstacle)getOneObjectAtOffset(getImage().getWidth()/2, -getImage().getHeight()/2, Obstacle.class);
        Obstacle wCheck3 = (Obstacle)getOneObjectAtOffset(getImage().getWidth()/2, getImage().getHeight()/4, Obstacle.class);
        Obstacle wCheck4 = (Obstacle)getOneObjectAtOffset(getImage().getWidth()/2, -getImage().getHeight()/4, Obstacle.class);

        Obstacle wCheck5 = (Obstacle)getOneObjectAtOffset(-getImage().getWidth()/2, 0, Obstacle.class);
        Obstacle wCheck6 = (Obstacle)getOneObjectAtOffset(-getImage().getWidth()/2, -getImage().getHeight()/2, Obstacle.class);
        Obstacle wCheck7 = (Obstacle)getOneObjectAtOffset(-getImage().getWidth()/2, getImage().getHeight()/4, Obstacle.class);
        Obstacle wCheck8 = (Obstacle)getOneObjectAtOffset(-getImage().getWidth()/2, -getImage().getHeight()/4, Obstacle.class);

        if (wCheck != null || wCheck2 != null || wCheck3 != null || wCheck4 != null) {
            moveRight = 0;
        } else {
            moveRight = 5;
        }

        if (wCheck5 != null || wCheck6 != null || wCheck7 != null || wCheck8 != null) {
            moveLeft = 0;
        } else {
            moveLeft = 5;
        }

    }

    //for use in bullet curve
    public int moveRightValue() {
        return moveRight;
    }
    //same here but with top down collisions
    public void headOnCollision() {
        Obstacle wCheck3 = (Obstacle)getOneObjectAtOffset(0, getImage().getHeight()/2, Obstacle.class);
        Obstacle wCheck4 = (Obstacle)getOneObjectAtOffset(0, -getImage().getHeight()/2, Obstacle.class);
        if (wCheck3 != null) {
            moveDown = 0;
        } else {
            moveDown = 5;
        }

        if (wCheck4 != null) {
            moveUp = 0;
        } else {
            moveUp = 5;
        }
    }

    public boolean check() {
        Actor d = getOneIntersectingObject(EnemyBullet.class);
        if (d!=null) {
            return true;
        }
        return false;
    }

    //various animations. Checks which key is pressed and what picture should be switched to
    private void animateDown() {
        if (getImage() == image2) {
            setImage(image3);
        } else {
            setImage(image2);
        }
    }

    private void animateLeft() {
        if (getImage() == image4) {
            setImage(image5);
        } else {
            setImage(image4);
        }
    }

    private void animateRight() {
        if (getImage() == image6) {
            setImage(image7);
        } else {
            setImage(image6);
        }
    }

    private void animateUp() {
        if (getImage() == image8) {
            setImage(image9);
        } else {
            setImage(image8);
        }
    }

    private void checkBombStatus(){
        if (wait > 1){
            wait --;
        }
        if(wait == 1){
            placeBomb = true;  
        }
        if (wait == 0){
            placeBomb = false;
        }
    }
    // // takes the counter and decreases one every time the user uses the bomb
    public void bomb(){
        Bomb b = new Bomb();
        if(Greenfoot.isKeyDown("space") && !placeBomb){
            getWorld().addObject(b,getX(), getY());
             wait += waitTime;
        }
    }

    public boolean placeBomb() {
        return placeBomb;
    }

    //Directional shooting with arrow keys spawns an instance of 'hero bullet' and rotates it according to which arrow key is pressed. Actual shooting happens in that class
    public void shoot() {
        HeroBullet h = new HeroBullet();

        if (timer.millisElapsed() > shootSpeed){
            if(Greenfoot.isKeyDown("right")){
                shootSFX.play();
                v = "right";
                getWorld().addObject(h, getX(), getY());
                timer.mark();
            }
            else if (Greenfoot.isKeyDown("left")){
                shootSFX.play();
                v = "left";
                getWorld().addObject(h, getX(), getY());
                h.setRotation(180);
                timer.mark();
            }
            else if(Greenfoot.isKeyDown("up")){
                shootSFX.play();
                v = "up";
                getWorld().addObject(h, getX(), getY());
                h.setRotation(270);
                timer.mark();
            }
            else if(Greenfoot.isKeyDown("down")){
                shootSFX.play();
                v = "down";
                getWorld().addObject(h, getX(), getY());
                h.setRotation(90);
                timer.mark();
            }
        }
    }

    public String returnV() {
        return v;
    }

    // if hero touches enemy's bullets. Health will be lost
    public boolean checkDeath() {
        Actor d = getOneIntersectingObject(Enemy.class);
        Actor f = getOneIntersectingObject(EnemyBullet.class);
        if (d!=null || f!=null ) {
            return true;
            //Greenfoot.stop();
        }
        else return false;
    }   

    // checks if hero comes in contact with the healthPowerUp
    public boolean checkHealthPowerUp(){
        Actor d = getOneIntersectingObject(HealthPowerUp.class);
        if(d!=null){
            return true;
        }
        else {
            return false;
        }
    }   

    //picks up key if in contact
    public void pickKey() {
        Actor d = getOneIntersectingObject(Key.class);
        if (d != null) {         
            numKey++;
        }
    }

    //sees if the actor is colliding with the door and if he has the required amount of keys, and returns true if both are true
    public boolean removeDoor(){
        Actor g = getOneIntersectingObject(LockedDoor.class);
        if (g != null && numKey > 0) { 
            return true;
        }
        return false;
    }

    //sets the the damage to -5 if hero picks up the powerup
    public void pickDmgUp(){
        Actor d = getOneIntersectingObject(DamageUp.class);
        if (d != null) {         
            damage = -5;
        }
    }

    //returns damage, used in enemies when substracting their health
    public int getDamage(){
        return damage;
    }

    //necessary to make removeDoor() work, forgive me
    public void reduceKey() {
        numKey--;
    }
}
Enemy Code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Grunt here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Grunt extends Enemy
{
    private int health = 1;
    GreenfootSound shootSFX = new GreenfootSound("enemyshoot.mp3");
    /**
     * Act - do whatever the Grunt wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act(){
        moveRandomly();
        randomShoot();
        checkDeath();
    }    

    //moves the grunt randomly
    //http://www.greenfoot.org/topics/3205/15
    public void moveRandomly(){
        //countinously moving in the direction its facing at speed 5
        move(5); 
        //greenfoot continously pulls a random number. If the random number is less than 10 turns the grunt a random angle between 45 and -45 
        if (Greenfoot.getRandomNumber(100) < 10){ 
            turn(Greenfoot.getRandomNumber(90 + 1) - 45);
        }       

        //if colliding with any obstacle, turns a complete 180 degrees
        if (isColliding()){ 
            turn(180);
        }
    }

    //checks if the grunt is colliding with any object of class Obstacle and returns true if it is.
    public boolean isColliding() {
        Actor w = getOneIntersectingObject(Obstacle.class);
        return w != null;
    }

    //shoots a bullet randomly
    public void randomShoot() {
        EnemyBullet e = new EnemyBullet();
        //greennfoot picks a random number between 0 and 499 each act. If this number is less than 5, then a bullet is spawned. 
        //Actual shooting happens in bullet class
        if (Greenfoot.getRandomNumber(500) < 10){
            shootSFX.play();
            getWorld().addObject(e, getX(), getY());
        }   
    }

    public void checkDeath() {
        Actor d = getOneIntersectingObject(HeroBullet.class);
        Hero h = ((Hero) getWorld().getObjects(Hero.class).get(0));
        if (h.placeBomb() == true){
            int healthLostBomb = getWorld().getObjects(Bomb.class).get(0).damage(); // ERROR COMES HERE
            healthBomb(healthLostBomb);
            if (getHealth() <= 0) {
                getWorld().removeObject(this);
            }
        }
        if (d!=null) {
            int healthLost = getWorld().getObjects(Hero.class).get(0).getDamage(); 
            health(healthLost);
            getWorld().removeObject(getOneIntersectingObject(HeroBullet.class));
            if (getHealth() <=0) {
                getWorld().removeObject(this);
            }
        }

    }

    public void health(int healthLostBullet ){
        health = health + healthLostBullet;
    }

    public void healthBomb(int healthLostBomb){
        health = health + healthLostBomb;
    }

    public int getHealth(){
        return health;
    }
}
BombCode:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
 * Write a description of class Bomb here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Bomb extends Bullet
{
    int timer = 100;
    public int damage = -5;
    public void act() 
    {
        timer--;
        if (timer == 0){
            //explode();
            getWorld().removeObject(this);
        }
    }
    // removes object within the radius of the bomb
    // public void explode (){
    // getWorld().removeObjects(getObjectsInRange(200, SmartGrunt.class));
    // getWorld().removeObjects(getObjectsInRange(200, Grunt.class));
    // }

    public int damage(){
        List<Grunt> o = getObjectsInRange(200,Grunt.class);
        Hero h = ((Hero) getWorld().getObjects(Hero.class).get(0));
        if(h.placeBomb() == true && o.size()>0){
            return damage;
        }
        else if  (h.placeBomb() == true && o.size()<=0){
            return damage;
        }
        else return damage;
    }
}

danpost danpost

2016/12/17

#
There is much that can be done to improve your coding (making it less bulky and more to the point). The excessive use of field and variables is complicating things as well as how you are going about certain thing. For example, the way you use the 'wait' field in placing the bomb (which, by the way, is partly the cause of the current issue mentioned). Insead of starting its value at 100, start it at zero. If it is zero, you are not waiting. If it is not zero, then decrease it and check to see if it becomes zero. If it just changed to zero, place the bomb. The code would simply be as follows:
// instance field
private int wait; // default ' = 0'

// in code
if (wait > 0) // if waiting
{
    if (--wait == 0) // if decreasing becomes zero
        getWorld().addObject(new Bomb(), getX(), getY()); // add bomb
}
else if (Greenfoot.isKeyDown("space")) wait = waitTime; // start waiting
You do not need the 'placeBomb' field at all. Just see if any are in the world with:
boolean bombExists = ! getWorld().getObjects(Bomb.class).isEmpty();
The enemy needs to check this before 'get(0)' on the error line. The damage method of the Bomb class in every case will return damage and nothing more. It can simply be:
public int damage()
{
    return damage;
}
I doubt you need all the fields on lines 13 and 20 of the Hero class. Instead of checking what might be around the hero beforehand, just move the hero as directed by the user and then check what is at that location; if something like a wall, block or border is there, reverse the move. If you really need to check beforehand, you only really need to check in the direction the user is trying to take the hero.
rkr rkr

2016/12/17

#
What if i want to return damage when the enemy is range and when it is not it returns 0 (0 damage)
rkr rkr

2016/12/17

#
I meant to change the last 2 return damage in the bomb code to zero
rkr rkr

2016/12/17

#
I changed my code: Hero Code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Hero here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Hero extends Actor
{
    GreenfootSound shootSFX = new GreenfootSound("Tear.mp3");
    GreenfootSound backgroundMusic = new GreenfootSound("dipterasonata.mp3");  
    int moveRight = 5, moveLeft = 5, moveUp = 5, moveDown = 5;
    int numKey = 0;
    double health;
    private int wait = 0;
    private final int waitTime = 100;
    public boolean placeBomb = false;
    String v = "null";
    boolean movingRight = false, movingLeft = false, movingUp = false, movingDown = false;
    double shootSpeed = 600; //can shoot every 600 miliseconds
    int damage = -1;
    GreenfootImage image1 = new GreenfootImage("hero1.png");
    GreenfootImage image2 = new GreenfootImage("hero2.png");
    GreenfootImage image3 = new GreenfootImage("hero3.png");
    GreenfootImage image4 = new GreenfootImage("hero4.png");
    GreenfootImage image5 = new GreenfootImage("hero5.png");
    GreenfootImage image6 = new GreenfootImage("hero6.png");
    GreenfootImage image7 = new GreenfootImage("hero7.png");
    GreenfootImage image8 = new GreenfootImage("hero8.png");
    GreenfootImage image9 = new GreenfootImage("hero9.png");
    private SimpleTimer timer = new SimpleTimer();

    /**
     * Act - do whatever the Hero wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() {
        removeDoor();
        headOnCollision();
        sideCollision();
        movement();
        pickDmgUp();
        shoot();
        pickKey();
        checkDeath();
        //backgroundMusic.playLoop();
        backgroundMusic.setVolume(50);
        bomb();
        // checkBombStatus();
    }

    //basic movement
    public void movement() {
        //had to make these exceptions since otherwise the hero would get stuck at the walls.
        //basically if it comes into contact with a wall from a specific direction (let's say to the right), the movement to the right is set to 0
        //but you can still move left
        if (moveRight == 0) {
            moveLeft = 5;
        } else if (moveLeft == 0) {
            moveRight = 5;
        } else {
            moveLeft = moveRight;
        }

        //same here but vertically
        if (moveDown == 0) {
            moveUp = 5;
        } else if (moveUp == 0) {
            moveDown = 5;
        } else {
            moveDown = moveUp;
        }

        //basic movement
        if (Greenfoot.isKeyDown("w")) {
            setLocation(getX(), getY() - moveUp);
            animateUp();
            movingUp = true;
            movingDown = false;
            movingLeft = false;
            movingRight = false;
        } else if (Greenfoot.isKeyDown("s")) {
            setLocation(getX(), getY() + moveDown);
            animateDown();
            movingUp = false;
            movingDown = true;
            movingLeft = false;
            movingRight = false;
        } else if (Greenfoot.isKeyDown("d")) {
            setLocation(getX() + moveRight, getY());
            movingRight = true;
            movingLeft = false; 
            movingUp = false;
            movingDown = false;
            animateRight();
        } else if (Greenfoot.isKeyDown("a")) {
            setLocation(getX() - moveLeft, getY());
            movingLeft = true;
            movingRight = false;
            movingUp = false;
            movingDown = false;
            animateLeft();
        } else {
            setImage(image1);
            movingLeft = false;
            movingRight = false;
            movingUp = false;
            movingDown = false;
        }
    }

    public boolean movingDirection(int i) {
        if (i == 1) {
            return movingRight;
        } else if (i == 2){
            return movingLeft;
        } else if (i == 3) {
            return movingUp;
        } else if (i == 4) {
            return movingDown;
        } else {
            return false;
        }
    }

    //checks if the hero is colliding with specific parts of the wall and sets the speed of the hero accordingly (speed at 0 if colliding)
    public void sideCollision() {
        Obstacle wCheck = (Obstacle)getOneObjectAtOffset(getImage().getWidth()/2, 0, Obstacle.class);
        Obstacle wCheck2 = (Obstacle)getOneObjectAtOffset(getImage().getWidth()/2, -getImage().getHeight()/2, Obstacle.class);
        Obstacle wCheck3 = (Obstacle)getOneObjectAtOffset(getImage().getWidth()/2, getImage().getHeight()/4, Obstacle.class);
        Obstacle wCheck4 = (Obstacle)getOneObjectAtOffset(getImage().getWidth()/2, -getImage().getHeight()/4, Obstacle.class);

        Obstacle wCheck5 = (Obstacle)getOneObjectAtOffset(-getImage().getWidth()/2, 0, Obstacle.class);
        Obstacle wCheck6 = (Obstacle)getOneObjectAtOffset(-getImage().getWidth()/2, -getImage().getHeight()/2, Obstacle.class);
        Obstacle wCheck7 = (Obstacle)getOneObjectAtOffset(-getImage().getWidth()/2, getImage().getHeight()/4, Obstacle.class);
        Obstacle wCheck8 = (Obstacle)getOneObjectAtOffset(-getImage().getWidth()/2, -getImage().getHeight()/4, Obstacle.class);

        if (wCheck != null || wCheck2 != null || wCheck3 != null || wCheck4 != null) {
            moveRight = 0;
        } else {
            moveRight = 5;
        }

        if (wCheck5 != null || wCheck6 != null || wCheck7 != null || wCheck8 != null) {
            moveLeft = 0;
        } else {
            moveLeft = 5;
        }

    }

    //for use in bullet curve
    public int moveRightValue() {
        return moveRight;
    }
    //same here but with top down collisions
    public void headOnCollision() {
        Obstacle wCheck3 = (Obstacle)getOneObjectAtOffset(0, getImage().getHeight()/2, Obstacle.class);
        Obstacle wCheck4 = (Obstacle)getOneObjectAtOffset(0, -getImage().getHeight()/2, Obstacle.class);
        if (wCheck3 != null) {
            moveDown = 0;
        } else {
            moveDown = 5;
        }

        if (wCheck4 != null) {
            moveUp = 0;
        } else {
            moveUp = 5;
        }
    }

    public boolean check() {
        Actor d = getOneIntersectingObject(EnemyBullet.class);
        if (d!=null) {
            return true;
        }
        return false;
    }

    //various animations. Checks which key is pressed and what picture should be switched to
    private void animateDown() {
        if (getImage() == image2) {
            setImage(image3);
        } else {
            setImage(image2);
        }
    }

    private void animateLeft() {
        if (getImage() == image4) {
            setImage(image5);
        } else {
            setImage(image4);
        }
    }

    private void animateRight() {
        if (getImage() == image6) {
            setImage(image7);
        } else {
            setImage(image6);
        }
    }

    private void animateUp() {
        if (getImage() == image8) {
            setImage(image9);
        } else {
            setImage(image8);
        }
    }

    // private void checkBombStatus(){
    // if (wait > 1){
    // wait --;
    // }
    // if(wait == 1){
    // placeBomb = true;  
    // }
    // if (wait == 0){
    // placeBomb = false;
    // }
    // }
    // // takes the counter and decreases one every time the user uses the bomb
    public void bomb(){
        if (wait>0){
            if (--wait == 0){
                getWorld().addObject(new Bomb(),getX(), getY());
            }
        }
        else if(Greenfoot.isKeyDown("space")){
            wait = waitTime;
        }
    }

    //Directional shooting with arrow keys spawns an instance of 'hero bullet' and rotates it according to which arrow key is pressed. Actual shooting happens in that class
    public void shoot() {
        HeroBullet h = new HeroBullet();

        if (timer.millisElapsed() > shootSpeed){
            if(Greenfoot.isKeyDown("right")){
                shootSFX.play();
                v = "right";
                getWorld().addObject(h, getX(), getY());
                timer.mark();
            }
            else if (Greenfoot.isKeyDown("left")){
                shootSFX.play();
                v = "left";
                getWorld().addObject(h, getX(), getY());
                h.setRotation(180);
                timer.mark();
            }
            else if(Greenfoot.isKeyDown("up")){
                shootSFX.play();
                v = "up";
                getWorld().addObject(h, getX(), getY());
                h.setRotation(270);
                timer.mark();
            }
            else if(Greenfoot.isKeyDown("down")){
                shootSFX.play();
                v = "down";
                getWorld().addObject(h, getX(), getY());
                h.setRotation(90);
                timer.mark();
            }
        }
    }

    public String returnV() {
        return v;
    }

    // if hero touches enemy's bullets. Health will be lost
    public boolean checkDeath() {
        Actor d = getOneIntersectingObject(Enemy.class);
        Actor f = getOneIntersectingObject(EnemyBullet.class);
        if (d!=null || f!=null ) {
            return true;
            //Greenfoot.stop();
        }
        else return false;
    }   

    // checks if hero comes in contact with the healthPowerUp
    public boolean checkHealthPowerUp(){
        Actor d = getOneIntersectingObject(HealthPowerUp.class);
        if(d!=null){
            return true;
        }
        else {
            return false;
        }
    }   

    //picks up key if in contact
    public void pickKey() {
        Actor d = getOneIntersectingObject(Key.class);
        if (d != null) {         
            numKey++;
        }
    }

    //sees if the actor is colliding with the door and if he has the required amount of keys, and returns true if both are true
    public boolean removeDoor(){
        Actor g = getOneIntersectingObject(LockedDoor.class);
        if (g != null && numKey > 0) { 
            return true;
        }
        return false;
    }

    //sets the the damage to -5 if hero picks up the powerup
    public void pickDmgUp(){
        Actor d = getOneIntersectingObject(DamageUp.class);
        if (d != null) {         
            damage = -5;
        }
    }

    //returns damage, used in enemies when substracting their health
    public int getDamage(){
        return damage;
    }

    //necessary to make removeDoor() work, forgive me
    public void reduceKey() {
        numKey--;
    }
}
Enemy Code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Grunt here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Grunt extends Enemy
{
    private int health = 1;
    GreenfootSound shootSFX = new GreenfootSound("enemyshoot.mp3");
    /**
     * Act - do whatever the Grunt wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act(){
        moveRandomly();
        randomShoot();
        checkDeath();
    }    

    //moves the grunt randomly
    //http://www.greenfoot.org/topics/3205/15
    public void moveRandomly(){
        //countinously moving in the direction its facing at speed 5
        move(5); 
        //greenfoot continously pulls a random number. If the random number is less than 10 turns the grunt a random angle between 45 and -45 
        if (Greenfoot.getRandomNumber(100) < 10){ 
            turn(Greenfoot.getRandomNumber(90 + 1) - 45);
        }       

        //if colliding with any obstacle, turns a complete 180 degrees
        if (isColliding()){ 
            turn(180);
        }
    }

    //checks if the grunt is colliding with any object of class Obstacle and returns true if it is.
    public boolean isColliding() {
        Actor w = getOneIntersectingObject(Obstacle.class);
        return w != null;
    }

    //shoots a bullet randomly
    public void randomShoot() {
        EnemyBullet e = new EnemyBullet();
        //greennfoot picks a random number between 0 and 499 each act. If this number is less than 5, then a bullet is spawned. 
        //Actual shooting happens in bullet class
        if (Greenfoot.getRandomNumber(500) < 10){
            shootSFX.play();
            getWorld().addObject(e, getX(), getY());
        }   
    }

    public void checkDeath() {
        Actor d = getOneIntersectingObject(HeroBullet.class);
        Hero h = ((Hero) getWorld().getObjects(Hero.class).get(0));
        boolean bombExist = !getWorld().getObjects(Bomb.class).isEmpty();
        if (bombExist == true){
            int healthLostBomb = getWorld().getObjects(Bomb.class).get(0).damage(); // STILL GIVING ME ERROR HERE INDEXOUTOFBOUNDSEXCEPTION INDEX = 0 SIZE = 0
            healthBomb(healthLostBomb);
            if (getHealth() <= 0) {
                getWorld().removeObject(this);
            }
        }
        if (d!=null) {
            int healthLost = getWorld().getObjects(Hero.class).get(0).getDamage();
            health(healthLost);
            getWorld().removeObject(getOneIntersectingObject(HeroBullet.class));
            if (getHealth() <=0) {
                getWorld().removeObject(this);
            }
        }

    }

    public void health(int healthLostBullet ){
        health = health + healthLostBullet;
    }

    public void healthBomb(int healthLostBomb){
        health = health + healthLostBomb;
    }

    public int getHealth(){
        return health;
    }
}
Bomb Code
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
 * Write a description of class Bomb here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Bomb extends Bullet
{
    int timer = 100;
    public int damage = -5;
    public void act() 
    {
        timer--;
        if (timer == 0){
            //explode();
            getWorld().removeObject(this);
        }
    }
    // removes object within the radius of the bomb
    // public void explode (){
    // getWorld().removeObjects(getObjectsInRange(200, SmartGrunt.class));
    // getWorld().removeObjects(getObjectsInRange(200, Grunt.class));
    // }

    public int damage(){
        List<Grunt> o = getObjectsInRange(200,Grunt.class);
        Hero h = ((Hero) getWorld().getObjects(Hero.class).get(0));
        if(o.size()>0){
            return damage;
        }
        else if  (o.size()<=0){
            return 0;
        }
        else return 0;
    }
}

rkr rkr

2016/12/17

#
It is still giving me the indexoutofbound exception index =0 size = 0 at line 61 in the enemy code
danpost danpost

2016/12/17

#
rkr wrote...
It is still giving me the indexoutofbound exception index =0 size = 0 at line 61 in the enemy code
It should not give you that anymore. Did you recompile after making the change?
danpost danpost

2016/12/17

#
There is something that seems a bit strange here, however. Are you delivering damage even though it is still a bomb? Should not the bomb explode first where the bomb is replaced with an explosion; then the explosion would deliver damage to all intersecting entities?
rkr rkr

2016/12/17

#
nvm it works! thanks !
rkr rkr

2016/12/17

#
how would i make the bomb explode then deal damage?
danpost danpost

2016/12/17

#
rkr wrote...
how would i make the bomb explode then deal damage?
Create an Explosion class and give it an explosion image. Add one to all locations that the bomb will affect and then remove the bomb. The Explosion class can then deal the damage to anything at their placed positions. After each one deals its damage, which can be after a slight delay to show the explosion images, it can remove itself.
rkr rkr

2016/12/17

#
thanks it works
rkr rkr

2016/12/17

#
i have another question not related to bombs if i wanted to implement knock back depending on what angle my bullet hits the enemy. How can i approach that? My bullet curves
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
 * Write a description of class HeroBullet here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class HeroBullet extends Bullet
{
    /**
     * Act - do whatever the HeroBullet wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    private int damage = -1;
    private boolean notAlreadySet = true, notAlreadySet2 = true;
    String key = "";
    int whichDirection = 0;
    double accelR = 2.5, accelL = -2.5, accelU = -2.5, accelD = 2.5;
    int rightValue = 0;
    int leftValue = 0;
    int upValue = 0;
    int downValue = 0;
    public void act() {
        getExactKey();
        setBoolean();
        setDamage();
        curve();
        move(10);
        remove();
    }
    // remove if the bullet hits an ostacles
    // remove if the bullet is at the edge of the world
    public void remove(){
        Actor f = getOneIntersectingObject(Obstacle.class);
        if (f!=null || atWorldEdge()) { //if the bullet is touching an enemy or an obstacle
            getWorld().removeObject(this); //removes this specific instance of bullet
        }
    }

    public boolean atWorldEdge(){
        if(getX() < 10 || getX() > getWorld().getWidth() - 10)
            return true;
        if(getY() < 10 || getY() > getWorld().getHeight() - 10)
            return true;
        else
            return false;
    }

    public void curve() {
        Hero h = ((Hero) getWorld().getObjects(Hero.class).get(0));
        if (whichDirection == 1 && !(key.equals("left"))) {
            setLocation(getX()+rightValue, getY());
            rightValue+=accelR;
            accelR-=0.5;
            if (accelR < 0) {
                accelR = 0;
            }
        } else if (whichDirection == 2 && !(key.equals("right"))) {
            setLocation(getX()-leftValue, getY());
            leftValue-=accelL;
            accelL+=0.5;
            if (accelL > 0) {
                accelL = 0;
            }
        } else if (whichDirection == 3 && !(key.equals("down"))) {
            //System.out.println("in" + " " + whichDirection + " " + key);
            setLocation(getX(), getY()-upValue);
            upValue-=accelU;
            accelU+=0.5;
            if (accelU > 0) {
                accelU = 0;
            } 
        } else if (whichDirection == 4 && !(key.equals("up"))) {
            setLocation(getX(), getY()+downValue);
            downValue+=accelD;
            accelD-=0.5;
            if (accelD < 0) {
                accelD = 0;
            } 
        } else {

        }
        //rightValue = 0;
        //leftValue = 0;
    }

    public void setBoolean() {
        Hero h = ((Hero) getWorld().getObjects(Hero.class).get(0));
        if (notAlreadySet) {
            if (h.movingDirection(1)) {
                whichDirection = 1;
            } else if (h.movingDirection(2)) {
                whichDirection = 2;
            } else if (h.movingDirection(3)){
                whichDirection = 3;
            } else if (h.movingDirection(4)) {
                whichDirection = 4;
            }
            notAlreadySet = false;
        }
    }

    public void getExactKey() {
        Hero h = ((Hero) getWorld().getObjects(Hero.class).get(0));
        if (notAlreadySet2) {
            key = h.returnV();//System.out.println(key);
            notAlreadySet2 = false;
        }
    }

    //sets the damage according to the damge set in hero
    public void setDamage(){
        damage = getWorld().getObjects(Hero.class).get(0).getDamage();
    }

}
danpost danpost

2016/12/17

#
rkr wrote...
if i wanted to implement knock back depending on what angle my bullet hits the enemy. How can i approach that?
Just use the rotation of the bullet.
rkr rkr

2016/12/17

#
so if the bullet collides with the enemy i should set the location of the enemy by using the bullet rotation how should i do that? is there any trigonometry involved
There are more replies on the next page.
1
2
3