Skip to content
Advertisement

How to put random numbers in Pygame

import sys, pygame
import random
pygame.init()

x=0.5
speed = [x, x]
size = width, height = 800, 600
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load("intro_ball.gif")
ballrect = ball.get_rect()

Sair = True

while Sair:

    for event in pygame.event.get():
        if event.type == pygame.QUIT: Sair=False
    ballrect = ballrect.move(speed)
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
        x=random.uniform(0, 1)
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]
        x=random.uniform(0, 1)

    screen.fill(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()

sys.exit()

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:

pos = [0, 0]
while Sair:

    for event in pygame.event.get():
        if event.type == pygame.QUIT: Sair=False

    if ballrect.left < 0 or ballrect.right > width:
        x = random.uniform(0.1, 1)
        speed[0] = x if speed[0] < 0.0 else -x 

    if ballrect.top < 0 or ballrect.bottom > height:
        x = random.uniform(0.1, 1)
        speed[1] = x if speed[1] < 0.0 else -x  

    pos[0] += speed[0]
    pos[1] += speed[1]
    ballrect.topleft = (int(pos[0]), int(pos[1]))

    screen.fill(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()

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.

int a = 1
a + 0.5 == 1

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.

x = random.uniform(0.1, 1)
speed[0] = x if speed[0] < 0.0 else -x 
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement