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

2018/6/25

My snake won't move anymore

vaal vaal

2018/6/25

#
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class SnakeHead here.
 * 
 * @author (Valentijn & Oline) 
 * @version (Final Draft)
 */
public class SnakeHead extends Animal
{  
   
   
   /**
     * Act - do whatever the SnakeHead wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
       int count = 0;
       
       int Diamondseaten = 0;
      
       
    
    
    
        if (Greenfoot.isKeyDown("left")) {
            if (canSee (Wall.class))
            {}
           turn(-25);
        }
        if (Greenfoot.isKeyDown("right")){
            if (canSee (Wall.class))
           {}
            turn(25);
        }
        if (Greenfoot.isKeyDown("up")){
            if (canSee (Wall.class))
            {
                World world = getWorld();
                getWorld().removeObjects(getWorld().getObjects(null));
            }
            move();
        }
        if (Greenfoot.isKeyDown("down")){
            if (canSee (Wall.class))
            {}
            move(-2);
        }
      
        if (canSee(Diamond.class))
        {
            removeTouching (Diamond.class);
        }
        if (isTouching(Wall.class))
        {
            Greenfoot.stop();
            Greenfoot.setWorld(new SnakeWorld());
            
      
    }  
  
     if(count > 20){
         
        move();
        count = 0;
    }
        
    if(Diamondseaten < 1){
        count += 1;
    }else if(Diamondseaten < 2){
        count += 2;
    }else if(Diamondseaten < 3){
        count += 2.5;
    }else if(Diamondseaten < 4){
        count += 4;
    }else if(Diamondseaten >= 4){
        count += 5;
    }
    
    int speed = 20;
    
    if(count == speed){
        getWorld().addObject(new SnakeTail(Diamondseaten*speed), getX(), getY());
    }
    
    
}
}
danpost danpost

2018/6/26

#
vaal wrote...
My snake won't move anymore << Code Omitted >>
Line 60 will never be true. You set the count field to zero at line 19 while declaring the variable, which exists only for the current execution of the method. Line 74 tries to add a fractional amount to the count field which is declared to hold an integer value, so only 2 will be added there. Since the Diamondseaten field is set to zero at line 21 and count is incremented to 1 at line 70, and since speed is set to 20 at line 81, count will never be speed at line 83. You main issue is not knowing how to handle your variables. Variables you declare inside a method are only valid for that execution of the method. To have variables persist longer (as long as the object that has them exists), they must be declared outside any method.
You need to login to post a reply.