我是python和kivy的新手,我试图通过制作一个小型扫雷游戏来学习python,但是,我觉得下面代码中的逻辑是正确的,但不知何故似乎不起作用:完整文件如下:
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
import random
class spot(Button):
'''
classdocs
'''
def __init__(self, **kwargs):
'''
Constructor
'''
super(spot,self).__init__(**kwargs)
self.ismine=False
self.text="X"
if 'id' in kwargs:
self.id=kwargs['id']
#else:
# self.text="X"
class minesholder(GridLayout):
def __init__(self,**kwargs):
super(minesholder,self).__init__(**kwargs)
class game(BoxLayout):
spots={}
mines=[]
def __init__(self,**kwargs):
super(game,self).__init__(**kwargs)
self.m=minesholder(rows=5, cols=5)
self.add_widget(self.m)
self.attachtogrid()
def attachtogrid(self):
self.m.clear_widgets()
self.spots.clear()
for r in range(0,5):
for c in range(0,5):
idd=str(r)+","+str(c)
self.spots[idd]=idd
s = spot(id=idd)
self.m.add_widget(s)
s.bind(on_press=self.spottouched)
print(idd)
self.createmines()
def createmines(self):
self.mines.clear()
count=0
while (count <= 10):
c=str(random.randint(0,4))+','+str(random.randint(0,4))
print(c)
if self.mines.count(c)==0:
self.mines.append(c)
count+=1
def spottouched(self,spotted):
#if self.mines.count(str(spotted.id))==1:
# spotted.text="BOMB"
#else: spotted.text=""
for k in self.mines:
if k==spotted.id: spotted.text="BOMB"
else:
spotted.text=""
问题是最后 4 行,当我删除“spotted.text=""”时,代码工作完美,但是当我保留 text=""时,代码不再工作,尽管有11 个炸弹中只有 1 个被检测到,如果没有 text="",所有炸弹都会被正确检测到(text="BOMB"有效)。
最佳答案
每次调用 spottouched()
时,您都会循环遍历每个地雷并相应地设置文本。但是,假设您有两个炸弹 - 我们将这些炸弹称为['bomb-a', 'bomb-b']
。
现在您触摸 ID 为'bomb-a'
的按钮。 spottouched()
循环遍历地雷。列表中的第一个地雷是 'bomb-a'
- 因此它将文本设置为 "BOMB"
。然后它循环 - 列表中的第二个地雷是 'bomb-b'
,因此文本设置回 ""
。因此,唯一会显示“BOMB”
文本的地雷是列表中的最后一个地雷。
尝试这样的事情:
def spottouched(self, spotted):
spotted.text = "BOMB" if spotted.id in self.mines else ""
关于python - kivy按钮文本=""逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24460217/