How to load an image in pygame?

Viewed 89

So I'm a new programmer 2 weeks of learning. I was wondering on how to load an image correctly using Pygame 1.9.6. I'm trying to roll a dice and whatever it rolls loads the correct image. But, I need to know how to load an image first.

Now this is all what I've come up with so far:

import pygame as p


WIDTH = HEIGHT = 250
DIMENSION = 2
SQ_SIZE = HEIGHT // DIMENSION
IMAGES = {}


class DiceState:
   def __int__(self):
       self.Dice = ['d1', 'd2', 'd3', 'd4', 'd5', 'd6']


def drawBackground(screen):
    colors = [p.Color("black")]
    for d in range(DIMENSION):
        color = colors
        p.draw.rect(screen, color, p.Rect(SQ_SIZE, SQ_SIZE))


def loadImages():
    dice_sides = ['d1', 'd2', 'd3', 'd4', 'd5', 'd6']
    for dice_side in dice_sides:
        IMAGES[dice_side] = p.transform.scale(p.image.load("images/" + dice_side + ".png"), SQ_SIZE)


def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    screen.fill(p.Color("white"))
    ds = DiceState
    loadImages()
    running = True


if __name__ == "__main__":
    main()

d1 means dice 1 for number 1. d2 = number 2

What I've tried is that it's my first time attempting this so I have no idea what to do. I know I shouldn't come on this site and pester you all to fix my issues. But all I want is help. I want to learn like you all too. So please help me if you can and want.

2 Answers

You're loading the image OK, but passing incorrect arguments to the transform. Looking at the documentation on transform, you need to pass a ( width, height ), whereas your existing code is just passing a single number constant SQ_SIZE.

There's no real benefit from embedding a whole lot of function calls in together. Separate out each call into nicely-named variables to make your code more self-documenting:

def loadImages():
    global IMAGES, SQ_SIZE
    dice_sides = ['d1', 'd2', 'd3', 'd4', 'd5', 'd6']
    for dice_side in dice_sides:
        image_path  = os.path.join( "images", dice_side + ".png" )
        face_image  = p.image.load( image_path ).convert()
        target_size = ( SQ_SIZE, SQ_SIZE )
        sized_image = p.transform.scale( face_image, target_size )
        IMAGES[dice_side] = sized_image

It's better to use os.path.join() to make paths, as it handles all the operating system path dependencies automatically.

Do you intend to make the loadImages() a member function of the DiceState class?

asuming that you have the images 'd1.png'...'d6.png' than you can set the IMAGES variable like so:

os.chdir('images')
IMAGES = {'d'+side:p.transform.scale(p.image.load('d'+side+'.png').convert(), SQ_SIZE) for side in range(1, 7)}

then get rid of

for dice_side in dice_sides:
    IMAGES[dice_side] = p.transform.scale(p.image.load("images/" + dice_side + ".png"), SQ_SIZE)

in loadImages()

Related