Pages

duminică, 28 ianuarie 2018

PyGame : Test with an animated image.

This is a simple tutorial about how to create a bouncing ball effect with pygame python module.
The source code is very simple and you need a transparent image named earth.png .
The variables I used is size, speed, ball, ballrect.
I used ballrect with  get_rect().
The result get pygame Rect object.
This  has several virtual attributes which can be used to move and align the Rect:

  • x,y
  • top, left, bottom, right
  • topleft, bottomleft, topright, bottomright
  • midtop, midleft, midbottom, midright
  • center, centerx, centery
  • size, width, height
  • w,h

All of these attributes can be assigned to ballrect variable.
import sys
import pygame
pygame.init()
 
size = width, height = 640, 420
speed = [1, 1]
black = 0, 0, 0
 
screen = pygame.display.set_mode(size)
 
ball = pygame.image.load("earth.png")
ballrect = ball.get_rect()
 
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
 
    ballrect = ballrect.move(speed)
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]
 
    screen.fill(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()

pygame.display.update()
The result of this source code :