-
Notifications
You must be signed in to change notification settings - Fork 0
/
Listing_18-2.py
executable file
·47 lines (40 loc) · 2.68 KB
/
Listing_18-2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Listing_18-2.py
# Copyright Warren Sande, 2009
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version 61 ----------------------------
# Bouncing ball with up and down arrow keys
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
background = pygame.Surface(screen.get_size())
background.fill([255, 255, 255])
clock = pygame.time.Clock()
class Ball(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed
def move(self):
if self.rect.left <= screen.get_rect().left or \
self.rect.right >= screen.get_rect().right:
self.speed[0] = - self.speed[0]
newpos = self.rect.move(self.speed)
self.rect = newpos
my_ball = Ball('beach_ball.png', [10,0], [20, 20])
screen.blit(my_ball.image, my_ball.rect)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
my_ball.rect.top = my_ball.rect.top - 10
elif event.key == pygame.K_DOWN:
my_ball.rect.top = my_ball.rect.top + 10
clock.tick(30)
screen.blit(background, (0, 0))
my_ball.move()
screen.blit(my_ball.image, my_ball.rect)
pygame.display.flip()