-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.lua
103 lines (85 loc) · 2.57 KB
/
script.lua
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
99
100
101
102
103
local result = get("result")
local width = 40
local height = 20
local snake = {{10, 10}, {10, 9}, {10, 8}}
local direction = {0, 1}
local food = {5, 5}
local function clear_screen()
result.set_content("")
end
function sleep (a)
local sec = tonumber(os.clock() + a);
while (os.clock() < sec) do
end
end
local function print_board()
clear_screen()
for y = 0, height - 1 do
for x = 0, width - 1 do
local is_snake = false
for _, segment in ipairs(snake) do
if segment[1] == y and segment[2] == x then
is_snake = true
break
end
end
if is_snake then
result.set_content(result.get_content() .. "#")
elseif y == food[1] and x == food[2] then
result.set_content(result.get_content() .. "*")
else
result.set_content(result.get_content() .. " ")
end
end
result.set_content(result.get_content() .."\n")
end
end
local function update_snake()
local new_head = {snake[1][1] + direction[1], snake[1][2] + direction[2]}
if new_head[1] < 0 or new_head[1] >= height or new_head[2] < 0 or new_head[2] >= width then
result.set_content(result.get_content() .. "Game Over!\n")
os.exit()
end
for _, segment in ipairs(snake) do
if segment[1] == new_head[1] and segment[2] == new_head[2] then
result.set_content(result.get_content() .. "Game Over!!\n")
os.exit()
end
end
table.insert(snake, 1, new_head)
if new_head[1] == food[1] and new_head[2] == food[2] then
food = {math.random(height) - 1, math.random(width) - 1}
else
table.remove(snake)
end
end
local function change_direction(key)
if key == 'w' and direction[1] ~= 1 and direction[1] ~= -1 then
direction = {-1,0}
elseif key == 's' and direction[1] ~= 1 and direction[1] ~= -1 then
direction = {1,0}
elseif key =='a' and direction[2] ~= -1 and direction[2] ~= 1 then
direction = {0,-1}
elseif key =='d' and direction[2] ~= -1 and direction[2] ~= 1 then
direction = {0,1}
end
end
local key_to_direction = {
w = {-1, 0},
s = {1, 0},
a = {0, -1},
d = {0, 1}
}
clear_screen()
function snake1()
print(direction)
print_board()
update_snake()
set_timeout(snake1, 5)
end
get("input-key").on_input(function(content)
local key = content:sub(-1, -1):lower()
change_direction(key)
direction = direction
end)
snake1()