Skip to content

Commit 18da724

Browse files
authored
examples: prevent a 180 turn in snek (#12286)
1 parent cc2847f commit 18da724

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

examples/snek/snek.v

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ mut:
5555
best HighScore
5656
snake []Pos
5757
dir Direction
58+
last_dir Direction
5859
food Pos
5960
start_time i64
6061
last_tick i64
@@ -70,6 +71,7 @@ fn (mut app App) reset_game() {
7071
Pos{0, 8},
7172
]
7273
app.dir = .right
74+
app.last_dir = app.dir
7375
app.food = Pos{10, 8}
7476
app.start_time = time.ticks()
7577
app.last_tick = time.ticks()
@@ -91,22 +93,22 @@ fn (mut app App) move_food() {
9193
fn on_keydown(key gg.KeyCode, mod gg.Modifier, mut app App) {
9294
match key {
9395
.w, .up {
94-
if app.dir != .down {
96+
if app.last_dir != .down {
9597
app.dir = .up
9698
}
9799
}
98100
.s, .down {
99-
if app.dir != .up {
101+
if app.last_dir != .up {
100102
app.dir = .down
101103
}
102104
}
103105
.a, .left {
104-
if app.dir != .right {
106+
if app.last_dir != .right {
105107
app.dir = .left
106108
}
107109
}
108110
.d, .right {
109-
if app.dir != .left {
111+
if app.last_dir != .left {
110112
app.dir = .right
111113
}
112114
}
@@ -150,6 +152,8 @@ fn on_frame(mut app App) {
150152
}
151153
app.snake << app.snake.last() + app.snake.last() - app.snake[app.snake.len - 2]
152154
}
155+
156+
app.last_dir = app.dir
153157
}
154158
// drawing snake
155159
for pos in app.snake {

0 commit comments

Comments
 (0)