pocketlang/tests/examples/snake.pk

125 lines
2.0 KiB
Plaintext
Raw Permalink Normal View History

2022-05-27 20:50:46 +08:00
2022-05-28 17:31:17 +08:00
import term, math
2022-05-27 20:50:46 +08:00
from types import Vector
## This is a pocketlang implementation of:
## https://www.youtube.com/watch?v=xGmXxpIj6vs&t=279s&ab_channel=ChrisDeLeonofHomeTeamGameDev
## x, y velocity of snake.
vx = 0; vy = 0
## position (at the middle).
px = 0; py = 0
## tile size.
tx = 0; ty = 0
## apple position.
ax = 15; ay = 15
## tail, trail
trail = []
tail = 15
## score
score = 0
def init()
2022-05-28 17:31:17 +08:00
size = term.getsize()
2022-05-27 20:50:46 +08:00
tx = size.x
ty = size.y
px = tx / 2; py = ty / 2
end
def frame()
px += vx
py += vy
if px < 0 then px = tx - 1 end
if px > tx - 1 then px = 0 end
if py < 0 then py = ty - 1 end
if py > ty - 1 then py = 0 end
2022-05-28 17:31:17 +08:00
term.clear()
term.write('press Q to quit | score = $score')
2022-05-27 20:50:46 +08:00
for i in trail
2022-05-28 17:31:17 +08:00
term.setposition(i.x, i.y)
term.start_bg(0, 0xff, 0)
term.write(' ')
term.end_bg()
2022-05-27 20:50:46 +08:00
if i.x == px and i.y == py
tail = 5
end
end
2022-05-28 17:31:17 +08:00
term.setposition(ax, ay)
term.start_bg(0xff, 0, 0)
term.write(' ')
term.end_bg()
2022-05-27 20:50:46 +08:00
trail.append(Vector(px, py))
while trail.length > tail
trail.pop(0)
end
if px == ax and py == ay
tail += 1
score += 1
ax = math.rand() % tx
ay = math.rand() % ty
end
2022-05-28 17:31:17 +08:00
term.flush()
2022-05-27 20:50:46 +08:00
end
def handle(event)
if event.type == term.EVENT_KEY_DOWN
if event.keycode == term.KEY_Q
2022-05-28 17:31:17 +08:00
term.stop()
2022-05-27 20:50:46 +08:00
end
## The "Switch Statement" alternative.
{
term.KEY_LEFT: fn
vx = -1; vy = 0
end,
term.KEY_UP: fn
vx = 0; vy = -1
end,
term.KEY_DOWN: fn
vx = 0; vy = 1
end,
term.KEY_RIGHT: fn
vx = 1; vy = 0
end,
term.KEY_T: fn
math.sin(12)
end,
}.get(event.keycode, fn end)()
end
end
def main()
2022-05-28 17:31:17 +08:00
config = term.Config()
2022-05-27 20:50:46 +08:00
config.capture_events = true
config.hide_cursor = true
config.new_buffer = true
config.fps = 20
config.init_fn = init
config.event_fn = handle
config.frame_fn = frame
2022-05-28 17:31:17 +08:00
term.run(config)
2022-05-27 20:50:46 +08:00
end
main()