jbills
jbills

Reputation: 694

Strange pygame image error

I have a small problem in my code. I have the following code:

import os,pygame
class npc:
    ntype = 0
    image = None
    x = 0
    y = 0
    text = ""
    name = ""
    def Draw(self,screen):
        screen.blit(self.image, [self.x*32,self.y*32])
    def __init__(self,name,nx,ny):
        f = open(name)
        z = 0
        for line in f:
            if z == 0:
                name = line
            if z == 1:
                ntype = line
            if z == 2:
                text = line
            if z == 3:
                self.image = pygame.image.load(os.path.join('img', line))
            self.x = nx
            self.y = ny
            z=z+1

The file which I am loading from is in the following format:

The Shadow
0
Hello. I am evil.
shadow.png

It is the last line which has the problem. When I try to load that png using pygame.image.load I get an error saying that it cant load that image. If I change the pygame load code to self.image = pygame.image.load(os.path.join('img', "shadow.png")) however, it works perfectly. I have looked over the files several times, and I can't find any reason for this error. Can someone see what I am doing wrong?

Traceback:

Traceback (most recent call last):
  File "./main.py", line 26, in <module>
    rmap = g.Load_Map("l1.txt",char)
  File "/home/josiah/python/rpg/generate.py", line 31, in Load_Map
    npcs.append(npc.npc(str.split(bx,',')[1],x,y))
  File "/home/josiah/python/rpg/npc.py", line 23, in __init__
    self.image = pygame.image.load(os.path.join('img', line))
pygame.error: Couldn't open img/shadow.png

Upvotes: 3

Views: 1298

Answers (1)

jro
jro

Reputation: 9474

You might have a trailing newline character. Try stripping the line:

self.image = pygame.image.load(os.path.join('img', line.strip()))

Better yet, load your file differently. Instead of the loop, you could do something like this (assuming every file is formatted identically, and has at least the same number of lines):

name, ntype, text, filename = [l.strip() for l in open(name).readlines()[:4]]

# Now use the variables normally, for example:
self.image = pygame.image.load(os.path.join('img', filename))

Upvotes: 2

Related Questions