So I'm trying to make a snake game and i can't get body parts to fallow each other in line. Can anyone give me any help? Here's my code:
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | public class Ground extends World { Random rand = new Random(); public Ground() { super ( 500 , 500 , 1 ); addObject( new Snake(), 250 , 250 ); addObject( new Apple(), rand.nextInt( 460 ) + 20 , rand.nextInt( 460 ) + 20 ); } public void showMap1() { setBackground( "ground.png" ); } } public class Apple extends Actor { public Apple(){ GreenfootImage image = getImage(); image.scale( 30 , 30 ); setImage(image); } } public class Snake extends Actor { public Snake(){ GreenfootImage image = getImage(); image.scale( 40 , 40 ); setImage(image); } @Override public void act() { moveHead(); if (Greenfoot.isKeyDown( "left" ) && getRotation() != 0 ){ setRotation( 180 ); } if (Greenfoot.isKeyDown( "right" ) && getRotation() != 180 ){ setRotation( 0 ); } if (Greenfoot.isKeyDown( "up" ) && getRotation() != 90 ){ setRotation( 270 ); } if (Greenfoot.isKeyDown( "down" ) && getRotation() != 270 ){ setRotation( 90 ); } Random rand = new Random(); int i = 1 ; Actor b = getOneIntersectingObject(Apple. class ); if (b != null ) { getWorld().removeObject(b); getWorld().addObject( new Apple(), rand.nextInt( 460 ) + 20 , rand.nextInt( 460 ) + 20 ); Body node = new Body(i); getWorld().addObject(node, getX(), getY()); i++; } } public void moveHead() { delay( 10 ); if (getRotation() == 180 ){ //left setLocation(getX() - 30 , getY()); } if (getRotation() == 0 ){ //right setLocation(getX() + 30 , getY()); } if (getRotation() == 270 ){ //up setLocation(getX(), getY() - 30 ); } if (getRotation() == 90 ){ //down setLocation(getX(), getY() + 30 ); } } } public class Body extends Snake { private int i; public Body( int node){ this .i = node; GreenfootImage image = getImage(); image.scale( 45 , 45 ); setImage(image); } @Override public void act() { moveBody( this .i); } public void moveBody( int i) { if (getRotation() == 180 ){ //left setLocation(getX() - ( 30 *i), getY()); } if (getRotation() == 0 ){ //right setLocation(getX() + ( 30 *i), getY()); } if (getRotation() == 270 ){ //up setLocation(getX(), getY() - ( 30 *i)); } if (getRotation() == 90 ){ //down setLocation(getX(), getY() + ( 30 *i)); } } } |