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

2012/11/10

Move the snake

1
2
3
4
5
6
Tezuka Tezuka

2012/11/14

#
I tried to add a counter but I cant pass the referens to my snake cuz it already have a parameter what should I do? i want to remove all objects in the world but I want to call the method in my snake class
danpost danpost

2012/11/14

#
Alright. I was going to say that you should have the counter in the world class. But, you could work the counter like you work the 'length' variable (each segment, whether head or body, has a seperate 'length' variable; but, you are only using the one in the 'head' segment). So, you could have a 'counter' variable in each segment; but all, except the one in the 'head' segment, will be 'null'. (1) Do not declare or create a Counter object in the world class. (2) In the Snake class, remove the constructor that has a Counter object as the parameter. (3) Make sure you declare 'private Counter counter;' in the Snake class. (4) In the Snake class, add the following method:
public void addedToWorld(World world)
{
    if (!"head".equals(segment)) return;
    counter = new Counter(); // may have to adjust constructor call
    world.addObject(counter, 100, 100); //wherever
}
Tezuka Tezuka

2012/11/14

#
thx that worked great
Tezuka Tezuka

2012/11/14

#
I want to remove all my objects in the actor is there a way to di it. I found removeObjects(getObjects(null)); but didnt work.
danpost danpost

2012/11/14

#
Try
getWorld().removeObjects(getWorld().getObjects(null));
'removeObjects' and 'getObjects' are non-static methods that are part of the World Class API; so, you need to execute them on world objects.
Tezuka Tezuka

2012/11/14

#
I get this message when I put it in my die() class java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed. at greenfoot.Actor.failIfNotInWorld(Actor.java:663) at greenfoot.Actor.getY(Actor.java:170) at Snake.move(Snake.java:115) at Snake.act(Snake.java:60) at greenfoot.core.Simulation.actActor(Simulation.java:565) at greenfoot.core.Simulation.runOneLoop(Simulation.java:523) at greenfoot.core.Simulation.runContent(Simulation.java:213) at greenfoot.core.Simulation.run(Simulation.java:203)
danpost danpost

2012/11/14

#
In the 'move' method of the Snake class, within the same 'if' block that the call to 'die();' is, and immediately after it, put a 'return;' statement.
Tezuka Tezuka

2012/11/14

#
now i get this java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed. at greenfoot.Actor.failIfNotInWorld(Actor.java:663) at greenfoot.Actor.getOneObjectAtOffset(Actor.java:867) at Snake.eat(Snake.java:148) at Snake.act(Snake.java:61) at greenfoot.core.Simulation.actActor(Simulation.java:565) at greenfoot.core.Simulation.runOneLoop(Simulation.java:523) at greenfoot.core.Simulation.runContent(Simulation.java:213) at greenfoot.core.Simulation.run(Simulation.java:203)
danpost danpost

2012/11/14

#
OK. In the 'act' method of the Snake class, between 'move();' and 'eat();', add the following line
if (getWorld() == null) return;
Tezuka Tezuka

2012/11/14

#
wow nice it worked but could u explaine those 3 lines?
danpost danpost

2012/11/14

#
Tezuka wrote...
wow nice it worked but could u explaine those 3 lines?
Which 3 lines are you referring to?
Tezuka Tezuka

2012/11/15

#
getWorld().removeObjects(getWorld().getObjects(null)); if (getWorld() == null) return; and the return statements
danpost danpost

2012/11/15

#
OK. (1) You wanted to remove all the objects from the world in the 'die' method. Since 'removeObjects' and 'getObjects' are World methods (not Actor methods) we need to prefix them with 'getWorld()' which return the world object that the actor is in. 'getObjects(null)' will return a list of all objects in that world. 'removeObjects' will remove all the object in the list of objects that are in that world. (2) the return satements: once you call die (and the object is removed from the world), you do not want to (and no longer can) do anything more with the object itself as far as moving, checking intersections, or checking world boundaries). The 'return;' statement immediately exits the method without any further instructions being executed. So, if you find that the object has hit the right or left edge of the world and you remove the object, and then try to see if it has hit the top or bottom edge, you will get the error because 'getX()' and 'getY()' cannot return a value if the actor is not in the world. (3) if (getWorld() == null) return; : this is related to (2) above. You do not want to execute any statements beyound the call to 'move' if the object is removed from the world. The 'return;' statements in (2) above only exits you from the 'move' method and puts you back in the 'act' method; now, you do not want to execute the call to 'eat' when the object is not in the world. So, we must ensure that the actor is still in the world before executing 'eat'. If not, exit the 'act' method.
Tezuka Tezuka

2012/11/15

#
OK. thx a lot for ur help. You sure know alot.
Tezuka Tezuka

2012/11/16

#
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
 * Write a description of class Playground here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Playground extends World
{
    /**
     * Defines the variables required in game.
     */
    private Snake snakeBody[];
    private Food food;
    private Counter score;
    private int direction;
    private boolean eaten;
    private int gameState;
    /**
     * Constructor for objects of class Playground.
     * 
     */
    public Playground()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1); 
        direction = 0;
        eaten = false;
        gameState = 0;
    }

    /**
     * Game starts from here.
     */ 
    public void act()
    {
        checkKeys();
        gameStates();
        
        if(eaten)
        {
            updateFoodLocation();// updates the location of the food;
        }


        int previousLocationX = snakeBody[0].getX();
        int previousLocationY = snakeBody[0].getY();
        snakeBody[0].move(20); // moves one step

        
        if(snakeBody[0].getX()!=previousLocationX || snakeBody[0].getY()!=previousLocationY) // Checks if the snake hits walls
        {
            for(int i=1; i<snakeBody.length; i++)
            {
                previousLocationX = snakeBody[i].getX();
                previousLocationY = snakeBody[i].getY();
                snakeBody[i].move(20); // entire body moves one step

            }

            if(snakeBody[0].getX()==food.getX() && snakeBody[0].getY()==food.getY()) // Checks if the snake eats food
            {
                growSnake(previousLocationX, previousLocationY);
                updateFoodLocation();
                score.add(5);
            }

            for ( int i = 1; i < snakeBody.length; i++)// Checks if the snake eats itself
            {
                if( snakeBody[0].getX() == snakeBody[i].getX() && 
                snakeBody[0].getY() == snakeBody[i].getY());
                {
                    gameState = -1;
                }
            }
        }
        else
        {
            gameState = -1;
        }
    }

    /**
     * This method will update the length of the Snake.
     */
    private void growSnake(int x, int y)
    {
        Snake s = new Snake(false);
        Snake oldSnake[] = new Snake[snakeBody.length];
        for(int i = 0; i < snakeBody.length; i++)
        {
            oldSnake[i] = snakeBody[i];
        }
        snakeBody = new Snake[snakeBody.length+1];
        for( int i = 0; i < snakeBody.length -1; i++)
        {
            snakeBody[i] = oldSnake[i];
        }
        snakeBody[snakeBody.length-1] = s;
        addObject(snakeBody[snakeBody.length-1], x , y);
    }

    private void updateFoodLocation()
    {
        int x = 0;
        int y = 0;
        boolean overlap = true;
        eaten = false;

        while(overlap)
        {
            x = Greenfoot.getRandomNumber(getWidth());
            y = Greenfoot.getRandomNumber(getHeight());

            for( int i = 1; i < snakeBody.length; i++)
            {
                // Condition to check food will not touch the snake
                if( x!= snakeBody[i].getX() || y!=snakeBody[i].getY())
                {
                    overlap = false;
                    break;
                }
            }
        }
        food.setLocation(x * 15, y * 15);
    }

    public void checkKeys()
    {
        if(Greenfoot.isKeyDown("right")) // checks if right key is pressed
        {
            if(direction==1 || direction==3)
                direction = 0;
        }
        else if(Greenfoot.isKeyDown("down")) // checks if down key is pressed
        {
            if(direction==0 || direction==2)
                direction = 1;
        }
        else if(Greenfoot.isKeyDown("left")) // checks if left key is pressed
        {
            if(direction==1 || direction==3)
                direction = 2;
        }
        else if(Greenfoot.isKeyDown("up")) // checks if up key is pressed
        {
            if(direction==0 || direction==2)
                direction = 3;
        }
    }
    
    public void gameStates()
    {
        if( gameState==0) // Initialization
        {
            setBackground("SnakeGame.jpg");
        }
        if(Greenfoot.getKey() !=null) // check if any key is pressed
        {
            gameState = 1; return;
        }
        else if ( gameState == 1) // Game Activate State
        {
            setBackground("bluerock.jpg");

            food = new Food(); // initialization of the food
            addObject(food, 0,0); // adding food actor to the world

            score = new Counter("Score : "); // initialization of the score
            addObject( score, 20, 4);// adding score

            snakeBody = new Snake[3]; // // initialization of the Snake
            for( int i = 0; i < snakeBody.length; i++)
            {
                snakeBody[i] = new Snake(i==0);
                addObject(snakeBody[i], 90+(snakeBody.length-i)* 15, 30);
            }
            updateFoodLocation();
            gameState = 2;
            return;
        }

        else if( gameState == -1) // game over
        {

            setBackground("GameOver.jpg");
            addObject(score, 300, 8);
            return;
        }
    }
}
Can u tell me what wrong with this code? i get a null exeption
There are more replies on the next page.
1
2
3
4
5
6