I am making a Snake game. Snake increases its tail when eats food. However, the snake eats food, its tail doesn't increase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Snake here. * * @author (your name) * @version (a version number or a date) */ public class Snake extends Actor { /** * Act - do whatever the Snake wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ private int speed = 2 ; private int dx = 1 ; private int dy = 0 ; private int foodCounter = 0 ; public Snake() { //Set the head of snake. GreenfootImage img = new GreenfootImage( 10 , 10 ); //Create a new image with 20x20 as the size. img.setColor(Color.WHITE); //Set colour img.fill(); //Fill the block. setImage(img); //Save our changes. } public void act() { // turnAround(); move(speed); if (isTouching(food. class )) { removeTouching(food. class ); SnakeWorld sw = (SnakeWorld)getWorld(); sw.addFood(); getWorld().addObject( new tail(), getX()- 1 , getY()- 1 ); } } public void turnAround() { if (Greenfoot.isKeyDown( "up" ) && dx == 0 ) { dx = - 1 ; dy = 0 ; setRotation( 270 ); } if (Greenfoot.isKeyDown( "down" ) && dx == 0 ) { dx = - 1 ; dy = 0 ; setRotation( 90 ); } if (Greenfoot.isKeyDown( "left" ) && dy == 0 ) { dx = 0 ; dy = 1 ; setRotation( 180 ); } if (Greenfoot.isKeyDown( "right" ) && dy == 0 ) { dx = 0 ; dy = 1 ; setRotation( 360 ); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class tail here. * * @author (your name) * @version (a version number or a date) */ public class tail extends Actor { /** * Act - do whatever the tail wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ int count = 0 ; public tail() { GreenfootImage img = new GreenfootImage( 10 , 10 ); //Create a new image with 20x20 as the size. img.setColor(Color.WHITE); //Set colour img.fill(); //Fill the block. setImage(img); } public void act() { } } |