JavaScript
x
34
34
1
import sys, pygame
2
import random
3
pygame.init()
4
5
x=0.5
6
speed = [x, x]
7
size = width, height = 800, 600
8
black = 0, 0, 0
9
10
screen = pygame.display.set_mode(size)
11
12
ball = pygame.image.load("intro_ball.gif")
13
ballrect = ball.get_rect()
14
15
Sair = True
16
17
while Sair:
18
19
for event in pygame.event.get():
20
if event.type == pygame.QUIT: Sair=False
21
ballrect = ballrect.move(speed)
22
if ballrect.left < 0 or ballrect.right > width:
23
speed[0] = -speed[0]
24
x=random.uniform(0, 1)
25
if ballrect.top < 0 or ballrect.bottom > height:
26
speed[1] = -speed[1]
27
x=random.uniform(0, 1)
28
29
screen.fill(black)
30
screen.blit(ball, ballrect)
31
pygame.display.flip()
32
33
sys.exit()
34
I expected the ball to move and every time it hits the corner change velocity.
Advertisement
Answer
To make the ball move, you’ve to use a variable for position wich can store floating point coordinates. The position is changed every frame depending on the speed. Finally the ball rectangle has to be updated with the position:
JavaScript
1
22
22
1
pos = [0, 0]
2
while Sair:
3
4
for event in pygame.event.get():
5
if event.type == pygame.QUIT: Sair=False
6
7
if ballrect.left < 0 or ballrect.right > width:
8
x = random.uniform(0.1, 1)
9
speed[0] = x if speed[0] < 0.0 else -x
10
11
if ballrect.top < 0 or ballrect.bottom > height:
12
x = random.uniform(0.1, 1)
13
speed[1] = x if speed[1] < 0.0 else -x
14
15
pos[0] += speed[0]
16
pos[1] += speed[1]
17
ballrect.topleft = (int(pos[0]), int(pos[1]))
18
19
screen.fill(black)
20
screen.blit(ball, ballrect)
21
pygame.display.flip()
22
Note, the coordinates of pygame.Rect
are integral values. If a positive floating point value which is less that 1 is added to an integral value, then the value doesn’t change at all, because the result is truncated to to the integral part again.
JavaScript
1
3
1
int a = 1
2
a + 0.5 == 1
3
Ensure that the random velocity is always greater than 0.0. Generate a random velocity and change the speed
dependent on the new direction:
e.g.
JavaScript
1
3
1
x = random.uniform(0.1, 1)
2
speed[0] = x if speed[0] < 0.0 else -x
3