-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest.lua
More file actions
98 lines (70 loc) · 2.16 KB
/
Test.lua
File metadata and controls
98 lines (70 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
function CalcRandomPos()
return Vector2i:new(math.random(0, world_size.x - 1), math.random(0, world_size.y - 1))
end
function NewGame()
snake = { { color=Colour.DarkGreen, pos=CalcRandomPos() } }
apple = CalcRandomPos()
snake_dir = Vector2i:new(1, 0)
counter = 0.0
delay = 0.15
score = 0
is_dead = false
end
function OnCreate()
math.randomseed(os.time())
tile_size = Vector2i:new(8, 8)
world_size = Dge:GetScreenSize() // tile_size
NewGame()
return true
end
function RandomPixel()
return Pixel:new(math.random(0, 255), math.random(0, 255), math.random(0, 255), 255)
end
function OnUpdate(dt)
if is_dead then
if Dge:GetKey(Key.Space).pressed then NewGame() end
Dge:DrawString(1, Dge:ScreenHeight() // 2, "Game over! Press SPACE to play again.", Colour.Yellow, 1, 1)
return true
end
if Dge:GetKey(Key.Left).pressed then snake_dir = Vector2i:new(-1, 0) end
if Dge:GetKey(Key.Right).pressed then snake_dir = Vector2i:new(1, 0) end
if Dge:GetKey(Key.Up).pressed then snake_dir = Vector2i:new(0, -1) end
if Dge:GetKey(Key.Down).pressed then snake_dir = Vector2i:new(0, 1) end
if counter > delay then
counter = 0.0
table.insert(snake, 1, { color = RandomPixel(), pos = snake[1].pos + snake_dir })
if snake[1].pos == apple then
score = score + 1
if score % 5 == 0 then
delay = delay - 0.001
end
apple = CalcRandomPos()
snake[#snake + 1] = snake[#snake]
end
for i=2, #snake do
snake[i].color = RandomPixel()
if snake[i].pos == snake[1].pos then
is_dead = true
end
end
if snake[1].pos.x < 0 or snake[1].pos.y < 0 or snake[1].pos.x >= world_size.x or snake[1].pos.y >= world_size.y then
is_dead = true
end
table.remove(snake, #snake)
end
counter = counter + dt
Dge:Clear(Pixel:new(32, 32, 32, 255))
Dge:DrawString(2, 2, "Score: " .. score, Colour.Yellow, 1, 1)
for k, v in pairs(snake) do
Dge:FillRectangle(tile_size * v.pos, tile_size, v.color)
end
Dge:FillRectangle(tile_size * apple, tile_size, Colour.Red)
return true
end
function CreateApp()
return
{
size = { 256, 240, 4, 4 },
title = "Snake"
}
end