Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --
- -- Pong
- -- Made by GravityScore
- --
- -- -------- Variables
- local w, h = term.getSize()
- local refresh = 0.15
- local paddle1 = {
- x = 1,
- y = 2,
- height = 5
- }
- local paddle2 = {
- x = w,
- y = 2,
- height = 5
- }
- local ball = {
- x = math.floor(w/2),
- y = math.floor(h/2),
- velx = -1,
- vely = 1,
- update = function(self)
- self.x = self.x + self.velx
- self.y = self.y + self.vely
- end
- }
- -- -------- Utilities
- local function pointOnPaddle(x, y, paddle)
- return x == paddle.x and y >= paddle.y and y <= paddle.y + paddle.height - 1
- end
- local function redraw()
- term.setBackgroundColor(colors.black)
- term.setTextColor(colors.white)
- term.clear()
- term.setBackgroundColor(colors.white)
- term.setCursorPos(ball.x, ball.y)
- write(" ")
- for i = 1, paddle1.height do
- term.setCursorPos(paddle1.x, paddle1.y + i - 1)
- write(" ")
- end for i = 1, paddle2.height do
- term.setCursorPos(paddle2.x, paddle2.y + i - 1)
- write(" ")
- end
- end
- -- -------- Main
- local function main()
- local timerId = os.startTimer(refresh)
- while true do
- local e, but, x, y = os.pullEvent()
- if e == "key" then
- if but == keys.up and paddle2.y > 1 then
- paddle2.y = paddle2.y - 1
- redraw()
- elseif but == keys.down and paddle2.y + paddle1.height <= h then
- paddle2.y = paddle2.y + 1
- redraw()
- elseif but == keys.w and paddle1.y > 1 then
- paddle1.y = paddle1.y - 1
- redraw()
- elseif but == keys.s and paddle1.y + paddle1.height <= h then
- paddle1.y = paddle1.y + 1
- redraw()
- elseif but == keys.q then
- term.setBackgroundColor(colors.black)
- term.setTextColor(colors.white)
- term.clear()
- term.setCursorPos(1, 1)
- return "quit"
- end
- elseif e == "timer" and but == timerId then
- ball.update(ball)
- redraw()
- if ball.x == 2 then
- if pointOnPaddle(ball.x - 1, ball.y, paddle1) then
- ball.velx = 1
- else
- ball.update(ball)
- redraw()
- sleep(2)
- return "game over"
- end
- end if ball.x == w - 1 then
- if pointOnPaddle(ball.x + 1, ball.y, paddle2) then
- ball.velx = -1
- else
- ball.update(ball)
- redraw()
- sleep(1)
- return "game over"
- end
- end
- if ball.y == 1 then ball.vely = 1 end
- if ball.y == h then ball.vely = -1 end
- timerId = os.startTimer(refresh)
- end
- end
- end
- -- Redraw
- redraw()
- -- Play
- local exit = main()
- -- Exit
- term.setBackgroundColor(colors.black)
- term.setTextColor(colors.white)
- term.clear()
- if exit == "game over" then
- term.setCursorPos(3, 3)
- write("Game Over!")
- sleep(2)
- term.clear()
- term.setCursorPos(1, 1)
- elseif exit == "quit" then
- term.setCursorPos(1, 1)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement