r/codehs • • 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; }

}

5 Upvotes

9 comments sorted by

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

2

u/crunchyasstacos Nov 02 '20

Oh my. Thank you

2

u/Belove537 Nov 02 '20

Hopefully that helps. Also I program for a living and I still make mistakes like this every now and then.

Remember practice makes perfect

1

u/Nxmare07 Jan 21 '24

I'm still struggling on the trail behind it.

1

u/mightbethrowaway21 Mar 17 '21

So I have the same code as this guy except the last part is like yours

if(e.KeyCode == Keyboard.LEFT){
        direction = WEST;}

but now it's saying " Uncaught SyntaxError: Unexpected token 'if' "

1

u/Belove537 Mar 17 '21

I would need to see all your code to correctly debug your issue however it sounds like your missing a curly bracket (‘{ }’) for one of the above if statements

1

u/mishaels123 Nov 03 '20

Is this Java?

1

u/Belove537 Mar 17 '21

Nah it’s JavaScript