gpt4 book ai didi

python - 如何在Pygame中放入随机数

转载 作者:太空宇宙 更新时间:2023-11-04 00:00:24 26 4
gpt4 key购买 nike

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()

我预计球会移动,并且每次它碰到角落都会改变速度。

最佳答案

要使球移动,您必须使用可以存储浮点坐标的位置变量。根据速度,每帧都会更改位置。最后球矩形必须用位置更新:

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()

注意,坐标pygame.Rect是整数值。如果将小于 1 的正浮点值添加到整数值,则该值根本不会改变,因为结果会再次被截断为整数部分。

int a = 1
a + 0.5 == 1

确保随机速度始终大于 0.0。生成随机速度并根据新方向更改 speed:

例如

x = random.uniform(0.1, 1)
speed[0] = x if speed[0] < 0.0 else -x

关于python - 如何在Pygame中放入随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55883986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com