根据pygam中指定的对象数自动移动多个对象

2024-09-27 00:22:23 发布

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

我正在创建一个平铺游戏,其中有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运行。我想知道如何让这些矩形不以相同的方式移动,并且位置不会最终改变到相同的位置,并且彼此移动不一样。我还想让它用字典来做


Tags: nameeventtrueformoveifdisplayrandom
1条回答
网友
1楼 · 发布于 2024-09-27 00:22:23

如果要单独移动对象,则必须为每个对象生成一个随机方向

在您的代码中,只为所有对象生成on direction,因为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

相关问题 更多 >

    热门问题