How to load an image in python?

  • As a general rule, assets should be loaded once before draw() starts.
  • Best place for loading assets is within setup() btW. Not in classes or in draw().
  • Here’s my take on your posted code:
# https://Discourse.Processing.org/t/how-to-load-an-image-in-python/17710/4
# 2020/Feb/11

FILES = 'warrior.png', 'knight.png'
troop = []

def setup():
    size(600, 600)
    
    global images
    images = tuple(loadImage(img) for img in FILES)

    Warrior.img = images[0]
    Knight.img = images[1]

    cy = height >> 1

    troop.append(Warrior('Chuck', 0, cy))
    troop.append(Warrior('Bruce', 100, cy))
    troop.append(Knight('Carl', 200, cy))
    troop.append(Warrior('Dave', 300, cy))

    for i in range(8): troop[0].fight(troop[2])

    for t in troop: print t.show()


class Warrior(object):
    img = None

    def __init__(self, name, x, y):
        self.health = 50
        self.attack = 5
        self.alive = True

        self.name = name
        self.x = x
        self.y = y


    def __str__(self, STR = 'Name: %s, Health: %d, Attack: %d, Alive: %s'):
        return STR % (self.name, self.health, self.attack, self.alive)


    def show(self):
        image(self.img, self.x, self.y)
        return self


    def fight(self, other):
        self.health -= other.attack
        other.health -= self.attack

        self.alive = self.health > 0
        other.alive = other.health > 0

        return self



class Knight(Warrior):
    def __init__(self, name, x, y):
        super(Knight, self).__init__(name, x, y)
        self.attack = 7
2 Likes