2017-05-29 47 views
1

我想知道是否可以將文本從txt文件顯示到pygame屏幕上。我正在製作一款遊戲,並且我試圖在遊戲中顯示來自文本文件的說明。如何將txt文件顯示到pygame屏幕?

這裏是我做如下:

def instructions(): 
    instructText = instructionsFont.render(gameInstructions.txt, True, WHITE) 
    screen.blit(instructText, ((400 - (instructText.get_width()/2)),(300 - (instructText.get_height()/2)))) 

但是我得到的錯誤:

line 356, in instructions 
    instructText = instructionsFont.render(pongInstructions.txt, True, WHITE) 
NameError: name 'pongInstructions' is not defined 

然而,我的嘗試是所有試驗和錯誤,因爲其實我不確定如何做到這一點... 任何幫助是極大的讚賞!

回答

0

gameinstructions沒有被定義,因爲python認爲它是一個變量。

來告訴Python這是你需要把它放在引號的字符串:

instructText = instructionsFont.render("gameInstructions.txt", True, WHITE) 

但是這可能不是你想要的。你想要做的是讀取文件。對於您應該使用with語句來安全地打開和關閉文件:

with open("gameInstructions.txt") as f: 
    instructText = instructionsFont.render(f.read(), True, WHITE) 

我目前不能嘗試的代碼,但是你可以通過下面的線路需要循環相反,如果pygame的無法處理的幾行文本一次的:

with open("gameInstructions.txt") as f: 
    for line in f: 
     instructText = instructionsFont.render(line, True, WHITE) 
+0

我嘗試這個代碼,但是我得到一個錯誤說:行26,在解碼 回報codecs.ascii_decode(輸入,self.errors)[0] 的UnicodeDecodeError: 'ASCII' 編解碼器無法解碼位置397中的字節0xe2:序號不在範圍內(128) – Student

+0

python的版本是你o N +它似乎期望ascii,而「â​​」字不是其中的一部分。從其他帖子我可以看到它應該支持unicode https://stackoverflow.com/questions/668359/unicode-fonts-in-pygame#668596 – Atsch

+0

我在python 3.6.0運行這個 – Student