我正在 pygame 中創建一個基本模擬,我的物件(螢屏上的綠色方塊表示的變形蟲)有兩種方法。我的更新方法運行良好,但碰撞方法給了我一個屬性錯誤。順便說一句,由于我在螢屏上添加了許多變形蟲,所以我將這些方法應用于我的變形蟲組。
import pygame
import random
import time
from pygame.locals import (
QUIT
)
pygame.init()
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
screen = pygame.display.set_mode([500, 500])
amoebas = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
class Amoeba(pygame.sprite.Sprite):
def __init__(self, maturingSpeed, x, y):
super(Amoeba, self).__init__()
self.surf = pygame.Surface((10,10))
self.surf.fill((0, maturingSpeed, 0))
self.rect = self.surf.get_rect(
center=(
x,
y,
)
)
self.speed = 2
self.age = 1
self.maturingSpeed = maturingSpeed
def update(self):
if self.rect.left <= 0:
direction = 1
elif self.rect.right >= SCREEN_WIDTH:
direction = 2
elif self.rect.top <= 0:
direction = 3
elif self.rect.bottom >= SCREEN_HEIGHT:
direction = 4
else:
direction = random.randint(1, 4)
if direction == 1:
self.rect.move_ip(self.speed, 0)
elif direction == 2:
self.rect.move_ip(-self.speed, 0)
elif direction == 3:
self.rect.move_ip(0, self.speed)
elif direction == 4:
self.rect.move_ip(0, -self.speed)
def collide(self):
posList = [(amoeba.rect.left, amoeba.rect.top) for amoeba in list]
length = len(posList)
print(posList)
print(length)
for i in range(length):
y = posList[i]
for h in range(length):
if posList[h] == y and h != i:
locationX = posList[i][0]
locationY = posList[i][1]
new_amoeba = Amoeba(150, locationX, locationY)
amoebas.add(new_amoeba)
all_sprites.add(new_amoeba)
else:
pass
screen.fill((255, 255, 255))
for i in range(100):
new_amoeba = Amoeba(150, random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT))
amoebas.add(new_amoeba)
all_sprites.add(new_amoeba)
while True:
time.sleep(0.000001)
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == QUIT:
break
amoebas.update()
amoebas.collide()
for entity in all_sprites:
screen.blit(entity.surf, entity.rect)
pygame.display.flip()
pygame.quit()
我對 OOP 很陌生,這是我用它撰寫的第一個復雜程式,所以歡迎任何建議!另外,我知道我的問題與這個問題幾乎相同:Python is throwing AttributeError: 'Group' object has no attribute 'blitme' 但不幸的是我無法理解答案,因此也歡迎任何幫助。
uj5u.com熱心網友回復:
pygame.sprite.Group.draw()并且pygame.sprite.Group.update()是由 提供的方法pygame.sprite.Group。
后者委托給update包含pygame.sprite.Sprite的 s的方法——您必須實作該方法。見pygame.sprite.Group.update():
呼叫
update()組中所有 Sprite 的方法。[...]
前者使用包含的 s 的image和rect屬性pygame.sprite.Sprite來繪制物件——您必須確保pygame.sprite.Sprites 具有所需的屬性。見pygame.sprite.Group.draw():
將包含的 Sprite 繪制到 Surface 引數。這使用
Sprite.image源表面的屬性和Sprite.rect。[...]
因此,您可以呼叫amoebas.update()and amoebas.draw(screen),但不能呼叫amoebas.collide()。
您必須collide在回圈中呼叫這些方法:
for amoeba in amoebas;
amoeba.collide()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/531676.html
下一篇:我如何呼叫這個方法?
