Pygame - Loading images in sprites










3















How do I load an image into a sprite instead of drawing a shape for the sprite?
Ex: I load a 50x50 image into a sprite instead of drawing a 50x50 rect



Here is my sprite code so far:



class Player(pygame.sprite.Sprite):

def __init__(self, color, width, height):

super().__init__()
#Config
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)

# Draw
pygame.draw.rect(self.image, color , [0, 0, width, height])

# Fetch
self.rect = self.image.get_rect()

def right(self, pixels):
self.rect.x += pixels
def left(self, pixels):
self.rect.x -= pixels
def up(self, pixels):
self.rect.y -= pixels
def down(self, pixels):
self.rect.y += pixels









share|improve this question


























    3















    How do I load an image into a sprite instead of drawing a shape for the sprite?
    Ex: I load a 50x50 image into a sprite instead of drawing a 50x50 rect



    Here is my sprite code so far:



    class Player(pygame.sprite.Sprite):

    def __init__(self, color, width, height):

    super().__init__()
    #Config
    self.image = pygame.Surface([width, height])
    self.image.fill(WHITE)
    self.image.set_colorkey(WHITE)

    # Draw
    pygame.draw.rect(self.image, color , [0, 0, width, height])

    # Fetch
    self.rect = self.image.get_rect()

    def right(self, pixels):
    self.rect.x += pixels
    def left(self, pixels):
    self.rect.x -= pixels
    def up(self, pixels):
    self.rect.y -= pixels
    def down(self, pixels):
    self.rect.y += pixels









    share|improve this question
























      3












      3








      3








      How do I load an image into a sprite instead of drawing a shape for the sprite?
      Ex: I load a 50x50 image into a sprite instead of drawing a 50x50 rect



      Here is my sprite code so far:



      class Player(pygame.sprite.Sprite):

      def __init__(self, color, width, height):

      super().__init__()
      #Config
      self.image = pygame.Surface([width, height])
      self.image.fill(WHITE)
      self.image.set_colorkey(WHITE)

      # Draw
      pygame.draw.rect(self.image, color , [0, 0, width, height])

      # Fetch
      self.rect = self.image.get_rect()

      def right(self, pixels):
      self.rect.x += pixels
      def left(self, pixels):
      self.rect.x -= pixels
      def up(self, pixels):
      self.rect.y -= pixels
      def down(self, pixels):
      self.rect.y += pixels









      share|improve this question














      How do I load an image into a sprite instead of drawing a shape for the sprite?
      Ex: I load a 50x50 image into a sprite instead of drawing a 50x50 rect



      Here is my sprite code so far:



      class Player(pygame.sprite.Sprite):

      def __init__(self, color, width, height):

      super().__init__()
      #Config
      self.image = pygame.Surface([width, height])
      self.image.fill(WHITE)
      self.image.set_colorkey(WHITE)

      # Draw
      pygame.draw.rect(self.image, color , [0, 0, width, height])

      # Fetch
      self.rect = self.image.get_rect()

      def right(self, pixels):
      self.rect.x += pixels
      def left(self, pixels):
      self.rect.x -= pixels
      def up(self, pixels):
      self.rect.y -= pixels
      def down(self, pixels):
      self.rect.y += pixels






      python pygame






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 2 '17 at 18:24









      PygasmPygasm

      663421




      663421






















          1 Answer
          1






          active

          oldest

          votes


















          3














          First load the image in the global scope or in a separate module and import it. Don't load it in the __init__ method, otherwise it has to be read from the hard disk every time you create an instance and that's slow.



          Now you can assign the global IMAGE in the class (self.image = IMAGE) and all instances will reference this image.



          import pygame as pg


          pg.init()
          # The screen/display has to be initialized before you can load an image.
          screen = pg.display.set_mode((640, 480))

          IMAGE = pg.image.load('an_image.png').convert_alpha()


          class Player(pg.sprite.Sprite):

          def __init__(self, pos):
          super().__init__()
          self.image = IMAGE
          self.rect = self.image.get_rect(center=pos)


          If you want to use different images for the same class, you can pass them during the instantiation:



          class Player(pg.sprite.Sprite):

          def __init__(self, pos, image):
          super().__init__()
          self.image = image
          self.rect = self.image.get_rect(center=pos)


          player1 = Player((100, 300), IMAGE1)
          player2 = Player((300, 300), IMAGE2)



          Use the convert or convert_alpha (for images with transparency) methods to improve the blit performance.




          If the image is in a subdirectory (for example "images"), construct the path with os.path.join:



          import os.path
          import pygame as pg

          IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha()





          share|improve this answer

























          • I copied everything and the images will not appear, therefore the sprites just show up as blank.

            – Pygasm
            Nov 2 '17 at 20:18












          • Nvm i got it to work, I needed to remove the colorkey and surface.fill code blocks for it to work, thanks!

            – Pygasm
            Nov 2 '17 at 20:28











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47082209%2fpygame-loading-images-in-sprites%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          First load the image in the global scope or in a separate module and import it. Don't load it in the __init__ method, otherwise it has to be read from the hard disk every time you create an instance and that's slow.



          Now you can assign the global IMAGE in the class (self.image = IMAGE) and all instances will reference this image.



          import pygame as pg


          pg.init()
          # The screen/display has to be initialized before you can load an image.
          screen = pg.display.set_mode((640, 480))

          IMAGE = pg.image.load('an_image.png').convert_alpha()


          class Player(pg.sprite.Sprite):

          def __init__(self, pos):
          super().__init__()
          self.image = IMAGE
          self.rect = self.image.get_rect(center=pos)


          If you want to use different images for the same class, you can pass them during the instantiation:



          class Player(pg.sprite.Sprite):

          def __init__(self, pos, image):
          super().__init__()
          self.image = image
          self.rect = self.image.get_rect(center=pos)


          player1 = Player((100, 300), IMAGE1)
          player2 = Player((300, 300), IMAGE2)



          Use the convert or convert_alpha (for images with transparency) methods to improve the blit performance.




          If the image is in a subdirectory (for example "images"), construct the path with os.path.join:



          import os.path
          import pygame as pg

          IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha()





          share|improve this answer

























          • I copied everything and the images will not appear, therefore the sprites just show up as blank.

            – Pygasm
            Nov 2 '17 at 20:18












          • Nvm i got it to work, I needed to remove the colorkey and surface.fill code blocks for it to work, thanks!

            – Pygasm
            Nov 2 '17 at 20:28
















          3














          First load the image in the global scope or in a separate module and import it. Don't load it in the __init__ method, otherwise it has to be read from the hard disk every time you create an instance and that's slow.



          Now you can assign the global IMAGE in the class (self.image = IMAGE) and all instances will reference this image.



          import pygame as pg


          pg.init()
          # The screen/display has to be initialized before you can load an image.
          screen = pg.display.set_mode((640, 480))

          IMAGE = pg.image.load('an_image.png').convert_alpha()


          class Player(pg.sprite.Sprite):

          def __init__(self, pos):
          super().__init__()
          self.image = IMAGE
          self.rect = self.image.get_rect(center=pos)


          If you want to use different images for the same class, you can pass them during the instantiation:



          class Player(pg.sprite.Sprite):

          def __init__(self, pos, image):
          super().__init__()
          self.image = image
          self.rect = self.image.get_rect(center=pos)


          player1 = Player((100, 300), IMAGE1)
          player2 = Player((300, 300), IMAGE2)



          Use the convert or convert_alpha (for images with transparency) methods to improve the blit performance.




          If the image is in a subdirectory (for example "images"), construct the path with os.path.join:



          import os.path
          import pygame as pg

          IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha()





          share|improve this answer

























          • I copied everything and the images will not appear, therefore the sprites just show up as blank.

            – Pygasm
            Nov 2 '17 at 20:18












          • Nvm i got it to work, I needed to remove the colorkey and surface.fill code blocks for it to work, thanks!

            – Pygasm
            Nov 2 '17 at 20:28














          3












          3








          3







          First load the image in the global scope or in a separate module and import it. Don't load it in the __init__ method, otherwise it has to be read from the hard disk every time you create an instance and that's slow.



          Now you can assign the global IMAGE in the class (self.image = IMAGE) and all instances will reference this image.



          import pygame as pg


          pg.init()
          # The screen/display has to be initialized before you can load an image.
          screen = pg.display.set_mode((640, 480))

          IMAGE = pg.image.load('an_image.png').convert_alpha()


          class Player(pg.sprite.Sprite):

          def __init__(self, pos):
          super().__init__()
          self.image = IMAGE
          self.rect = self.image.get_rect(center=pos)


          If you want to use different images for the same class, you can pass them during the instantiation:



          class Player(pg.sprite.Sprite):

          def __init__(self, pos, image):
          super().__init__()
          self.image = image
          self.rect = self.image.get_rect(center=pos)


          player1 = Player((100, 300), IMAGE1)
          player2 = Player((300, 300), IMAGE2)



          Use the convert or convert_alpha (for images with transparency) methods to improve the blit performance.




          If the image is in a subdirectory (for example "images"), construct the path with os.path.join:



          import os.path
          import pygame as pg

          IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha()





          share|improve this answer















          First load the image in the global scope or in a separate module and import it. Don't load it in the __init__ method, otherwise it has to be read from the hard disk every time you create an instance and that's slow.



          Now you can assign the global IMAGE in the class (self.image = IMAGE) and all instances will reference this image.



          import pygame as pg


          pg.init()
          # The screen/display has to be initialized before you can load an image.
          screen = pg.display.set_mode((640, 480))

          IMAGE = pg.image.load('an_image.png').convert_alpha()


          class Player(pg.sprite.Sprite):

          def __init__(self, pos):
          super().__init__()
          self.image = IMAGE
          self.rect = self.image.get_rect(center=pos)


          If you want to use different images for the same class, you can pass them during the instantiation:



          class Player(pg.sprite.Sprite):

          def __init__(self, pos, image):
          super().__init__()
          self.image = image
          self.rect = self.image.get_rect(center=pos)


          player1 = Player((100, 300), IMAGE1)
          player2 = Player((300, 300), IMAGE2)



          Use the convert or convert_alpha (for images with transparency) methods to improve the blit performance.




          If the image is in a subdirectory (for example "images"), construct the path with os.path.join:



          import os.path
          import pygame as pg

          IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha()






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 2 '17 at 19:22

























          answered Nov 2 '17 at 19:00









          skrxskrx

          15.7k31835




          15.7k31835












          • I copied everything and the images will not appear, therefore the sprites just show up as blank.

            – Pygasm
            Nov 2 '17 at 20:18












          • Nvm i got it to work, I needed to remove the colorkey and surface.fill code blocks for it to work, thanks!

            – Pygasm
            Nov 2 '17 at 20:28


















          • I copied everything and the images will not appear, therefore the sprites just show up as blank.

            – Pygasm
            Nov 2 '17 at 20:18












          • Nvm i got it to work, I needed to remove the colorkey and surface.fill code blocks for it to work, thanks!

            – Pygasm
            Nov 2 '17 at 20:28

















          I copied everything and the images will not appear, therefore the sprites just show up as blank.

          – Pygasm
          Nov 2 '17 at 20:18






          I copied everything and the images will not appear, therefore the sprites just show up as blank.

          – Pygasm
          Nov 2 '17 at 20:18














          Nvm i got it to work, I needed to remove the colorkey and surface.fill code blocks for it to work, thanks!

          – Pygasm
          Nov 2 '17 at 20:28






          Nvm i got it to work, I needed to remove the colorkey and surface.fill code blocks for it to work, thanks!

          – Pygasm
          Nov 2 '17 at 20:28




















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47082209%2fpygame-loading-images-in-sprites%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Top Tejano songwriter Luis Silva dead of heart attack at 64

          ReactJS Fetched API data displays live - need Data displayed static

          Evgeni Malkin