我正在尝试以给定的速率生成无限数量的敌人,并将其移向玩家。但是,我只能设法产生两个,每个它们产生的原始矩形一个。这是因为机芯会覆盖它们所生成的矩形,所以任何其他敌人都只会在前两个之一的顶部生成。这使用的是move_ip()函数,我认为这可能是问题所在,但是尝试仅使用move()则完全没有移动。
def main():
global DISPLAYSURF, FPSCLOCK
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT))
pygame.display.set_caption ('Ronin')
checkForQuit()
enemies = []
playerX = 730
enemyImage = pygame.image.load('enemyidle.png')
enemySurf = pygame.transform.scale(enemyImage, (PLAYERWIDTH, PLAYERHEIGHT))
leftRect = pygame.Rect(0, 735, PLAYERWIDTH, PLAYERHEIGHT)
rightRect = pygame.Rect(1500, 735, PLAYERWIDTH, PLAYERHEIGHT)
moveLeft = moveRight = moveUp = moveDown = False
enemycounter = 0
while True:
checkForQuit()
#Draw the background
DISPLAYSURF.blit(backgroundSurf, backgroundRect)
#draw the player
DISPLAYSURF.blit(playerSurf, playerRect)
#time the enemy spawn and draw the enemies
enemy = random.choice([leftRect, rightRect])
if enemycounter < ENEMYSPAWNRATE:
enemycounter += 1
if enemycounter == ENEMYSPAWNRATE:
enemycounter = 0
enemies.append(enemy)
enemyAI(enemies, playerRect)
for e in enemies:
DISPLAYSURF.blit(enemySurf, e)
pygame.display.update()
FPSCLOCK.tick(FPS)
def enemyAI(enemies, playerRect):
for e in enemies:
if e.left > playerRect.right:
e.move_ip(-1 * PLAYERSPEED +5, 0)
if e.right < playerRect.left:
e.move_ip(PLAYERSPEED -5, 0)
main()
我可以在调试器中看到,添加到敌人列表中的每个新敌人都具有与前两个现有敌人之一相同的坐标。但是我希望它们出现在leftRect或rightRect指定的原始坐标上。
答案 0 :(得分:0)
您基本上是正确的。您的问题在于创建两个矩形,然后将每个敌人分配给这两个矩形之一。
因为enemy = random.choice(...)
为leftRect
或rightRect
创建了一个别名,并且由于您enemies.append(enemy)
,所以您拥有一个由两个相同矩形的别名组成的列表。
尝试在随机选择矩形后制作.copy()
的矩形,
startLocations = (leftRect, rightRect)
def new_enemy():
"""Return a new enemy rect randomly in one of the start locations"""
return random.choice(startLocations).copy()
while True:
# ... as before ...
#time the enemy spawn and draw the enemies
if enemycounter < ENEMYSPAWNRATE:
enemycounter += 1
else:
enemycounter = 0
enemies.append(new_enemy())
enemyAI(enemies, playerRect)
# ... as before ...