Python Pygame读取.txt文件中的字符串,然后将其用作颜色错误

Python Pygame读取.txt文件中的字符串,然后将其用作颜色错误,python,pygame,Python,Pygame,我正在使用pygame为一个游戏制作一个背景绘图系统,由于每个场景有1024个独立的方块,我将每个方块的颜色存储在一个.txt文件中,如 square1 = BLACK square2 = GREEN 等等 当我使用此代码读取文件时 read = open("testgraphics.txt", "r") xcoords = 0 ycoords = 0 for x in read: if xcoords &

我正在使用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参数。我理解
我已经从我的文件中读取了一个字符串,但是当我执行
BLACK=(0,0,0)
时,如何让python知道我希望字符串“BLACK”应用于我在程序开始时设置的颜色?

我对pygame没有经验,但是:

小建议:

使用JSON。使用JSON,您可以简单地从文件中读取列表和字典,然后将它们写入文件

JSON是一个标准库,因此您不必安装它

JSONfile

{"square1" : "BLACK", "square2" : "GREEN"}
蟒蛇

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方面的经验,但是:

小建议:

使用JSON。使用JSON,您可以简单地从文件中读取列表和字典,然后将它们写入文件

JSON是一个标准库,因此您不必安装它

JSONfile

{"square1" : "BLACK", "square2" : "GREEN"}
蟒蛇

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中的颜色

因此,如果您有一个字符串以pygames预定义的颜色命名颜色,您可以像下面这样获取颜色本身:

BLACK=pygame.Color(“黑色”)
绿色=pygame.Color(“绿色”)

请注意,颜色的名称是小写。

您可以在前面的回答中看到如何在pygame.color.THECOLORS中调查颜色

因此,如果您有一个字符串以pygames预定义的颜色命名颜色,您可以像下面这样获取颜色本身:

BLACK=pygame.Color(“黑色”)
绿色=pygame.Color(“绿色”)

请注意,颜色的名称是小写。

您使用字典,例如,{'BLACK':(0,0,0),'WHITE':(255255244)}@JustinEzequiel pygame抽屉是否允许颜色rgb值作为列表而不是颜色名称?什么列表?字典是从字符串中查找颜色值。您使用字典,例如,{'BLACK':(0,0,0),'WHITE':(255255244)}@JustinEzequiel pygame抽屉允许颜色rgb值作为列表而不是颜色名称吗?什么列表?字典将从字符串中查找颜色值。但是这允许我在10行代码中渲染所有1024个正方形吗?您的方法似乎意味着我必须键入所有键如果您是指循环,您可以使用以下命令:
对于范围内的I(len(mydata)):squarecolor=mydata[“square”+I]
,但这允许我在10行代码中渲染所有1024个正方形吗?您的方法似乎暗示我必须键入所有键如果您是指循环,您可以使用以下命令:
for I in range(len(mydata)):squarecolor=mydata[“square”+I]