不同“速度”的pygame元素

2024-09-29 19:27:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚做了一个太空入侵游戏,东西掉到地上,你必须避免撞车,等等

我成功地创造了两个物体同时落下,但我不能让他们以不同的速度这样做。你知道吗

这是第一个对象的属性。你知道吗

thing_startx = random.randrange(0, display_width-100)
thing_starty = -700
thing_speed = 4

现在它落下了

thing_starty += thing_speed 

在每次while循环迭代中。你知道吗

对于下一个物体,我只是把随机数加到原始的X和Y坐标上,这样它就得到了不同的位置。(如果mult==True,则使用下面的cf函数创建两个rect对象)

def things_mult(thingx, thingy, thingw, thingh, color, mult, xopt, yopt, wopt, col2):
    if mult == False:
        pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
    else:
        pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw , thingh])
        pygame.draw.rect(gameDisplay, col2, [thingx + xopt, thingy + yopt, thingw + wopt, thingh])

现在,我想我只需要定义

thingy_new = thing_starty + thing_yopt
thingy_new = thingy_new + thing_speed* someconstant #(to make it faster or slower)

不幸的是,结果不是这样的。 有人能解释一下我为什么会有那么简单的逻辑上的缺陷吗?你知道吗


Tags: rectnewpygamecolorspeedthingdrawthingy
1条回答
网友
1楼 · 发布于 2024-09-29 19:27:39

最简单的解决方案是在代表游戏对象的列表中组合rect、speed和其他数据,然后将这些对象放入另一个列表中,并使用for循环来更新位置并绘制它们。你知道吗

您还可以使用字典而不是列表来提高代码的可读性。你知道吗

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
# The objects consist of a pygame.Rect, the y-speed and a color.
objects = [
    [pygame.Rect(150, -20, 64, 30), 5, pg.Color('dodgerblue')],
    [pygame.Rect(350, -20, 64, 30), 3, pg.Color('sienna1')],
    ]

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    for obj in objects:
        # [0] is the rect, [1] is the y-speed.
        # Move the objects by adding the speed to the rect.y coord.
        obj[0].y += obj[1]

    screen.fill(BG_COLOR)
    # Draw the rects.
    for obj in objects:
        pg.draw.rect(screen, obj[2], obj[0])
    pg.display.flip()
    clock.tick(60)

pg.quit()

如果您知道类是如何工作的,并且您的对象也需要特殊的行为,那么最好为您的对象定义一个类。你知道吗

相关问题 更多 >

    热门问题