Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6758535
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T13:48:17+00:00 2026-05-26T13:48:17+00:00

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

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T13:48:19+00:00Added an answer on May 26, 2026 at 1:48 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I cannot imagine how this is anything other than a bug, but since I
This is most likely a bug in Mathematica 8.0.1 and maybe other versions too.
This post is about C# and .Net, but some info is valuable for other
Since enumeration uses integers, what other structure can I use to give me enum-like
I want a Python object that will monitor whether other objects have changed since
newbie for clearcase. Since clearcase's config is rather different from other concept in git,
I opened up Business Intelligence Design Studio (BIDS) the other day. Since then my
So I have cloned a project at github and fixed a patch. Since this
I've been battling with this bug for 3 hours. I have checked the build
This bug tricked me into spending 4 hours debugging perfectly functional code last night.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.