[英]Dictionary not populating correctly
我的代碼遇到了一個我根本無法解決的問題。
按照下面的代碼部分:
在Generate_Game_World
類中創建第二個詞典(worldmap)
后,總部位置存儲在
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)
您所有的字典值都是對一個類屬性regionData
引用。
您想創建副本 :
self.worldmap = {(x,y): self.regionData.copy() for x in range(self.mapSize) for y in range (self.mapSize)}
dict.copy()
使用dict.copy()
方法創建一個淺表副本。 這是足夠的,因為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"
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.