diff options
author | Dmitrii Ubskii <ubskydm@gmail.com> | 2021-05-16 22:19:49 +0300 |
---|---|---|
committer | Linus Groh <mail@linusgroh.de> | 2021-05-18 18:58:07 +0100 |
commit | bb76bcde57f65d6684353bd072867bfd15906e8c (patch) | |
tree | ac839e021bda9935721c23658a196a4622f94068 /Userland | |
parent | 7c67c9b45f68e1337a21a97a76468943d5680cec (diff) | |
download | serenity-bb76bcde57f65d6684353bd072867bfd15906e8c.zip |
Pong: Improve AI paddle movement
Begin and end triggers for AI paddle to start moving prevent it from
continually jerking around the ball's position. It still moves in steps
of paddle.speed though, but overall experience is smoother.
Diffstat (limited to 'Userland')
-rw-r--r-- | Userland/Games/Pong/Game.cpp | 34 |
1 files changed, 24 insertions, 10 deletions
diff --git a/Userland/Games/Pong/Game.cpp b/Userland/Games/Pong/Game.cpp index 4fd689a482..057545103d 100644 --- a/Userland/Games/Pong/Game.cpp +++ b/Userland/Games/Pong/Game.cpp @@ -141,18 +141,32 @@ void Game::round_over(int winner) void Game::calculate_move() { - if ((m_ball.y() + m_ball.radius) < (m_player2_paddle.rect.y() + (m_player2_paddle.rect.height() / 2))) { - m_player2_paddle.moving_up = true; - m_player2_paddle.moving_down = false; - return; + int player_2_paddle_top = m_player2_paddle.rect.top(); + int player_2_paddle_bottom = m_player2_paddle.rect.bottom(); + + int ball_position = m_ball.y() + m_ball.radius; + + // AI paddle begins moving when the ball crosses the begin_trigger, + // but stops only if it crosses the end_trigger. end_trigger forces + // overcorrection, so that the paddle moves more smoothly. + int begin_trigger = m_player2_paddle.rect.height() / 4; + int end_trigger = m_player2_paddle.rect.height() / 2; + + if (m_player2_paddle.moving_up) { + if (player_2_paddle_top + end_trigger < ball_position) + m_player2_paddle.moving_up = false; + } else { + if (player_2_paddle_top + begin_trigger > ball_position) + m_player2_paddle.moving_up = true; } - if ((m_ball.y() + m_ball.radius) > (m_player2_paddle.rect.y() + (m_player2_paddle.rect.height() / 2))) { - m_player2_paddle.moving_up = false; - m_player2_paddle.moving_down = true; - return; + + if (m_player2_paddle.moving_down) { + if (player_2_paddle_bottom - end_trigger > ball_position) + m_player2_paddle.moving_down = false; + } else { + if (player_2_paddle_bottom - begin_trigger < ball_position) + m_player2_paddle.moving_down = true; } - m_player2_paddle.moving_up = false; - m_player2_paddle.moving_down = false; } void Game::tick() |