python - 使多个对象自动移动 pygame 中指定的对象数量

标签 python pygame

我正在创建一个包含 NPC 的平铺游戏。我可以成功创建一个 NPC,但是当我绘制多个 NPC 时,它们会在代码运行几秒钟后共享相同的位置。我创建这个示例是为了演示我的意思。

import pygame, random, math

screen = pygame.display.set_mode((800,600)) 

NPCP = {'Bob' : (2,6), 'John' : (4,4)} # 25, 19 max width and height
pygame.time.set_timer(pygame.USEREVENT, (100))
sMove = True

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.USEREVENT:
            sMove = True
    screen.fill((0,0,255))
    for name in NPCP:
        x,y = NPCP.get(name)
        pygame.draw.rect(screen, (255,0,0), (x*32,y*32,50,50))
        if sMove == True:
            move = random.randint(1,4)
            sMove = False
        if move == 1:
            if math.floor(y) > 2:
                y -= 2
        if move == 2:
            if math.floor(y) < 17:
                y += 2
        if move == 3:
            if math.floor(x) < 23:
                x += 2
        if move == 4:
            if math.floor(x) > 2:
                x -= 2
        print(x,y)
        NPCP[name] = (x,y)

    pygame.display.flip()

在本例中,我使用字典来创建这些 NPC 或矩形。我用一个计时器和一个范围从 1 到 4 的随机数字来移动它们,以选择要进行的移动。我使用 for 循环来为每个 NPC 运行。我想知道如何允许这些矩形不以相同的方式移动,并且位置最终不改变到相同的位置并且彼此移动不同。我还希望它使用字典来做到这一点。

最佳答案

如果您想单独移动对象,那么您必须为每个对象生成一个随机方向。

在您的代码中,仅为所有对象生成方向,因为在生成第一个对象的方向后,sMove 立即设置为 False。该方向用于所有对象。
此外,移动方向 (move) 永远不会重置为 0。这会导致最后一个随机方向应用于所有后续帧,直到方向再次更改。

if sMove == True:
    move = random.randint(1,4)
    sMove = False

在循环后重置sMove重置move,解决问题:

for name in NPCP:
    x,y = NPCP.get(name)
    pygame.draw.rect(screen, (255,0,0), (x*32,y*32,50,50))
    if sMove == True:
        move = random.randint(1,4)
    if move == 1:
        if math.floor(y) > 2:
            y -= 2
    if move == 2:
        if math.floor(y) < 16:
            y += 2
    if move == 3:
        if math.floor(x) < 22:
            x += 2
    if move == 4:
        if math.floor(x) > 2:
            x -= 2
    print(x,y)
    NPCP[name] = (x,y)

sMove = False # wait for next timer
move = 0      # stop moving

关于python - 使多个对象自动移动 pygame 中指定的对象数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55723064/

相关文章:

python - Conda 在使用 channel 时无法解析 requirements.yml

python - 使用图片来映射墙壁

Python BeautifulSoup 从 find_all() 返回错误的输入列表

python - 多边形的OpenCV凹凸角点

python - pygame Sprite 组绘制不绘制所有 Sprite

python - rect.collisionrect 在两个矩形之间不起作用

python - 如何将控制台插入 pyGame 窗口?

python - 在不使用 Sprite 的情况下,如何在屏幕底部的移动图像和下落物体之间进行碰撞检测?

python - 当权重参数为整数时如何从 numpy.bincount 获取整数数组

python - 为什么文本行之间有间隙?