2017-10-06 32 views
0

所以我不知道如何解釋它,但如果你看看這個代碼,你可能會有所幫助。需要幫助創建一個Python中的列表和函數的字典

class tower: 
    def __init__(self, name, namex, namey, x, y, width, height, nameimg): 
     self.name = name 
     self.namex = namex 
     self.namey = namey 
     self.x = x 
     self.y = y 
     self.width = width 
     self.height = height 
     self.nameimg = nameimg 

    def getname(self): 
     return self.name 
    def getnamex(self): 
     return self.namex 
    def getnamey(self): 
     return self.namey 
    def getx(self): 
     return self.x 
    def gety(self): 
     return self.y 
    def getwidth(self): 
     return self.width 
    def getheight(self): 
     return self.height 
    def getnameimg(self): 
     return self.nameimg 


background = tower("background", "backgroundx", "backgroundy", 0, 0, 1280, 720, backgroundImg) 
ppsh = tower("ppsh", "ppshx", "ppshy", 1127, 140, 120, 40, ppshImg) 
trenchgun = tower("trenchgun", "trenchgunx", "trenchguny", 1207, 140, 120, 27, trenchgunImg) 
thompson = tower("thompson", "thompsonx", "thompsony", 1127, 120, 120, 39, thompsonImg) 
colt = tower("colt", "coltx", "colty", 1, 1, 70, 46, coltImg) 
mg = tower("mg", "mgx", "mgy", 1, 1, 135, 27, mgImg) 

towers = [background, ppsh, trenchgun, thompson, colt, mg] 

def game_loop(): 
    positions = { 
     (background.getnamex()): (background.getx()), 
     (background.getnamey()): (background.gety()), 
     (ppsh.getnamex()): (ppsh.getx()), 
     (ppsh.getnamey()): (ppsh.gety()), 
     (trenchgun.getnamex()): (trenchgun.getx()), 
     (trenchgun.getnamey()): (trenchgun.gety()), 
     (thompson.getnamex()): (thompson.getx()), 
     (thompson.getnamey()): (thompson.gety()), 
     (colt.getnamex()): (colt.getx()), 
     (colt.getnamey()): (colt.gety()), 
     (mg.getnamex()): (mg.getx()), 
     (mg.getnamey()): (mg.gety()), 
     } 

如果你看看底部我希望把它,所以我不必每次都寫了一個新的生產線,但是從上面的列表採取。這是我作爲一個例子的嘗試。

towers = [background, ppsh, trenchgun, thompson, colt, mg] 

def game_loop(): 
    for i in towers: 
     positions = { 
      (i.getnamex()): (i.getx()), 
      (i.getnamey()): (i.gety()), 
      } 

如果任何人都可以幫助它將不勝感激,我一直堅持這一段時間了。

回答

2

您可以定義一個空的字典,並根據需要添加鍵值對

def game_loop(): 
    global towers 
    positions={} 
    for i in towers: 
     positions[i.getnamex()]= i.getx() 
     positions[i.getnamey()]= i.gety() 
    return positions 

positions=game_loop()