examples: prevent a 180 turn in snek (#12286)

pull/12294/head weekly.2021.43
Amund Tenstad 2021-10-25 09:57:05 +02:00 committed by GitHub
parent cc2847f6ff
commit 18da724a9f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 8 additions and 4 deletions

View File

@ -55,6 +55,7 @@ mut:
best HighScore best HighScore
snake []Pos snake []Pos
dir Direction dir Direction
last_dir Direction
food Pos food Pos
start_time i64 start_time i64
last_tick i64 last_tick i64
@ -70,6 +71,7 @@ fn (mut app App) reset_game() {
Pos{0, 8}, Pos{0, 8},
] ]
app.dir = .right app.dir = .right
app.last_dir = app.dir
app.food = Pos{10, 8} app.food = Pos{10, 8}
app.start_time = time.ticks() app.start_time = time.ticks()
app.last_tick = time.ticks() app.last_tick = time.ticks()
@ -91,22 +93,22 @@ fn (mut app App) move_food() {
fn on_keydown(key gg.KeyCode, mod gg.Modifier, mut app App) { fn on_keydown(key gg.KeyCode, mod gg.Modifier, mut app App) {
match key { match key {
.w, .up { .w, .up {
if app.dir != .down { if app.last_dir != .down {
app.dir = .up app.dir = .up
} }
} }
.s, .down { .s, .down {
if app.dir != .up { if app.last_dir != .up {
app.dir = .down app.dir = .down
} }
} }
.a, .left { .a, .left {
if app.dir != .right { if app.last_dir != .right {
app.dir = .left app.dir = .left
} }
} }
.d, .right { .d, .right {
if app.dir != .left { if app.last_dir != .left {
app.dir = .right app.dir = .right
} }
} }
@ -150,6 +152,8 @@ fn on_frame(mut app App) {
} }
app.snake << app.snake.last() + app.snake.last() - app.snake[app.snake.len - 2] app.snake << app.snake.last() + app.snake.last() - app.snake[app.snake.len - 2]
} }
app.last_dir = app.dir
} }
// drawing snake // drawing snake
for pos in app.snake { for pos in app.snake {