Esempio n.1
Animazione raffigurante palline che rimbalzano (per provare questo script servono 5 immagini chiamate "ballx.png" dove x è un numero da 0 a 4) (realizzato da gennaro)
1 #!/usr/bin/python
2
3 import sys
4 from random import randint
5 import pygame
6 from pygame.locals import *
7
8 pygame.init()
9
10 class Ball(pygame.sprite.Sprite):
11 def __init__(self):
12 pygame.sprite.Sprite.__init__(self)
13
14 self.image = pygame.image.load("ball%d.png" % randint(0,4))
15 self.image = self.image.convert_alpha()
16
17 self.rect = self.image.get_rect()
18 self.rect = self.rect.move(randint(self.rect.width, 640-self.rect.width),
19 randint(self.rect.height,480-self.rect.height))
20
21 self.x_speed = randint(1,6)
22 self.y_speed = randint(1,6)
23
24 def update(self):
25 width, height = 640, 480
26
27 if self.rect.left < 0 or self.rect.right > width:
28 self.x_speed = -self.x_speed
29
30 if self.rect.top < 0 or self.rect.bottom > height:
31 self.y_speed = -self.y_speed
32
33 self.rect = self.rect.move(self.x_speed, self.y_speed)
34
35
36 screen = pygame.display.set_mode((640,480))
37 background = pygame.image.load("sfondo.png").convert()
38 screen.blit(background,(0,0))
39 pygame.display.update()
40
41 group = pygame.sprite.RenderUpdates([Ball() for x in range(randint(4,10))])
42
43 while True:
44 for event in pygame.event.get():
45 if event.type in (QUIT, KEYDOWN): sys.exit()
46
47 group.clear(screen,background)
48 group.update()
49 pygame.display.update(group.draw(screen))
50
51 pygame.time.delay(25)