所以我刚刚开始使用pygame并且正在努力在block_list上调用.update_y,在过去的教程中类似的尝试从类中调用该方法并将其与其他人的代码进行比较我看不到任何东西我显然做错了但我收到错误“AttributeError:'Group'对象每次没有属性'update_x'
任何帮助将不胜感激
import pygame, random
# DEFINITIONS
PURPLE = (147, 112, 219)
BLACK = ( 0, 0, 0)
GREEN = ( 34, 139, 34)
WHITE = (255, 255, 255)
WIDTH = 800
HEIGHT = 600
class Block(pygame.sprite.Sprite):
"""
This class is for the targets to hit and player
"""
def __init__(self, color, width, height):
"""
Constructor that deals with dimensions of target
"""
pygame.sprite.Sprite.__init__(self)
self.x_change = 2
self.y_change = 2
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
self.reverse = True
self.move_count = 0
def update_x(self):
if self.reverse:
self.rect.x +=.1
self.move_count +=.1
if self.move_count > 20:
self.reverse = False
self.move_count = 0
else:
self.rect.x -=.1
self.move_count +=.1
if self.move_count > 20:
self.reverse = True
self.move_count = 0
def bullet_movement(self):
self.rect.y += 1
pygame.init()
screen = pygame.display.set_mode([WIDTH, HEIGHT])
# list for block targets
block_list = pygame.sprite.Group()
# list for all sprites
all_sprites_list = pygame.sprite.Group()
# list for player
player_list = pygame.sprite.Group()
x = 10
y = 10
# create targets
for column in range(4):
y += 50
x = 55
for row in range (7):
target = Block(PURPLE, 50, 5)
target.rect.y = y
target.rect.x = x
x += 100
block_list.add(target)
all_sprites_list.add(target)
# create shields
x = 90
for shield in range(4):
shield = Block(PURPLE, 95, 20)
shield.rect.y = 450
shield.rect.x = x
x += 160
all_sprites_list.add(shield)
player = Block(GREEN, 50, 5)
player.rect.y =(HEIGHT - 25)
all_sprites_list.add(player)
player_list.add(player)
game = True
clock = pygame.time.Clock()
while game:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player.rect.x += 25
if event.key == pygame.K_LEFT:
player.rect.x -= 25
screen.fill(BLACK)
block_list.update_x()
all_sprites_list.draw(screen)
clock.tick(60)
pygame.display.flip()
pygame.quit()
答案 0 :(得分:0)
见下面一行:
block_list = pygame.sprite.Group()
它指向没有update_X方法的pygame.sprite.Group()。参考:http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group但是你的update_X是在你的Block类中定义的!如下更改并尝试:
block_list = Block()