Problem Solving and Python Programming: Laboratory Programs

Laboratory Python Programs Set 3

Problem Solving and Python Programming

Engineering Python : UNIT V : Files, Modules, Packages : Experiment and Solution

Experiment 12 : Developing a game activity using Pygame like bouncing ball, car race etc.

Solution :  Python program for bouncing ball :

import pygame

# Define color for Screen

WHITE = (255, 255, 255) #

Define color for ball

RED = (255, 0, 0)

pygame.init()

 

# Set the height and width of the screen

size = [600, 400]

screen = pygame.display.set_mode(size)

 

pygame.display.set_caption("BOUNCING BALL DEMO")

 

# Loop until the user clicks the close button.

finish = False

 

# Used to manage how fast the screen updates

clock = pygame.time.Clock()

 

# Starting position

x = 50

y = 50

 

# Change in Speed and direction of ball by following units

change_x = 5

change_y = 5

radius = 50

# Main Program Loop

while not finish:

# --- Event Processing

for event in pygame.event.get():

if event.type == pygame. QUIT: #if user clicks close button

finish = True

 

# Move the ball to starting point

x += change_x

y += change_y

 

# Bounce the ball if needed

if y > = 350 or y < = 0:

change_y = change_y * - 1

if x >= 550 or x < = 0:

change_x = change_x * -1

 

# Set the screen background

screen.fill(WHITE)

 

# Draw the ball

pygame.draw.circle(screen, RED, (x+10, y+10), radius)

 

#Time per frame

clock.tick(60)

 

# Update the screen with whatever is the current position

pygame.display.flip()

 

# Finally close everything down

pygame.quit()

Output


 

Problem Solving and Python Programming: Laboratory Programs : Tag: Engineering Python : Problem Solving and Python Programming - Laboratory Python Programs Set 3