Bouncing Ball Explanation
Bouncing Ball Explanation
1. Importing the library
- This imports the
pygame
library, 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
pygame
that 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
pygame
are 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_x
andball_y
: Initial position of the ball (100, 100).ball_dx
andball_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
while
loop keeps the game running untilrunning
is 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_dx
toball_x
andball_dy
toball_y
. - This creates movement.
9. Bouncing off walls
- Checks if the ball hits the left or right edge (
ball_x - ball_radius < 0
orball_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 < 0
orball_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
WHITE
to 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
pygame
modules cleanly after the game loop ends.
Comments
Post a Comment