Bouncing Ball Explanation
Bouncing Ball Explanation
1. Importing the library
- This imports the
pygamelibrary, which is used for game development in Python. It provides tools for graphics, sound, and user interaction.
2. Initializing Pygame
- This initializes all the modules in
pygamethat are necessary for the game to run, such as display, sound, and input handling.
3. Setting up the display
pygame.display.set_mode((800, 600)): Creates a window with a size of 800 pixels wide and 600 pixels tall.pygame.display.set_caption("Bouncing Ball"): Sets the title of the window to "Bouncing Ball".
4. Defining colors
- Colors in
pygameare defined using RGB values.WHITE: Full intensity of red, green, and blue (255, 255, 255).RED: Full intensity of red, with green and blue at 0 (255, 0, 0).
5. Ball setup
ball_xandball_y: Initial position of the ball (100, 100).ball_dxandball_dy: Change in position (speed) of the ball in the x and y directions, respectively.ball_radius: The radius of the ball (20 pixels).
6. Main loop
- The
whileloop keeps the game running untilrunningis set toFalse. running = True: Initially sets the game to be active.
7. Event handling
pygame.event.get(): Retrieves all the events (like mouse clicks, key presses, etc.).- Checks if the event is
pygame.QUIT(when the user clicks the close button), and exits the loop by settingrunning = False.
8. Moving the ball
- Updates the ball's position by adding
ball_dxtoball_xandball_dytoball_y. - This creates movement.
9. Bouncing off walls
- Checks if the ball hits the left or right edge (
ball_x - ball_radius < 0orball_x + ball_radius > 800).- Reverses the direction of movement in the x-axis by negating
ball_dx.
- Reverses the direction of movement in the x-axis by negating
- Checks if the ball hits the top or bottom edge (
ball_y - ball_radius < 0orball_y + ball_radius > 600).- Reverses the direction of movement in the y-axis by negating
ball_dy.
- Reverses the direction of movement in the y-axis by negating
10. Clearing the screen
- Fills the screen with the color
WHITEto clear the previous frame.
11. Drawing the ball
- Draws a circle on the screen.
screen: The surface to draw on.RED: The color of the circle.(ball_x, ball_y): The position of the circle.ball_radius: The radius of the circle.
12. Updating the display
- Updates the display with the new frame.
13. Quitting the game
- Exits all
pygamemodules cleanly after the game loop ends.
Comments
Post a Comment