我有一个列表,其中包含 的类,enemy
并且我使用for
循环和敌人类中的一个函数使它们跟随玩家move()
。
但是当有多个敌人时,他们会在跟随玩家时变得混乱,所以我决定将这个添加到for
循环中:
for enmy in enemies:
pygame.draw.circle(screen, (255,0,0), (enmy.x-enmy.rad,enmy.y-enmy.rad), enmy.rad, 0)
for enmy2 in enemies:
if enmy2 is not enmy:
if not enmy.rect.colliderect(enmy2.rect):
enmy.move()
enmy.rect=pygame.Rect(enmy.x-enmy.rad*2,enmy.y-enmy.rad*2,enmy.rad*2,enmy.rad*2)
pygame.draw.rect(screen, (0,0,255), enmy.rect, 2)
所以我希望这会测试列表中除自身之外的每个实例,但是当对象单独时它不会移动!(而且如果有两个,它们会发生碰撞并停止)
这是整个代码(不需要额外的文件c:)
import pygame
from random import randint
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,480))
clock=pygame.time.Clock()
px=35
py=35
prect=pygame.Rect(px-10,py-10,20,20)
class Enemy(object):
def __init__(self,x,y):
self.x=x
self.y=y
self.rad=randint(5,10)
self.rect=pygame.Rect(0,0,0,0)
def move(self):
if self.x>px:
self.x-=1
if self.y<py:
self.y+=1
if self.x<px:
self.x+=1
if self.y>py:
self.y-=1
enemies=[Enemy(90,80),Enemy(100,100)]
while True:
screen.fill((200,230,200))
key=pygame.key.get_pressed()
if key[K_UP]:
py-=2
if key[K_DOWN]:
py+=2
if key[K_RIGHT]:
px+=2
if key[K_LEFT]:
px-=2
for e in pygame.event.get():
if e.type==QUIT:
exit()
for enmy in enemies:
pygame.draw.circle(screen, (255,0,0), (enmy.x-enmy.rad,enmy.y-enmy.rad), enmy.rad, 0)
for enmy2 in enemies:
if enmy2 is not enmy:
if not enmy.rect.colliderect(enmy2.rect):
enmy.move()
enmy.rect=pygame.Rect(enmy.x-enmy.rad*2,enmy.y-enmy.rad*2,enmy.rad*2,enmy.rad*2)
pygame.draw.rect(screen, (0,0,255), enmy.rect, 2)
prect=pygame.Rect(px-20,py-20,20,20)
pygame.draw.circle(screen, (0,0,255), (px-10,py-10), 10, 0)
pygame.draw.rect(screen, (255,0,0), prect, 2)
clock.tick(80)
pygame.display.flip()
有人请帮助我!