我正在使用 pygame 為游戲制作背景繪圖系統,由于每個場景有 1024 個獨立的方塊,我將每個方塊的顏色存儲在一個 .txt 文件中,例如square1 = BLACKsquare2 = GREEN等等。當我使用此代碼讀取我的文件時 read = open("testgraphics.txt", "r") xcoords = 0 ycoords = 0 for x in read: if xcoords > 1024: xcoords += 32 else: ycoords += 32 print(x) squarecolorformatting = x[-6:] squarecolor = squarecolorformatting[:-1] print(squarecolor) #This returns a string of just the color I want, e.g. BLACK pygame.draw.rect(screen,squarecolor, [xcoords,ycoords,32,32]) #print(f.read()) Scene1Read = True read.close()TypeError: invalid color argument我收到pygame.draw 行的錯誤。我知道我已經從我的文件中讀取了一個字符串,但是我如何讓 python 知道我希望我的字符串“BLACK”應用于我在程序開始時設置的顏色BLACK = (0, 0, 0)?
2 回答

慕虎7371278
TA貢獻1802條經驗 獲得超4個贊
您可以在此處的先前答案中看到如何在此處調查pygame.color.THECOLORS?中的顏色。
因此,如果您有一個在 pygames 預定義顏色中命名顏色的字符串,您可以像這樣自己獲取顏色:
BLACK?=?pygame.Color("black") GREEN?=?pygame.Color("green")
請注意,顏色的名稱是小寫的。

莫回無
TA貢獻1865條經驗 獲得超7個贊
我沒有使用 pygame 的經驗,但是:
小建議:
使用 JSON。使用 JSON,您可以簡單地從文件中讀取列表和字典并將它們寫入文件。
JSON 是一個標準庫,因此您不必安裝它。
JSON文件
{"square1" : "BLACK", "square2" : "GREEN"}
Python文件
import json
閱讀:
with open("MYFILE.json", "r") as file:
mydata = json.load(file)
squarecolor = mydata["square1"]
寫作:
with open("MYFILE.json", "w+") as file:
#The + behind the w means, that, if the file doesn't exist, python creates it
json.dump(mydata, file)
添加回答
舉報
0/150
提交
取消