Untitled

 avatar
unknown
plain_text
3 months ago
1.3 kB
5
Indexable
import pygame

# Initialize pygame
pygame.init()

# Set up display
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Ball Bouncing")

# Define ball properties
ball_radius = 20
ball_color = (255, 0, 0)  # Red color
x, y = width // 2, height // 2  # Initial position of the ball
dx, dy = 0, 0  # Initially no movement
ball_moving = False  # Ball is not moving yet

# Game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # Start ball movement when spacebar is pressed
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                ball_moving = True  # Ball starts moving

    # If the ball is moving, update its position
    if ball_moving:
        x += dx
        y += dy

        # Bounce off the left and right walls
        if x - ball_radius <= 0 or x + ball_radius >= width:
            dx = -dx  # Reverse direction on the x-axis

    # Fill screen with black
    screen.fill((0, 0, 0))

    # Draw the ball
    pygame.draw.circle(screen, ball_color, (x, y), ball_radius)

    # Update the screen
    pygame.display.update()

    # Set the frame rate
    pygame.time.Clock().tick(60)

# Quit pygame
pygame.quit()

Editor is loading...
Leave a Comment