2011-11-30 71 views
3

我在我的代碼中有一個小問題。我有以下代碼:奇怪的pygame圖像錯誤

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 Shadow 
0 
Hello. I am evil. 
shadow.png 

這是有問題的最後一道防線。當我嘗試使用pygame.image.load加載該png時,我收到一個錯誤,說它不能加載該圖像。但是,如果我將pygame加載代碼更改爲self.image = pygame.image.load(os.path.join('img', "shadow.png")),它完美地工作。我已經多次查看這些文件,並且找不到此錯誤的任何原因。有人可以看到我做錯了什麼嗎?

回溯:

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 
+0

你爲什麼不使用類似: '[名,ntype,text,self.image] = f.read()。split('\ n')' – joaquin

回答

2

你可能有一個尾部的換行符。試試剝線:

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

更好的是,加載文件的方式不同。取而代之的是循環的,你可以做這樣的事情(假設每個文件格式相同,且至少具有相同的行數):

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)) 
+0

謝謝:)我不知道那是怎麼回事。文件中沒有任何換行符。 – jbills