Docsity

Python program to create a bouncing blue dot within a red square using Pygame, Ejercicios de Programación Informática

Toggle sidebar
bg1
Python program to create a bouncing blue dot
within a red square using Pygame
Here is the Python code to create a blue dot that bounces within the walls of
a red square using the Pygame library:
import pygame
# Initialize Pygame
pygame.init()
# Define the screen dimensions
width = 500
height = 500
screen = pygame.display.set_mode((width, height))
# Define the colors
blue = (0, 0, 255)
red = (255, 0, 0)
# Define the coordinates and velocity of the dot
x = 50
y = 50
vel_x = 5
vel_y = 5
# Define the size and position of the square
square_size = 100
square_x = (width - square_size) / 2
square_y = (height - square_size) / 2
# Main game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move the dot
x += vel_x
y += vel_y
# Bounce within the square
if x < square_x:
pf2

Vista previa parcial del texto

¡Descarga Python program to create a bouncing blue dot within a red square using Pygame y más Ejercicios en PDF de Programación Informática solo en Docsity!

Python program to create a bouncing blue dot

within a red square using Pygame

Here is the Python code to create a blue dot that bounces within the walls of a red square using the Pygame library: import pygame

Initialize Pygame

pygame.init()

Define the screen dimensions

width = 500 height = 500 screen = pygame.display.set_mode((width, height))

Define the colors

blue = (0, 0, 255) red = (255, 0, 0)

Define the coordinates and velocity of the dot

x = 50 y = 50 vel_x = 5 vel_y = 5

Define the size and position of the square

square_size = 100 square_x = (width - square_size) / 2 square_y = (height - square_size) / 2

Main game loop

running = True while running:

Handle events

for event in pygame.event.get(): if event.type == pygame.QUIT: running = False

Move the dot

x += vel_x y += vel_y

Bounce within the square

if x < square_x:

x = square_x vel_x = -vel_x elif x > square_x + square_size: x = square_x + square_size vel_x = -vel_x if y < square_y: y = square_y vel_y = -vel_y elif y > square_y + square_size: y = square_y + square_size vel_y = -vel_y

Draw the background and square

screen.fill((255, 255, 255)) pygame.draw.rect(screen, red, (square_x, square_y, square_size, square_size))

Draw the dot

pygame.draw.circle(screen, blue, (x, y), 10)

Update the screen

pygame.display.flip()

Quit Pygame

pygame.quit() This program uses a main loop that runs until the user closes the game window. Within the loop, Pygame events are handled, the dot is moved, and everything is drawn on the screen. The dot bounces within the square using a series of conditional checks. Finally, the screen is updated with pygame.display.flip() and Pygame is exited at the end of the program with pygame.quit().