我尝试运行时收到的错误消息是:第 69 行,Boids 中没有对象 Boids,第 69 行参考鼠标输入行。
#!/usr/bin/env python
from random import random
from pygame.locals import *
import boids, predator, diver, pygame, sys
import config as cfg
bgimage = pygame.image.load("ramfjord.png")
class Ramfjorden:
def __init__(self, width=1024, height=760):
pygame.init()
self.width = width
self.height = height
self.screen = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption('Ramfjorden')
def loadSprites(self):
self.predator_group = pygame.sprite.Group()
for i in range(cfg.predatorNum):
self.predator_group.add(predator.Predator(rect=pygame.Rect(random()*self.width, random()*self.height, 70, 70)))
self.boids_group = pygame.sprite.Group()
for i in range(cfg.boidNum):
self.boids_group.add(boids.Boids(rect=pygame.Rect(random()*self.width, random()*self.height, 40, 40)))
self.diver_group = pygame.sprite.Group()
self.diver_group.add(diver.Diver(rect=pygame.Rect(300, 300, 150, 231)))
def collision(self, sprite1, sprite2):
if sprite1 == sprite2:
return False
else:
return pygame.sprite.collide_circle(sprite1, sprite2)
def mainLoop(self):
fps = pygame.time.Clock()
self.loadSprites()
while True:
self.screen.blit(bgimage, (0,0))
self.predator_group.draw(self.screen)
self.boids_group.draw(self.screen)
self.diver_group.draw(self.screen)
for predator in self.predator_group.sprites():
predator.update(ramfjord=self)
for boids in self.boids_group.sprites():
boids.update(ramfjord=self)
for predator in self.predator_group.sprites():
predator.swim(ramfjord=self)
for boids in self.boids_group.sprites():
boids.swim(ramfjord=self)
spriteHitList = pygame.sprite.groupcollide(self.predator_group, self.boids_group, False, True, collided=self.collision)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
elif event.type == pygame.MOUSEBUTTONUP:
self.boids_group.add(boids.Boids(rect=pygame.Rect(random()*self.width, random()*self.height, 40, 40)))
pygame.display.update()
fps.tick(30)
def main():
ramfjord = Ramfjorden()
ramfjord.mainLoop()
if __name__ == "__main__":
main()