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

2016/7/7

java.lang.NullPointerException

Changster101 Changster101

2016/7/7

#
When I run my Cruiser into my PIrate, the pirate should re spawn, or go back to the right of the screen. But the game stops when the cruiser runs into the pirate, giving me an error.
java.lang.NullPointerException
	at Pirate.reSpawn(Pirate.java:41)
	at Cruiser.rekted(Cruiser.java:167)
	at Cruiser.act(Cruiser.java:46)
	at greenfoot.core.Simulation.actActor(Simulation.java:604)
	at greenfoot.core.Simulation.runOneLoop(Simulation.java:562)
	at greenfoot.core.Simulation.runContent(Simulation.java:221)
	at greenfoot.core.Simulation.run(Simulation.java:211)
My cruiser class
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Cruiser here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Cruiser extends Actor
{
    private static int count;
    Pirate pirate;
    private int gunHeat = 0;
    private int lives;
    private int timer = 0;
    GreenfootImage image1;
    GreenfootImage image;
    public Cruiser(Pirate pirate)
    {
        GreenfootImage image = getImage();
        
        GreenfootImage image1 = new GreenfootImage("Boost.png");
        image.scale(100, 45);
        this.image = image;
        lives = 3;
        this.pirate = pirate;
        this.image1 = image1;
        count=0;
    }   

    /**
     * Act - do whatever the Cruiser wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        motionControl();
        //stayInWorld();
        boost();
        fire();
        stayInWorldY1();
        stayInWorldY();
        gunHeat--;
        
        isShot();
        rekted();
        
        fuelLevel();
        moreFuel();
        
        
    }    

    private void motionControl()
    {
        if (getX()>0 && getX() < getWorld().getWidth())
        {

            if(Greenfoot.isKeyDown("up"))
            {
                setLocation(getX(),getY()-3);
            }
            if(Greenfoot.isKeyDown("down"))
            {
                setLocation(getX(),getY()+3);
            }
            if(Greenfoot.isKeyDown("right"))
            {
                setLocation(getX()+3,getY());
            }
            if(Greenfoot.isKeyDown("left"))
            {
                setLocation(getX()-3,getY());
            }
        } else 
        {
            setLocation(50, getY());
        }
    }

    private void stayInWorldY()
    {
        if (getY()>0)
        {

            if(Greenfoot.isKeyDown("up"))
            {
                setLocation(getX(),getY()-3);
            }
            if(Greenfoot.isKeyDown("down"))
            {
                setLocation(getX(),getY()+3);
            }
            if(Greenfoot.isKeyDown("right"))
            {
                setLocation(getX()+3,getY());
            }
            if(Greenfoot.isKeyDown("left"))
            {
                setLocation(getX()-3,getY());
            }
        }
        else 
        {
            setLocation(getX(), 550);
        }
    }

    private void stayInWorldY1()
    {
        if (getY()<getWorld().getHeight())
        {

            if(Greenfoot.isKeyDown("up"))
            {
                setLocation(getX(),getY()-3);
            }
            if(Greenfoot.isKeyDown("down"))
            {
                setLocation(getX(),getY()+3);
            }
            if(Greenfoot.isKeyDown("right"))
            {
                setLocation(getX()+3,getY());
            }
            if(Greenfoot.isKeyDown("left"))
            {
                setLocation(getX()-3,getY());
            }
        }
        else 
        {
            setLocation(getX(), 50);
        }
    }

    //public void stayInWorld()
    // {
    //   if(getX()<10 || getX()>790)
    // {
    //    setLocation(50, getY());
    //}
    // }
    //ASK ABOUT HOW TO GET A TIME LIMIT FOR THIS

    public void boost()
    {
        if (Greenfoot.isKeyDown("shift"))
        {
            setLocation(getX()+5,getY());
           
            getImage();
            setImage(image1);
            
        }else 
        {
            getImage();
            setImage(image);
        }
    }

    public void rekted()
    {
        
        if(getOneIntersectingObject(Pirate.class) !=null && Greenfoot.isKeyDown("shift") )
        {
         this.pirate.reSpawn();
         
         
         
            
        }
    }

    private void fire()
    {
        if (Greenfoot.isKeyDown("space") && gunHeat <= 0)
        {
            getWorld().addObject(new Missile(), getX()+45,getY());
            Greenfoot.playSound("shot1.wav");
            gunHeat = 25;

        }
    }

    

    public void removeLives()
    {
        Space space = (Space) getWorld();
        Score score = space.getScore();
        score.updateScore(score.getPoints(), score.getPower(), "Lives: " + lives);  
    }

    private void isShot()
    {
        Actor enemyLaser = getOneIntersectingObject(EnemyLaser.class);
        if (enemyLaser !=null)
        {
            getWorld().removeObject(enemyLaser);
            getWorld().addObject(new Explosion(), getX(), getY());
            lives--;
           if (lives <= 0)
           {
               Space space = (Space) getWorld();
               space.gameOver();
            }else
            {
                removeLives();
            }
           
          
        }
        
    
    
    }
    public void fuelLevel()
    {
        timer++;
        
        if(timer>=100)
        {
        Space space = (Space) getWorld();
        Score score = space.getScore();
        score.updateScore(score.getPoints(), score.getPower()-1, score.getLives());
        timer = 0;
        
        if (score.getPower() <= 0)

        {
            space.gameOver();
        }
    }
    }
    public void moreFuel()
    
    {
        Actor powerUp = getOneIntersectingObject(PowerPod.class);
        if (powerUp !=null)
        {
            getWorld().removeObject(powerUp);
            Space space = (Space) getWorld();
        Score score = space.getScore();
        score.updateScore(score.getPoints(), score.getPower()+10, score.getLives());
        if(score.getPower() >100)
        {
            score.updateScore(score.getPoints(), 100, score.getLives());
        }
        }
    }
    // public void pirateCollision()
    // {
        // Actor pirate = getOneIntersectingObject(Pirate.class);
        // if (pirate !=null)
        // {
            // Space space = (Space) getWorld();
            // space.gameOver();
        // }
    // }


}
My pirate class
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.lang.*;
/**
 * Write a description of class Pirate here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Pirate extends Actor
{
    private static int count;
    
    public Pirate()
    {
        count = 0;
    }
    /**
     * Act - do whatever the Pirate wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        move();
        isHit();
        fireShot();
    }    

    private void move()
    {
        setLocation(getX()-3, getY());
        if (getX() < 10)
        {
            reSpawn();
        }
    }

    public void reSpawn()
    {
         
        int distance = Greenfoot.getRandomNumber(100);
        setLocation(getWorld().getWidth() + distance, Greenfoot.getRandomNumber(600));
        if (getOneIntersectingObject(Pirate.class) !=null)
        {
            reSpawn();
        }
    }

    private void isHit()

    {
        Actor missile=getOneIntersectingObject(Missile.class);

        if(missile !=null)
        {
            getWorld().removeObject(missile);
            count++;
            addPoints();
            getWorld().addObject(new Explosion(), getX(), getY());
            if(Greenfoot.getRandomNumber(10) <1)
            {
                getWorld().addObject(new PowerPod(), getX(), getY());
            }
            reSpawn();
                       
                       //some methods excluded
        }

    }

    private boolean inRange()
    {
        Space world = (Space) getWorld();
        Cruiser cruiser = world.getCruiser();
        int range = Math.abs(cruiser.getY() - getY());
        
        
        return (range > 0 && range <20);
        
    }

    public void fireShot()
    {
        if(Greenfoot.getRandomNumber(1000)<50)
        {
            if (inRange())
            {
                getWorld().addObject(new EnemyLaser(),getX(),getY());
            }
        }
    }
    public void addPoints()
    {
        Space space = (Space) getWorld();
        Score score = space.getScore();
        score.updateScore("Score: " + count, score.getPower(), score.getLives());
    }
}

danpost danpost

2016/7/8

#
The only thing on line 41 of the Pirate class that could give that error is 'getWorld'. This tells me that 'pirate' in the Cruiser class is not the pirate that you have in the world. Make sure (by looking at the Space class code) that the Pirate object that is added into the world is the same Pirate object that is passed to the Cruiser object when creating it. If you cannot figure it out, post the class code of the Space class.
Changster101 Changster101

2016/7/8

#
I can't figure it out. Here is the space code. Thank you for the quick response.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.*;
/**
 * Write a description of class Space here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Space extends World
{
    Cruiser cruiser;
    Score score;
    Pirate pirate;
    Flames flames;
    /**
     * Constructor for objects of class Space.
     * 
     */
    public Space()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        
        
        super(800, 600, 1, false); 
        
        GreenfootImage background = getBackground();
        background.setColor(new Color (000, 000, 000));
        background.fill();
        
        createStars(100);
        
        flames = new Flames(cruiser);
        pirate = new Pirate();
        cruiser = new Cruiser(pirate);
        score = new Score("Score: 0", 100, "Lives: 3");
        
        addObject(cruiser, 100, 300);
        addObject(new Pirate(), getWidth() + 50, Greenfoot.getRandomNumber(600));
        addObject(new Pirate(), getWidth() + 50, Greenfoot.getRandomNumber(600));
        addObject(new Pirate(), getWidth() + 50, Greenfoot.getRandomNumber(600));
        addObject(score, 400, 30);
        
        
        setPaintOrder(Cruiser.class, Explosion.class, Pirate.class, Missile.class, Stars.class);
        
        this.cruiser = cruiser;
    }
    
    private void createStars(int numStars)
    {
       for (int i = 0; i <= numStars; i++)
       {
           int xPos = Greenfoot.getRandomNumber(getWidth());
           int yPos = Greenfoot.getRandomNumber(getHeight());
           addObject(new Stars(),xPos, yPos);
        }
        
       
    }
    public void gameOver()
    {
        removeObjects(getObjects(Cruiser.class));
        removeObjects(getObjects(Pirate.class));
        removeObjects(getObjects(Explosion.class));
        removeObjects(getObjects(Missile.class));
        removeObjects(getObjects(EnemyLaser.class));
        removeObjects(getObjects(PowerPod.class));
        removeObjects(getObjects(Score.class));
        addObject(new EndScreen(score.getPoints()), getWidth ()/2, getHeight()/2);
        Greenfoot.stop();
    }
    public Cruiser getCruiser()
        {
            return cruiser;
        }
    public Score getScore()
        {
            return score;
        }
        public Flames getFlames()
        {
            return flames;
        }
}
danpost danpost

2016/7/8

#
Before giving any suggestions for fixing the issue, let me explain what is happening here -- because if you can make sense of what is happening, you are better equipped to avoid the same issue in the future. In the Space class, you have line 33 assigning a new Pirate object to the 'pirate' field declared on line 13. On line 34, you are passing this object to a new Cruiser object for it to store by line 26 of the Cruiser class in its 'pirate' field declared on line 12. Nowhere past line 34 of the Space class is this Pirate object ever referred to again; that is, it is not added into the world. Lines 38, 39 and 40 add Pirate objects into the world, but these are new and different instances of the class. Hence, when the Cruiser object calls 'reSpawn' on the 'pirate' and the method tries to get the world that this Pirate object is in, a 'null' value is returned (it is not in any world) -- and when 'getWidth' is called on a non-existent world ... well, you just cannot get the width of a world that does not exist; hence, the NullPointerException error. Now, because you are adding multiple Pirate objects into the world, having the Cruiser hold a reference to just one of them makes little sense (in your case). Which one of the Pirate objects should the field be set to, indeed! Apparently, the world is to maintain a count of three Pirate object in it. Notice what I just expressed. The World is to maintain this state. This can be done by adding the following to the Space class:
public void act()
{
    if (getObjects(Pirate.class).size() < 3)
    {
        addObject(new Pirate(), 0, 0);
    }
}
I realize that you do not want them to spawn at the location (0, 0) -- but bear with me here. When adding the initial Pirate objects into the world (via the Space class constructor), you are placing them all at the same location; yet, in the 'reSpawn' method of the Pirate class, you seem to be worried about them spawning on top of each other (placing them more randomly along the x-axis and checking for overlapping with other Pirate objects). I do not know how important that is, especially considering that they are being spawned outside the world viewing window. If it really does not matter than you can change the location above to the same location as where you placed them in the constructor. If it does matter, then add the following to the Pirate class:
protected void addedToWorld(World world)
{
    while (getX() < world.getWidth() || getOneIntersectingObject(Pirate.class) != null)
    {
        int x = world.getWidth()+Greenfoot.getRandomNumber(100);
        int y = Greenfoot.getRandomNumber(world.getHeight());
        setLocation(x, y);
    }
}
Either way, remove the 'reSpawn' method from the Pirate class and any calls to it. Also, remove the 'Pirate pirate' fields from all classes and the parameters to the constructors to any classes that you have a Pirate object going to (fixing those calls as well).
You need to login to post a reply.