Advertisement
DarkblooM

Untitled

Jan 14th, 2025
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.78 KB | None | 0 0
  1. local socket = require "socket"
  2.  
  3. PIXEL_SIZE = 15
  4. SPEED = 0.1
  5. GROWTH_FACTOR = 3
  6.  
  7. function love.load()
  8.   grid = {}
  9.   for y = 1, love.graphics.getHeight() / PIXEL_SIZE do
  10.     for x = 1, love.graphics.getWidth() / PIXEL_SIZE do
  11.       table.insert(grid, 0)
  12.     end
  13.   end
  14.  
  15.   snake = {}
  16.     snake.pos = {y = 0, x = 0}
  17.     snake.length = GROWTH_FACTOR
  18.     snake.path = {}
  19.     snake.facing = nil
  20.  
  21.   last_key = nil
  22. end
  23.  
  24. function love.update(dt)
  25.   table.insert(snake.path, 1, snake.pos)
  26.  
  27.   if #snake.path > snake.length then table.remove(snake.path, #snake.path) end
  28.  
  29.   if last_key == "up" and snake.facing ~= "down" then snake.facing = "up"
  30.   elseif last_key == "down" and snake.facing ~= "up" then snake.facing = "down"
  31.   elseif last_key == "left" and snake.facing ~= "right" then snake.facing = "left"
  32.   elseif last_key == "right" and snake.facing ~= "left" then snake.facing = "right" end
  33.  
  34.   if snake.facing == "up" then snake.pos.y = snake.pos.y - 1
  35.   elseif snake.facing == "down" then snake.pos.y = snake.pos.y + 1
  36.   elseif snake.facing == "left" then snake.pos.x = snake.pos.x - 1
  37.   elseif snake.facing == "right" then snake.pos.x = snake.pos.x + 1 end
  38.  
  39.   socket.sleep(SPEED)
  40. end
  41.  
  42. function love.draw()
  43.   love.graphics.setColor(0, 0, 0, 1)
  44.   love.graphics.rectangle("fill", 0, 0, love.graphics.getWidth(), love.graphics.getHeight())
  45.  
  46.   love.graphics.setColor(255, 255, 255, 1)
  47.   love.graphics.rectangle("fill", snake.pos.x * PIXEL_SIZE, snake.pos.y * PIXEL_SIZE, PIXEL_SIZE, PIXEL_SIZE)
  48.  
  49.   for i = 1, #snake.path do
  50.     love.graphics.rectangle("fill", snake.path[i].x * PIXEL_SIZE, snake.path[i].y * PIXEL_SIZE, PIXEL_SIZE, PIXEL_SIZE)
  51.   end
  52. end
  53.  
  54. function love.keypressed(key, scancode, isrepeat)
  55.   if scancode == "escape" then love.event.quit() end
  56.   last_key = scancode
  57. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement