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()

TypeError: invalid color argument我收到pygame.draw 行的错误。我知道我已经从我的文件中读取了一个字符串,但是我如何让 python 知道我希望我的字符串“BLACK”应用于我在程序开始时设置的颜色BLACK = (0, 0, 0)?


富国沪深
浏览 159回答 2
2回答

慕虎7371278

您可以在此处的先前答案中看到如何在此处调查pygame.color.THECOLORS 中的颜色。因此,如果您有一个在 pygames 预定义颜色中命名颜色的字符串,您可以像这样自己获取颜色:BLACK = pygame.Color("black") GREEN = pygame.Color("green")请注意,颜色的名称是小写的。

莫回无

我没有使用 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python