From f129d97f9797513d270a095ed7e8229b8a796f12 Mon Sep 17 00:00:00 2001 From: me Date: Tue, 29 Apr 2025 09:04:41 +0300 Subject: [PATCH] lua moving ball --- lua-moving-ball/main.lua | 100 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 lua-moving-ball/main.lua diff --git a/lua-moving-ball/main.lua b/lua-moving-ball/main.lua new file mode 100644 index 0000000..3947f1b --- /dev/null +++ b/lua-moving-ball/main.lua @@ -0,0 +1,100 @@ +-- Gist accompanying https://alloca.space/blog/lua-lang.html +-- +-- Build and Run +-- ------------- +-- +-- 1. Install https://love2d.org on your system +-- +-- 2. Run with: +-- +-- love . + + +-- Constants + +SCREEN_WIDTH = 640 +SCREEN_HEIGHT = 480 +BALL_SPEED = 200 +BALL_RADIUS = 50 + +-- Objects + +local background = { + ["color"] = { + ["r"] = 0x08 / 255, + ["g"] = 0x18 / 255, + ["b"] = 0x29 / 255, + } +} + +local ball = { + position = { + ["x"] = SCREEN_WIDTH/3, + ["y"] = SCREEN_HEIGHT/3, + }, + direction = { + ["x"] = 1, + ["y"] = 1, + }, + color = { + ["r"] = 0xf9 / 255, + ["g"] = 0x92 / 255, + ["b"] = 0x26 / 255, + }, + ["radius"] = BALL_RADIUS, +} + +-- Main + +function love.load() + love.window.setMode(SCREEN_WIDTH, SCREEN_HEIGHT, {vsync=true,msaa=4}) +end + +function love.update() + updateBall(ball) +end + +function love.draw() + love.graphics.clear(background.color.r, background.color.g, background.color.b, 255, true, true) + + love.graphics.setColor(ball.color.r, ball.color.g, ball.color.b) + love.graphics.circle("fill", ball.position.x, ball.position.y, ball.radius) +end + +-- Update + +function updateBall(ball) + applyKeys(ball) + swingBall(ball) +end + +function applyKeys(ball) + if love.keyboard.isDown("d") then ball.direction.x = 1 end + if love.keyboard.isDown("a") then ball.direction.x = -1 end + if love.keyboard.isDown("s") then ball.direction.y = 1 end + if love.keyboard.isDown("w") then ball.direction.y = -1 end +end + +function swingBall(ball) + local p, d = swing(ball.position.x, ball.direction.x, 0 + ball.radius, SCREEN_WIDTH - ball.radius) + ball.position.x = p + ball.direction.x = d + + local p, d = swing(ball.position.y, ball.direction.y, 0 + ball.radius, SCREEN_HEIGHT - ball.radius) + ball.position.y = p + ball.direction.y = d +end + +function swing(position, direction, min, max) + if (position <= min) then + position = min + direction = 1 + elseif (position >= max) then + position = max + direction = -1 + end + + local dt = love.timer.getDelta() + position = position + (direction * BALL_SPEED * dt) + return position, direction +end