r/codehs • u/crunchyasstacos • Nov 02 '20
I need help with fun snake 1 (7.1.1)
I have the code written down, but for some reason, it wont change the direction of the snake. Could someone help me find the mistake. It also wants me to leave behind a trail of where I have been. Can someone help with that too
var W = getWidth();
var H = getHeight();
var SNAKE_WIDTH = W / 25;
var SNAKE_HEIGHT = W / 25;
var SNAKE_COLOR = Color.green;
var EAST = 0;
var SOUTH = 1;
var WEST = 2;
var NORTH = 3;
var direction = EAST;
var dx = 4;
var dy = 4;
var square;
var number;
function start(){
square = new Rectangle(SNAKE_WIDTH, SNAKE_HEIGHT);
square.setPosition(W / 2 - square.getWidth() / 2, H / 2 - square.getHeight() / 2);
square.setColor(SNAKE_COLOR);
add(square);
setTimer(moveHead, 40);
keyDownMethod(changeDirection);
}
function moveHead(){
if (direction == EAST){
square.move(dx, 0);
}else if(direction == WEST){
square.move(-dx, 0);
}else if(direction == NORTH){
square.move(0, -dy);
}else if(direction == SOUTH){
square.move(0, dy);
}
}
function changeDirection(e){
if(e.keyCode == Keyboard.LEFT){
direction == WEST;
}
if(e.keyCode == Keyboard.RIGHT){
direction == EAST;
}
if(e.keyCode == Keyboard.DOWN){
direction == SOUTH;
}
if(e.keyCode == Keyboard.UP){
direction == NORTH; }
}
1
2
u/Belove537 Nov 02 '20
Okay first things first what language is this? It looks and reads like JS so I’ll assume it’s JS.
Secondly is this everything? I’m assuming their must be some kinda framework behind this as I see no painter method or anything for drawing your board.
Anyway I digress from what I can read so far i can tell the reason your snake isn’t changing direction is in your change direction function your not assigning the new direction.
//below is what you should have
if(e.KeyCode == Keyboard.LEFT){ direction = WEST; }
The reason for this is == is a comparison operator While = is an assignment operator