我正在创建一个包含 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/