Skip to content

Commit cba055e

Browse files
committed
fea: enable teleport snake
1 parent fb23bb8 commit cba055e

File tree

1 file changed

+25
-9
lines changed

1 file changed

+25
-9
lines changed

lua/snake/snake.lua

+25-9
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ function Snake:new()
1818
self.queue = { initial_position }
1919
self.movements_queue = {}
2020
self.direction = "r" -- u d l r
21-
self.size = 3 -- snake size
21+
self.size = 3 -- snake size
2222

2323
for _ = 1, self.size do
2424
self:move()
@@ -61,10 +61,10 @@ function Snake:change_dir(dir)
6161
local last_dir = self.movements_queue[#self.movements_queue] or self.direction
6262

6363
if
64-
(new_dir == "l" and last_dir == "r")
65-
or (new_dir == "r" and last_dir == "l")
66-
or (new_dir == "u" and last_dir == "d")
67-
or (new_dir == "d" and last_dir == "u")
64+
(new_dir == "l" and last_dir == "r")
65+
or (new_dir == "r" and last_dir == "l")
66+
or (new_dir == "u" and last_dir == "d")
67+
or (new_dir == "d" and last_dir == "u")
6868
then
6969
return
7070
end
@@ -73,13 +73,29 @@ function Snake:change_dir(dir)
7373
end
7474

7575
function Snake:board_colision_check(height, width)
76+
local enable_colision = self.size > 1 -- dosable colision
77+
7678
for _, pos in ipairs(self.queue) do
77-
if pos.x <= 0 or pos.x > width then
78-
return true
79+
if not enable_colision then
80+
-- if coliding with wall, game over
81+
if pos.x <= 0 or pos.x > width then
82+
return true
83+
end
84+
85+
if pos.y <= 0 or pos.y > height then
86+
return true
87+
end
7988
end
8089

81-
if pos.y <= 0 or pos.y > height then
82-
return true
90+
-- teleport to the other wall
91+
pos.x = pos.x % width
92+
if pos.x == 0 then
93+
pos.x = width
94+
end
95+
96+
pos.y = pos.y % height
97+
if pos.y == 0 then
98+
pos.y = height
8399
end
84100
end
85101

0 commit comments

Comments
 (0)