字典没有正确填充

时间:2013-08-17 21:58:06

标签: python pygame

我遇到了我的代码问题,我根本无法理解。

根据以下代码部分:

(worldmap)类中创建第二个字典Generate_Game_World后,HQ位置存储在

self.worldmap[HQLOCATIONX,HQLOCATIONY]["Region_Type"] = "HQ"

然而,在这样做之后,似乎用" HQ"填满整个阵列。在测试窗口中看到的值。我根本无法弄清楚为什么会这样。

import pygame
from tkinter import *

test = Tk ()
test.geometry = ("640x480")

pygame.init()

WORLDSIZE = 499
HQLOCATIONX = int(WORLDSIZE/2)
HQLOCATIONY = int(WORLDSIZE/2)

class Generate_Game_World ():

    regionData = {"Region_Type" : "None", 
                  "Region_Level" : 0}

    def __init__(self, mapSize):
        self.mapSize = mapSize

    def main (self):
        # creates 2d map
        self.worldmap = {(x,y) : self.regionData for x in range(self.mapSize) for y in range (self.mapSize)}

        # Sets the HQ to worldmap(249,249)
        self.worldmap[HQLOCATIONX,HQLOCATIONY]["Region_Type"] = "HQ"

        # checks worldmap(0,0) --> (10,10) for its Region Type
        for x in range (10):
            for y in range (10):
                label = Label (text=self.worldmap[x,y]["Region_Type"]).grid(row = x, column=y)

class Game (object):
    def main (self, screen):
        gameworld = Generate_Game_World(WORLDSIZE)     
        gameworld.main()

        while 1:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return

                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            test.mainloop()
            pygame.display.flip()

if __name__ == "__main__":
    screen = pygame.display.set_mode((1024, 768))
    Game().main(screen)

1 个答案:

答案 0 :(得分:2)

您的所有字典值都是对 one 类属性regionData的引用。

您想要创建副本

self.worldmap = {(x,y): self.regionData.copy() for x in range(self.mapSize) for y in range (self.mapSize)}

这使用dict.copy() method来创建浅拷贝;这就足够了,因为Generate_Game_World.regionData的值只是字符串而且它们是不可变的,因此可以安全地共享。

您还可以使用字典文字从头开始创建新字典;你似乎没有在其他任何地方使用self.regionData,所以内联是可能的:

self.worldmap = {(x,y): {"Region_Type" : "None", "Region_Level" : 0} 
                 for x in range(self.mapSize) for y in range (self.mapSize)}

最后但并非最不重要的是,你的意思是使用None单身而不是字符串"None"吗?