【发布时间】:2019-08-15 00:59:32
【问题描述】:
我是 python 新手,并且是自学的。我正在尝试制作一个名为“Mines”的简化扫雷游戏。这个游戏有一个 5 x 5 的按钮网格,带有随机数量的地雷。一切正常,除了一个问题。单击安全空间后,该按钮应被禁用,因此您无法获得更多积分。使用我的代码,我不知道该怎么做。
我已经尝试调用一个方法来禁用按钮,以及使用 DISABLED 命令。都没有奏效。我希望单击后禁用“白色”按钮,因为这些是安全空间。在理想情况下,我会在单击按钮时调用 disable() 方法并使用该方法禁用该按钮。
##Create the canvas of the board.
window = Tk ()
window.title("Mines Game")
window.geometry('819x655')
##Scoring function. The first box clicked awards 1 point, and after that each box is worth double your total points.
def score():
global scores
if (scores == 0):
scores = scores + 1
print ("Safe space hit! You have " + str(scores) + " point.")
else:
scores = scores * 2
print ("Safe space hit! You have " + str(scores) + " points.")
def squares():
##Main method of creating a 5x5 square of buttons.
global scores
scores = 0
less_bombs = True
r = -1
c = 0
x = 0
if less_bombs:
for i in range(5):
r = r + 1
for l in range(5):
y = randint(0,25)
if x == 5:
y = 10
if y < 6:
btn = Button(window, bg = "red", command=end)
btn.grid(column = c,row = r)
#btn.grid(sticky="nesw")
btn.config(height = 8, width = 22)
x = x + 1
else:
btn = Button(window, bg = "white", command=lambda:[score(),DISABLED])
btn.grid(column = c,row = r)
#btn.grid(sticky="nesw")
btn.config(height = 8, width = 22)
c = c + 1
c = 0
def end():
##This method creates the popup after you click a mine.
end = Tk ()
end.title ('Game Over!')
end.geometry ('300x161')
btn = Button(end, text ="Close game", command=close)
btn.grid(column = 0,row = 0)
#btn.grid(sticky="nesw")
btn.config(height = 10, width = 20)
btn = Button(end, text ="Reset game", command=lambda:[reset(),end.destroy()])
btn.grid(column = 1,row = 0)
#btn.grid(sticky="nesw"
btn.config(height = 10, width = 20)
if (scores == 1):
print ("Game over! You hit a mine :(")
print ("Your score for that game was " + str(scores) + " point.")
if (scores != 1):
print ("Game over! You hit a mine :(")
print ("Your score for that game was " + str(scores) + " points.")
def disable():
pass
def close():
sys.exit()
def reset():
squares()
squares()
window.mainloop()
我希望按钮在被点击后被禁用,但目前玩家可以根据需要多次点击按钮。
【问题讨论】:
-
我认为您的问题已经在这里提出并回答了stackoverflow.com/questions/16046743/…
-
除非我实施错误,否则这不是我的解决方案。我不仅试图反其道而行之,而且还试图禁用 25 个按钮中的一个。