Here is simple code to get you started with bouncing a ball against the boundaries of the window. I have used two images, one for the icon of the application and one for the ball. The image files are given under the code for you to download and use with the code. Download the image files and put them in the same folder where you save the code.
Code:
Graphic for the icon:
Graphic for the ball:
Output:
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys, pygame | |
pygame.init() | |
# Screen and Window setup | |
screen_size = screen_width, screen_height = 720, 320 | |
logo = pygame.image.load("logo32x32.png") | |
pygame.display.set_icon(logo) | |
pygame.display.set_caption("Bouncing 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_speed = [1, 1] | |
# Game Loop | |
while True: | |
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] | |
# Screen update | |
screen.fill(black) | |
screen.blit(ball, ball_rect) | |
pygame.display.flip() |
Graphic for the icon:
Graphic for the ball:
Output:
No comments:
Post a Comment