Ошибка Pygame: self.spritedict [spr] = surface_blit (spr.image, spr.rect)

1

Я делаю игру с pygame с помощью python 3. Я не могу получить изображение инопланетянина для отображения на "экранной" поверхности.

Я искал часы и рассмотрел книгу на ее основе, но я не могу найти источник проблемы. Я также рассмотрел другие вопросы здесь. Спасибо

Heres the trackback:

Traceback (most recent call last):
  File "alien_invasion.py", line 35, in <module>
    run_game()
  File "alien_invasion.py", line 33, in run_game
    g_funcs.update_screen(ai_settings, ai_screen, a_ship, aliens_g, bullets)
  File ...
    aliens_g.draw(ai_screen)
  File...
    self.spritedict[spr] = surface_blit(spr.image, spr.rect)
AttributeError: 'Alien' object has no attribute 'image'

Здесь мой игровой модуль:

import pygame
from pygame.sprite import Group
from settings import Settings
from ship import Ship
import game_function as g_funcs



def run_game():
    """Games definition with control while loop"""
    #Initialize pygame, settings and screen surface
    pygame.init()
    ai_settings = Settings()
    ai_screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_length))
    pygame.display.set_caption("Alien Invasion")

    #make a ship, group of bullets, group of aliens
    a_ship = Ship(ai_settings, ai_screen)
    bullets = Group()
    aliens_g = Group()

    #Create FLEET of aliens
    g_funcs.create_fleet(ai_settings, ai_screen, aliens_g)

    #start the main loop for the game
    while True:

        g_funcs.check_events(ai_settings, ai_screen, a_ship, bullets)
        a_ship.update_location()
        g_funcs.update_bullet(bullets)
        g_funcs.update_screen(ai_settings, ai_screen, a_ship, aliens_g, bullets)

run_game()

Здесь все функции:

import sys
import pygame
from bullet import Bullet
from alien import Alien

def check_events(ai_settings, ai_screen, a_ship, bullets):
    """Respond to keypresses and mouse events."""
    #watch for keyboard and mouse events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_event(event, ai_settings, ai_screen, a_ship, bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_event(event, a_ship)



def check_keydown_event(event, ai_settings, ai_screen, a_ship, bullets):
    """ONLY callable by check_events function when keydown."""
    if event.key == pygame.K_RIGHT:
        a_ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        a_ship.moving_left = True
    elif event.key == pygame.K_UP:
        a_ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        a_ship.moving_down = True
    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings, ai_screen, a_ship, bullets)
    elif event.key == pygame.K_q:
        sys.exit()

def fire_bullet(ai_settings, ai_screen, a_ship, bullets):
    """Fire bullets if bullets limit is not met"""
    #CREATE a new bullet INSTANCE and add it to the bullets GROUP
    if len(bullets) < ai_settings.bullets_allowed:
        new_bullet = Bullet(ai_settings, ai_screen, a_ship)
        bullets.add(new_bullet)

def check_keyup_event(event, a_ship):
    """ONLY callable by check_events function when keyup."""
    if event.key == pygame.K_RIGHT:
        a_ship.moving_right = False
    if event.key == pygame.K_LEFT:
        a_ship.moving_left = False
    if event.key == pygame.K_UP:
        a_ship.moving_up = False
    if event.key == pygame.K_DOWN:
        a_ship.moving_down = False


def update_screen(ai_settings, ai_screen, a_ship, aliens_g, bullets):
    """Update image on the screen and flip to the new screen."""
    #Redraw the screen during each pass through the loop
    ai_screen.fill(ai_settings.bg_color)
    #REDRAW all bullets behind ship and aliens
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    a_ship.blitme()
    aliens_g.draw(ai_screen)
    #Make the most recently drawn screen visible
    pygame.display.flip()

def update_bullet(bullets):
    """Update positions of bullets and delete old ones."""
    #Update bullet positions
    bullets.update()

    #get rid of the old bullets that go off screen
    for bullet in bullets.copy():
        if bullet.bullet_rect.bottom <= 0:
            bullets.remove(bullet)


def create_fleet(ai_settings, ai_screen, aliens_g):
    """Create a full fleet of aliens"""
    alien = Alien(ai_settings, ai_screen)
    alien_amount_x = get_number_aliens_x(ai_settings, alien.alien_rect.width)

    #Create the first row of aliens
    for one in range(alien_amount_x):
        create_alien(ai_settings, ai_screen, aliens_g, one)

def get_number_aliens_x(ai_settings, alien_width):
    """Determine the amount of alien that fits in a row"""
    #Calulations:
    availabe_space_x = ai_settings.screen_width - 2 * alien_width
    alien_amount_x = int(availabe_space_x / (2 * alien_width))
    return alien_amount_x

def create_alien(ai_settings, ai_screen, aliens_g, one):
    """Create an alien and place it in the row."""
    alien = Alien(ai_settings, ai_screen)
    alien_width = alien.alien_rect.width
    alien.x = alien_width + 2 * alien_width * one
    alien.alien_rect.x = alien.x
    aliens_g.add(alien)

И... heres мой чужой модуль:

import pygame
from pygame.sprite import Sprite


class Alien(Sprite):
    """A CLASS that MANAGES a single alienn in the fleet."""

    def __init__(self, ai_settings, ai_screen):
        """Initialize the alien and start position"""
        super().__init__()
        self.ai_settings = ai_settings
        self.screen = ai_screen

        #Load the alien image and SET RECT attribute
        self.alien_image = pygame.image.load('images/alien.bmp')
        self.alien_rect = self.alien_image.get_rect()

        #Set starting point of alien at the top left corner of screen
        #settings the space(top and left) to the width and height of image_rect
        self.alien_rect.x = self.alien_rect.width
        self.alien_rect.y = self.alien_rect.height

        self.x_float = float(self.alien_rect.x)

    def blit_a(self):
        """Draw alien at its current location"""
        self.screen.blit(self.alien_image, self.alien_rect)
Теги:
python-3.x
pygame
sprite

1 ответ

2

Пигмейские спрайты должны иметь self.image и self.rect, иначе группа спрайтов не сможет разбить изображение, и AttributeError будет поднят.

Если вы посмотрите на метод draw групп спрайтов, вы увидите, что он выполняет итерацию над содержащимися спрайтами и blits spr.image на spr.rect.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню