Created
April 24, 2015 13:11
-
-
Save H2CO3/aef4d634bb43cf8fde40 to your computer and use it in GitHub Desktop.
Pong in Sparkling, in 40 minutes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let SDL = dynld("sdl2"); | |
let w = SDL::OpenWindow("Pong", 640, 480); | |
var paddle = { | |
"x": 0, | |
"y": 0, | |
"w": 100, | |
"h": 40 | |
}; | |
var ball = { | |
"x": w.width / 2, | |
"y": w.height / 2, | |
"vx": 2, | |
"vy": 2, | |
"r": 40 | |
}; | |
// game loop | |
let tmr = SDL::StartTimer(0.04); // 1/0.04 FPS | |
w.setFont("LiberationMono-Bold", 32, "normal"); | |
let run = true; | |
while run { | |
var e; | |
while (e = SDL::PollEvent()) != nil { | |
if e.type == "quit" { | |
run = false; | |
} | |
// move paddle | |
if e.type == "keyboard" and e.state { | |
if e.value == "Left" { | |
paddle.x -= 30; | |
} | |
if e.value == "Right" { | |
paddle.x += 30; | |
} | |
} | |
// move ball | |
if e.type == "timer" { | |
if ball.x - ball.r <= 0 or ball.x + ball.r >= w.width { | |
ball.vx *= -1; | |
} | |
if ball.y - ball.r <= 0 or ball.y + ball.r >= w.height { | |
ball.vy *= -1; | |
} | |
ball.x += ball.vx; | |
ball.y += ball.vy; | |
// check if it collided with the paddle | |
if ball.x >= paddle.x and ball.x < paddle.x + paddle.w and ball.y + ball.r >= w.height - paddle.h { | |
// print("collided with paddle"); | |
ball.vy *= -1; | |
} | |
// check if it collided with the bottom wall | |
if ball.y + ball.r >= w.height { | |
run = false; | |
} | |
} | |
} | |
// clear screen | |
w.setColor(0, 0, 0, 1); | |
w.clear(); | |
// draw frame | |
w.setColor(1, 1, 1, 1); | |
w.strokeRect(1, 1, w.width - 2, w.height - 2); | |
// draw paddle | |
w.setColor(0, 1, 0, 1); | |
w.fillRect(paddle.x, w.height - paddle.h, paddle.w, paddle.h); | |
// draw ball | |
w.setColor(1, 0, 1, 1); | |
w.fillEllipse(ball.x, ball.y, ball.r, ball.r); | |
// render | |
w.refresh(); | |
} | |
SDL::StopTimer(tmr); | |
w.setColor(1, 1, 1, 1); | |
let str = w.renderText("Game Over!", true); | |
let sz = w.textSize("Game Over!"); | |
w.renderTexture(str, w.width / 2 - sz.width / 2, w.height / 2 - sz.height / 2); | |
w.refresh(); | |
run = true; | |
while run { | |
var e; | |
while (e = SDL::PollEvent()) != nil { | |
if e.type == "quit" { | |
run = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment