yiransheng / rust-snake-wasm

A snake game in rust and webassembly

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Going [wa] while going right very quickly results in death when it shouldn't. same for [sd] when going left.

yiransheng opened this issue · comments

Reported here by: /r/LLBlumire
https://www.reddit.com/r/rust/comments/9u77iv/show_rrust_yet_another_snake_game_in_rust_and/e92ds55/?st=jo3l3ytb&sh=e64c6931

Very interesting bug.

In regular snake game, the snake movement produced in each tick is atomic, from before to after, both head and tail would've been updated and moved (assuming no food consumed). In addition, only input key not opposite to current head direction is allowed.

In this game, this atomic update is broken into two: move head first, then move tail next tick (logic tick, not rendering tick). So something like this happens:

[step 0, no input] state: Eaten | snake: >>>>
[step 1, input: up] state: Consuming | snake: >>>>^ (allowed input, not opposite of >)
[step 2, input: right] state: Eaten | snake: >>>< (allowed input, not opposite of ^)

Immediate death occurs... Test case for this added here: c0cada3

There is a solution in #12, by adding a third state in snake state enum. However, I am not too sure about it yet. still analyzing the problem.

EDIT: fix in #12 is necessary. The assumption of checking opposite direction for valid moves is incorrect. Correct check is if following new direction to be set, disallow if the next block is neck. (A neck is a block that points to head).

Interesting fix 👍