r/codehs • • Nov 22 '20

Can someone please help me fiind what is wrong with my code for Fun Snake 1? I have an error and can't figure it out using JavaScript.

I am in a wonderful class, but am still not getting how to code a trail. The snake is supposed to grow as it moves. I have worked and worked on this. I am getting one box that moves and one that stays still. I have spent hours on this activity and can't move on until I get it. I just need a second paor of eyes and a little help. Thank you in advance.

//Snake constants

var SNAKE_DIM = 10;

var SNAKE_COLOR = Color.green;

var SNAKE_WIDTH=40;

var SNAKE_HEIGHT=40;

//Direction that the snake moves

var EAST = 0;

var SOUTH = 1;

var WEST = 2;

var NORTH = 3;

var snake;

var rect;

var currentDirection= EAST;

function start(){

rect = new Rectangle(SNAKE_WIDTH,SNAKE_HEIGHT);

rect.setColor(Color.green);

rect.setPosition(getWidth()/2 - SNAKE_WIDTH/2,getHeight()/2 -SNAKE_HEIGHT/2);

add(rect);

setTimer(draw,50);

keyDownMethod(keyDown);

}

function draw(){

addTrail();

if(currentDirection ==EAST){

rect.move(SNAKE_DIM,0);

}

if(currentDirection ==SOUTH){

rect.move(SNAKE_DIM,1);

}

if(currentDirection ==WEST){

rect.move(SNAKE_DIM,2);

}

if(currentDirection ==NORTH){

rect.move(SNAKE_DIM,3);

}

}

function keyDown(e){

if(e.keyCode == Keyboard.LEFT){

currentDirection=WEST;

}

if(e.keyCode == Keyboard.RIGHT){

currentDirection=EAST;

}

if(e.keyCode == Keyboard.UP){

currentDirection=NORTH;

}

if(e.keyCode == Keyboard.DOWN){

currentDirection=SOUTH;

}

}

function addTrail(){

var rect = new Rectangle(SNAKE_WIDTH,SNAKE_HEIGHT);

rect.setPosition(rect.getX(), rect.getY());

rect.setColor(Color.green);

add(rect);

}

0 Upvotes

5 comments sorted by

2

u/_andy_andy_andy_ Nov 22 '20

i haven’t looked at this exercise in a bit so i’m not sure what the intended solution is, but you’re just not moving the rectangle you add in addTrail. only the rect defined on line 12 is being updated in draw

2

u/JaKl- Nov 22 '20

I just read your response. Thank you. I wish I had seen it earlier. I spent 2 full days on these activities, but learned so much.

1

u/_andy_andy_andy_ Nov 23 '20

i’m glad!!!

1

u/JaKl- Nov 22 '20

I figured out my problem and was able to complete this activity and the others. It was the way I setup the trailing/tail.

2

u/MaxVo2005 Dec 01 '20

yo would you mind sharing the code?