Reputation: 1422
I am new to python and kivy, I am trying to learn python bymaking a small minesweeper game, however, I feel the logic in below code is correct, but somehow seems not to work: complete file is as follows:
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=""
The issue is the last 4 lines, when I remove the "spotted.text=""", the code is working perfect, but when I keep the text="" the code is not working any more, despite of having 11 bombs only 1 is getting detected, with out the text="", all the bombs are getting detected correctly (text="BOMB" works).
Upvotes: 1
Views: 131
Reputation: 14854
Each time spottouched()
is called, you loop through each mine and set the text accordingly. But let's say you have two bombs - let's call the bombs ['bomb-a', 'bomb-b']
.
Now you touch the button with the id 'bomb-a'
. spottouched()
loops through the mines. The first mine in the list is 'bomb-a'
- so it sets the text to "BOMB"
. Then it loops - the second mine in the list is 'bomb-b'
, so the text is set back to ""
. So the only mine which will show the "BOMB"
text is the very last mine in the list.
Try something like this instead:
def spottouched(self, spotted):
spotted.text = "BOMB" if spotted.id in self.mines else ""
Upvotes: 1