Sep-15-2019, 01:42 AM
I am trying to create a class called Ship in a separate .py file and I am trying to import its associated .png image (ship.png) into my Pygame file and every time I try to import the image or the class I receive this error message:
Please note that there is another class called settings but I am sure that is not the cause of the problem since the program ran fine before with it in it.
* All the files are saved in the exact same folder and the image is in a .png format.
Error:Traceback (most recent call last):
File "C:\Users\maxya\PycharmProjects\pygame\Alien Invasion\alien invasion.py", line 28, in <module>
run_game()
File "C:\Users\maxya\PycharmProjects\pygame\Alien Invasion\alien invasion.py", line 15, in run_game
ship = Ship(screen)
File "C:\Users\maxya\PycharmProjects\pygame\Alien Invasion\ship.py", line 4, in __init__
self.image = pygame.image.load('ship.png')
NameError: name 'pygame' is not defined
The code for the separate .py file for the ship class is this:class Ship(): def __init__(self, screen): self.screen = screen self.image = pygame.image.load('ship.png') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom def blitme(self): self.screen.blit(self.image, self.rect)The source code for the file I am trying to import the ship image and class into is this:
Please note that there is another class called settings but I am sure that is not the cause of the problem since the program ran fine before with it in it.
import sys import pygame from alien_invasion_settings import Settings from ship import Ship def run_game(): # init the game and create a screen object pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invansion") ship = Ship(screen) # main loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(ai_settings.bg_color) ship.blitme() pygame.display.flip() run_game()Any help would be greatly appreciated and thank you so much for your time.
* All the files are saved in the exact same folder and the image is in a .png format.