首先,一揽子道歉:这是我关于SO的第一个问题。
我正在使用Pygame项目,这两个类代表游戏中的对象,每个类都在自己的模块中。一个由玩家控制(ship.py)。我试图让另一个(kimchi.py)跟随屏幕周围的船舶对象。要做到这一点,我需要将船的centerx和centery值传递给泡菜模块,以及那些我难以接受的地方。我正在使用船舶进口船舶',然后尝试使用ship.centerx来访问变量,但这不起作用。
这是我的完整错误消息:
Traceback (most recent call last):
File "bluesky.py", line 51, in <module>
run_game()
File "bluesky.py", line 36, in run_game
gf.create_kimchi(bs_settings, screen, ship, kimchis)
File "/Users/benjamin_harvey/alien_invasion/hot_dog/game_functions.py", line 137, in create_kimchi
instantiate_kimchi(bs_settings, screen, ship, kimchis)
File "/Users/benjamin_harvey/alien_invasion/hot_dog/game_functions.py", line 108, in instantiate_kimchi
kimchi = Kimchi(bs_settings, screen, ship)
File "/Users/benjamin_harvey/alien_invasion/hot_dog/kimchi.py", line 15, in __init__
self.ship_rect_x = ship.centerx
AttributeError: 'Kimchi' object has no attribute 'centerx'
kimchi.py的相关代码:
import pygame
from pygame.sprite import Sprite
import random
import math
from ship import Ship
class Kimchi(pygame.sprite.Sprite):
"""A class to represent kimchi."""
def __init__(self, bs_settings, screen, ship):
"""Initialize the kimchi and set its starting position."""
pygame.sprite.Sprite.__init__(self)
self.screen = screen
self.bs_settings = bs_settings
self.ship_rect_x = ship.centerx
self.ship_rect_y = ship.centery
---snip---
这是我创建船只和泡菜对象的模块:
import pygame
from pygame.sprite import Group
from settings import Settings
from ship import Ship
import game_functions as gf
from hot_dog import Hotdog
from game_stats import GameStats
from button import Button
from kimchi import Kimchi
def run_game():
# Initialize pygame, settings, and screen object.
pygame.init()
# pygame.mixer.pre_init(44100, -16, 2, 2048)
bs_settings = Settings()
screen = pygame.display.set_mode(
(bs_settings.screen_width, bs_settings.screen_height))
pygame.display.set_caption("Blue Sky")
# Make the Play button
play_button = Button(bs_settings, screen, 'Play')
# Create an instance to store stats.
stats = GameStats(bs_settings)
# Make a ship, a group of bullets, and a group of hot_dogs.
ship = Ship(bs_settings, screen)
hot_dogs = Group()
kimchis = Group()
# Create the fleet of hot_dogs.
gf.create_fleet(bs_settings, screen, ship, hot_dogs)
# Create kimchi.
gf.create_kimchi(bs_settings, screen, ship, kimchis)
# Start the main loop for the game.
while True:
gf.check_events(bs_settings, screen, stats, play_button, ship, hot_dogs, kimchis)
if stats.game_active:
ship.update()
gf.update_hot_dogs(bs_settings, hot_dogs, ship, screen)
gf.update_kimchis(bs_settings, screen, ship, kimchis)
gf.update_screen(bs_settings, screen, stats, ship, hot_dogs, play_button, kimchis)
run_game()