如何解决Pygame从.txt文件中读取字符串,然后用作颜色错误
我正在使用pygame为游戏制作背景绘图系统,并且由于每个场景有1024个独立的正方形,因此我将每个正方形的颜色存储在.txt文件中,例如
square1 = BLACK
square2 = 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()
我收到pygame.draw行的错误TypeError: invalid color argument
。我明白
我已经从文件中读取了一个字符串,但是当我执行BLACK = (0,0)
时,如何让python知道我希望我的字符串“ BLACK”应用于我在程序启动时设置的颜色?
解决方法
我没有使用pygame的经验,但是:
小建议:
使用JSON。使用JSON,您可以轻松地从文件中读取列表和字典并将它们写入文件。
JSON是标准库,因此您无需安装它。
JSONfile
{"square1" : "BLACK","square2" : "GREEN"}
Pythonfile
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)
,
您可以在前面的答案中查看如何调查 pygame.color.THECOLORS here中的颜色。
因此,如果您有一个在pygames预定义颜色中命名颜色的字符串,则可以像这样自己捕获颜色:
BLACK = pygame.Color("black")
GREEN = pygame.Color("green")
请注意,颜色名称均为小写。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。