Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas Game: My snake eats itself

Since my other bug got solved, I'm posting a new question for this bug.

I made a Snake canvas game, but my snake tends to eat itself when you press two buttons at the same time.. I'm not sure how to explain it properly, but this is what happens:

Say my snake is moving towards the left, and I press down + right, it'll eat itself and trigger a game over. Same when it goes to the right: down + left and bam, dead. I can't seem to reproduce the bug when the snake goes up and down though..

This is the code involved with changing directions:

bindEvents = ->
    keysToDirections =
        37 : LEFT
        38 : UP
        39 : RIGHT
        40 : DOWN

    $(document).keydown (e) -> 
        key = e.which
        newDirection = keysToDirections[key]

        if newDirection
            setDirection newDirection
            e.preventDefault()

setDirection = (newDirection) ->
    # TODO: there's some bug here; try pressing two buttons at the same time..
    switch Snake.direction
        when UP, DOWN
            allowedDirections = [LEFT, RIGHT]
        when LEFT, RIGHT
            allowedDirections = [UP, DOWN]

    if allowedDirections.indexOf(newDirection) > -1
        Snake.direction = newDirection

I thought there was something wrong with the compiled JS because my switch statement doesn't have a break on the last case; however, I tried adding else return to the coffee script file and this didn't change anything. I'm completely lost here so I hope someone will be able to spot where I'm going wrong.

It seems as if it takes the keydown events right, but they get overridden when you press too fast. If that makes sense? Like.. You'd press up when the snake is going right, but then you press left before it actually had a chance to go up and then it just goes left. Chaotic sentence right there, I suggest you play for a while and try to reproduce this if you're as intrigued as I am :(

I have no clue how to debug this properly.. The game loop tends to spam me with messages when I do console.log.

A live demo and link to my github repo can be found here

Thanks in advance.

like image 507
Joris Ooms Avatar asked Nov 04 '11 15:11

Joris Ooms


2 Answers

The problem is that if you push the keys quickly enough, its possible to trigger the event callback multiple times during one frame. Thus, if the snake is going down, it can turn right and then up in the same frame, thus reversing direction and eating itself. I'll suggest two ways to solve this problem:

The first is to set a flag when the direction is changed, i.e.:

if allowedDirections.indexOf(newDirection) > -1 and !turnedThisFrame
    Snake.direction = newDirection
    turnedThisFrame = true

and then, in your code that runs every frame, set turnedThisFrame to false.

The second is to rework how you deal with keypresses. This is often the approach that I take. Keep a map of which keys are pressed (say, keysDown), and bind a function that sets keysDown[e.which] = true to keydown and another function which sets keysDown[e.which] = false to keyup. Then, you can check which keys are pressed in the code that runs each frame, and act accordingly.

Here's some details on how I implemented the second solution in a current project. The following code appears in my onload handler:

do ->
  keysDown = []

  $(document).keydown (e) ->
    keysDown.push e.which

  $(document).keyup (e) ->
    keysDown = _.without keysDown, e.which

  window.isPressed = (keyCode) -> keyCode in keysDown

The do -> construct is used to create a function and immediately calling it, which has the beneficial effect of keeping keysDown in closure for the handlers and isPressed, while avoiding polluting the main scope of the onload callback.

Then, at the beginning of my tick function (which runs once per frame and handles game logic, drawing the screen, etc.) I would have something like this:

switch Snake.direction
    when UP, DOWN
        allowedDirections = [LEFT, RIGHT]
    when LEFT, RIGHT
        allowedDirections = [UP, DOWN]

for direction in allowedDirections
    if isPressed(directionToKey[direction])
        Snake.direction = newDirection
        break

The map directionToKey would just be the opposite of your keysToDirections.

Note that this means that keys listed first in allowedDirections will have priority, i.e. if you are going right and press both up and down in the same frame, up will occur regardless of which was pressed first.

Added advantage to this second method: you don't have to change the key handler callbacks when switching between, say, a menu screen and the game. You just have a different tick function checking for what is pressed.

like image 90
Aaron Dufour Avatar answered Nov 10 '22 08:11

Aaron Dufour


You must retain the last direction is which the snake actually moved and determine allowedDirection based on that. Pressing a key only represents the intent to move in that direction, but it does not actually move when the key is pressed, but based on the speed of the game, i guess.

like image 44
Andy Avatar answered Nov 10 '22 09:11

Andy