多亏了这里的帮助,我在这个小程序上一直在进步。现在,我从行“ orchids.draw(screen)”中收到以下错误消息:“ AttributeError:'Sprite'对象没有属性'draw'”,该事件发生在碰撞事件之后。该程序在碰撞事件之前可以正常工作。我是pygame的新手,还是面向对象编程的新手。关于如何使程序运行的任何想法?
#Import and Init
import pygame
import random
from pygame.locals import *
pygame.init()
class Orchid(pygame.sprite.Sprite):
def __init__(self, pos):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('orchid1.gif')
self.rect = self.image.get_rect()
self.rect.topleft = pos
self.x_inc = 4
self.y_inc = 4
def update(self):
self.rect.x += self.x_inc
self.rect.y += self.y_inc
if self.rect.y > 700 or self.rect.y < 0:
self.y_inc = self.y_inc * -1
if self.rect.x > 1240 or self.rect.x < 0:
self.x_inc = self.x_inc * -1
#Set Up the Window
width = 1240
height = 700
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pollination!")
background = pygame.Surface(screen.get_size())
background = pygame.image.load("Forrest.jpg")
background = background.convert()
#Load and Convert the wasp
wasp = pygame.sprite.Sprite()
wasp.image = pygame.image.load("wasp1.gif")
wasp.rect = wasp.image.get_rect()
wasp_group = pygame.sprite.GroupSingle(wasp)
orchids = pygame.sprite.OrderedUpdates()
for i in range(7):
tmp_x = random.randrange(0, 1240)
tmp_y = random.randrange(0, 700)
orchids.add(Orchid([tmp_x, tmp_y]))
buzz = pygame.mixer.Sound("buzz.wav")
#Clock and Loop Variables
framerate = pygame.time.Clock()
GameGo = True
wasp_move = 5
#The Main Loop
while GameGo:
#Tick the Clock
framerate.tick(60)
#Keyborad Keypress Events, Movement
if pygame.key.get_pressed()[K_UP]:
wasp.rect.top -= wasp_move
if wasp.rect.top < -30:
wasp.rect.top = -30
if pygame.key.get_pressed()[K_DOWN]:
wasp.rect.top += wasp_move
if wasp.rect.top > 625:
wasp.rect.top = 625
if pygame.key.get_pressed()[K_LEFT]:
wasp.rect.right -= wasp_move
if wasp.rect.right < 110:
wasp.rect.right = 110
if pygame.key.get_pressed()[K_RIGHT]:
wasp.rect.right += wasp_move
if wasp.rect.right > 1255:
wasp.rect.right = 1255
for orchids in pygame.sprite.groupcollide(wasp_group, orchids, False, True):
buzz.play()
## #Blit our Images
screen.blit(background, (0, 0))
wasp_group.draw(screen)
orchids.draw(screen)
orchids.update()
pygame.display.update()
#Handle a Close Event
for event in pygame.event.get():
if event.type == pygame.QUIT:
GameGo = False
pygame.quit()
最佳答案
你的循环
for orchids in pygame.sprite.groupcollide(wasp_group, orchids, False, True):
buzz.play()
使名称
orchids
逐一分配给从groupcollide()
返回的每个兰花。在Python中,for
循环不会引入新的作用域,因此发生的是您在此循环的每次迭代中都覆盖了名称orchids
。然后,如Malik Brahimi指出的那样,在
orchids.draw
处,您试图在单个兰花(Sprite
对象)中找到该方法,这是一个精灵组的方法。因此'Sprite' object has no attribute 'draw'
。您可以通过将循环变量从
orchids
更改为orchid
来解决此问题。然后,什么都不会被覆盖。关于python - pygame碰撞麻烦,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29334567/