Bottom Page

Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 [PyGame] Importing a .png image
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:
Traceback (most recent call last): File "C:\Users\maxya\PycharmProjects\pygame\Alien Invasion\alien", line 28, in <module> run_game() File "C:\Users\maxya\PycharmProjects\pygame\Alien Invasion\alien", line 15, in run_game ship = Ship(screen) File "C:\Users\maxya\PycharmProjects\pygame\Alien Invasion\", 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
   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:
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.
You need to install pygame
From command line, not in python interpreter:
pip install pygame
It looks you didn't import pygame in
If that's all the code, you should keep it all in one file to more easily edit everything. Though if you plan to make many different classes, you can put them all in a different files and import them into a main file like you are doing with the Ship class. It just depends on how big the classes are and how many. Having 6 classes in one file could be disorganized and make it hard to find certain code. With just one class though, it can stay in the same file as main.
Age Doesn't Matter, Your Passion Does
- Shreya Jain

Top Page

Forum Jump:

Users browsing this thread: 1 Guest(s)