Skip to content

A snake game

1
package snake
2
3
import "core:fmt"
4
import rl "vendor:raylib"
5
6
WIN_HEIGHT :: 450
7
WIN_WIDTH :: 800
8
SNAKE_MAXLENGTH :: 100
9
SNAKE_STEP :: 20
10
GAME_TITLE :: "Snake game"
11
12
Vec2i :: struct {
13
x, y: i32,
14
}
15
16
// Define a struct to handle the snake's state
17
Snake :: struct {
18
head: Vec2i,
19
body: [SNAKE_MAXLENGTH]Vec2i,
20
length: int,
21
}
22
23
// Initialize the snake with a starting position and length
24
snake_init :: proc() -> Snake {
25
return Snake{head = Vec2i{0, 0}, length = 1}
26
}
27
28
// Update snake position and handle wrapping around the screen
29
snake_update_position :: proc(snake: ^Snake) {
30
prev_head := snake.head
31
32
if rl.IsKeyDown(.RIGHT) {
33
snake.head.x += SNAKE_STEP
34
if snake.head.x >= WIN_WIDTH {
35
snake.head.x = 0
36
}
37
} else if rl.IsKeyDown(.LEFT) {
38
snake.head.x -= SNAKE_STEP
39
if snake.head.x < 0 {
40
snake.head.x = WIN_WIDTH - SNAKE_STEP
41
}
42
} else if rl.IsKeyDown(.UP) {
43
snake.head.y -= SNAKE_STEP
44
if snake.head.y < 0 {
45
snake.head.y = WIN_HEIGHT - SNAKE_STEP
46
}
47
} else if rl.IsKeyDown(.DOWN) {
48
snake.head.y += SNAKE_STEP
49
if snake.head.y >= WIN_HEIGHT {
50
snake.head.y = 0
51
}
52
}
53
54
// Move body segments, keeping length within SNAKE_MAXLENGTH
55
for i := snake.length - 1; i > 0; i -= 1 {
56
snake.body[i] = snake.body[i - 1]
57
}
58
snake.body[0] = prev_head
59
60
if snake.length < SNAKE_MAXLENGTH {
61
snake.length += 1
62
}
63
}
64
65
// Render the snake on the screen
66
snake_draw :: proc(snake: ^Snake) {
67
for i in 0 ..< snake.length {
68
pos := snake.body[i]
69
color: rl.Color
70
if i == 0 {
71
color = rl.GREEN // Head color
72
} else {
73
color = rl.BLUE // Body color
74
}
75
rl.DrawRectangle(pos.x, pos.y, SNAKE_STEP, SNAKE_STEP, color)
76
}
77
rl.DrawRectangle(snake.head.x, snake.head.y, SNAKE_STEP, SNAKE_STEP, rl.GREEN)
78
}
79
80
81
main :: proc() {
82
rl.InitWindow(WIN_WIDTH, WIN_HEIGHT, GAME_TITLE)
83
defer rl.CloseWindow()
84
rl.SetTargetFPS(60)
85
86
snake := snake_init()
87
88
for !rl.WindowShouldClose() {
89
snake_update_position(&snake)
90
91
rl.BeginDrawing()
92
defer rl.EndDrawing()
93
rl.ClearBackground(rl.BLACK)
94
95
snake_draw(&snake)
96
}
97
}