Small Steps II — Making Things
Combining what you learned into a small game
Combine what you learned into a small game.
What you will learn
A game receives input, changes its state, and draws that state. This lesson is an assembly activity rather than new syntax.
Try it
void small_main()
{
Window window;
window.set_title("Mini Pong");
window.open(800, 500);
double paddle_y = 210;
double ball_x = 400;
double ball_y = 250;
double ball_vx = 260;
double ball_vy = 180;
StopWatch watch;
while (window.is_open())
{
double dt = watch.elapsed();
watch.reset();
if (window.key_down(Key::Up))
paddle_y = paddle_y - 300 * dt;
if (window.key_down(Key::Down))
paddle_y = paddle_y + 300 * dt;
ball_x = ball_x + ball_vx * dt;
ball_y = ball_y + ball_vy * dt;
if (ball_y < 10)
{
ball_y = 10;
ball_vy = -ball_vy;
}
if (ball_y > 490)
{
ball_y = 490;
ball_vy = -ball_vy;
}
if (ball_x < 50 && ball_x > 30 &&
ball_y > paddle_y && ball_y < paddle_y + 80)
{
ball_x = 50;
ball_vx = -ball_vx;
play_sound(Sound::Hit);
}
if (ball_x > 790)
{
ball_x = 790;
ball_vx = -ball_vx;
}
if (ball_x < 0)
{
ball_x = 400;
ball_y = 250;
ball_vx = 260;
play_sound(Sound::Lose);
}
window.clear(Black);
window.fill_rectangle(30, paddle_y, 15, 80, White);
window.fill_circle(ball_x, ball_y, 10, Yellow);
window.show();
}
}
Run the example and move the paddle with the up and down arrow keys. The code reads time and input, updates positions, handles collisions, then draws.
A collision check asks whether objects touch. After crossing a wall, the program corrects the position to the boundary as well as reversing direction. Start by finding the paddle movement instead of changing everything at once.
Exercise
The starter isolates paddle movement from the first Pong example. Add code to keep paddle_y between 0 and 420. The entire paddle must stay inside the window even when an arrow key is held. You can also transfer the tested limit code to the first Pong example.
void small_main()
{
Window window;
window.open(800, 500);
double paddle_y = 210;
StopWatch watch;
while (window.is_open())
{
double dt = watch.elapsed();
watch.reset();
if (window.key_down(Key::Up))
paddle_y = paddle_y - 300 * dt;
if (window.key_down(Key::Down))
paddle_y = paddle_y + 300 * dt;
// Keep paddle_y between 0 and 420.
window.clear(Black);
window.fill_rectangle(30, paddle_y, 15, 80, White);
window.show();
}
}
Hint
After updating paddle_y from input, use two if statements to keep it within 0 and 420.
show solution
void small_main()
{
Window window;
window.open(800, 500);
double paddle_y = 210;
StopWatch watch;
while (window.is_open())
{
double dt = watch.elapsed();
watch.reset();
if (window.key_down(Key::Up))
paddle_y = paddle_y - 300 * dt;
if (window.key_down(Key::Down))
paddle_y = paddle_y + 300 * dt;
if (paddle_y < 0) paddle_y = 0;
if (paddle_y > 420) paddle_y = 420;
window.clear(Black);
window.fill_rectangle(30, paddle_y, 15, 80, White);
window.show();
}
}