Friday, March 15, 2019

Adding a Paddle to Bouncing Ball

In the previous post we created the Bouncing Ball example. We will be adding a paddle to the Bouncing Ball example here, so that we can make it a bit interactive to play with. I have changed the title from Bouncing Ball to Paddle Ball. I have also changed the screen size to have more room to play. The images for the icon, ball and the paddle are given below the code. You can download them and put them in the same folder where you save the code.

Code:

import sys, pygame
pygame.init()
# Screen and Window setup
screen_size = screen_width, screen_height = 600, 600
logo = pygame.image.load("logo32x32.png")
pygame.display.set_icon(logo)
pygame.display.set_caption("Paddle Ball")
screen = pygame.display.set_mode(screen_size)
black = (0, 0, 0)
# Ball setup
ball = pygame.image.load("ball.png")
ball_rect = ball.get_rect()
ball_rect = ball_rect.move(290, 550)
ball_speed = [1, 1]
# Paddle setup
paddle = pygame.image.load("paddle.png")
paddle_rect = paddle.get_rect()
paddle_rect = paddle_rect.move(225, 570)
paddle_speed = 1
# Game Loop
while True:
# Exit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Ball update
ball_rect = ball_rect.move(ball_speed)
if ball_rect.left < 0 or ball_rect.right > screen_width:
ball_speed[0] = -ball_speed[0]
if ball_rect.top < 0 or ball_rect.bottom > screen_height:
ball_speed[1] = -ball_speed[1]
# Paddle update
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
paddle_rect = paddle_rect.move([-paddle_speed, 0])
if keys[pygame.K_RIGHT]:
paddle_rect = paddle_rect.move([paddle_speed, 0])
# Collision with paddle
if paddle_rect.colliderect(ball_rect):
ball_speed[1] = -ball_speed[1]
# Screen update
screen.fill(black)
screen.blit(ball, ball_rect)
screen.blit(paddle, paddle_rect)
pygame.display.flip()
view raw PaddleBall.py hosted with ❤ by GitHub

Graphic for the icon:


Graphic for the ball:


Graphic for the paddle:


Output:


No comments: