尝试在Tkinter中构建风险风格游戏

时间:2016-12-19 19:13:38

标签: python-3.x tkinter

我一直在尝试用Python建立自己的技能,并且正在尝试创建风险游戏。

我正在努力掌握课程和Tkinter,我现在并不是很远。

我的第一个尝试是创建一系列按钮来取代不同的国家。然后,我希望这些按钮在点击时更新国家/地区的军队数量。

到目前为止,我已经能够从我创建的类中生成地图并且按钮是可点击的。单击按钮时,它会更新军队数量,但总是为最后一个按钮。

如何获取它以便我点击按钮更新而不是最后一个按钮?

我是否以完全错误的方式解决了这个问题?

from tkinter import *
import random

class territory:
   def __init__ (self, country, player = "1", current_armies = 0, x=0, y=0):
        self.country = country
        self.current_armies = current_armies
        self.player = player
        self.y = y
        self.x = x

    def get_armies(self):
        print(self.country + " has " + str( self.current_armies)+ " armies.")

    def add_armies (self, armies):
        self.current_armies += armies

    def roll_dice (self, dice=1):
        rolls = []
        for i in range(0, dice):
            rolls.append(random.randint(1,6))
        rolls.sort()
        rolls.reverse()
        print (self.country + " has rolled " + str(rolls))
        return rolls

    def owner(self):
        print (self.country + " is owned by " + self.player)

    def get_country(self):
        print(country)

    def button (self):
        Button(window, text = territories[0].current_armies, width = 10, command =        click1(territories, 0)).grid(row=y,column=x)

window = Tk()

def create_territories():
    countries = ["UK", "GER", "SPA", "RUS"]
    terr_pos = [[1,0],[2,0],[1,5],[4,1]]
    sta_arm = [1,1,1,1]
    terr = []
    player = "1"
    for i in range(len(countries)):

        terr.append(territory(countries[i],player, sta_arm [i] , terr_pos[i][0],terr_pos[i][1]))
        if player == "1":
            player = "2"
        else:
            player = "1"
    return terr

def click1(territory, i):
    territory[i].current_armies += 1
    build_board(territory)


def build_board(territories):
     for i in range(0,4):
        Button(window, text = territories[i].country+"\n"+str(territories[i].current_armies), width = 10, command = lambda: click1(territories, i)).grid(row=territories[i].y,column=territories[i].x)

territories = create_territories()




window.title ("Domination")
create_territories()
build_board(territories)

window.mainloop()

1 个答案:

答案 0 :(得分:0)

在您的def button(self):...中,您始终引用territories[0]

Button(window, text=territories[0].current_armies,... command=click1(territories, 0)...

因此,您始终使用第一个区域作为参考,因此您应该使用territories[]中的索引初始化每个区域,以便将其传递到Button构造函数中。

关于“完全错误的方式”的问题,我个人会将此问题发送给CodeReview,因为这更多是他们的域名(我们修复了损坏的代码,他们会解决有臭味的代码),尽管有显着重叠。但是,我们确实更喜欢每个问题一个问题,并且“这整件事情是错的吗?”对StackOverflow来说有点宽泛。