I'm trying to code the game of Minesweeper. I haven't put in graphics just yet, only text labels on the buttons.

Here is my create_widgets method:

``````def create_widgets(self):
#Create the grid.
self.square = []
self.isAMine = []
for i in range(self.y):
row = []
mineRow = []
for j in range(self.x):
row.append(Button(self, width = 3))
row[j].grid(row = j + OFFSET, column = i)
mineRow.append(False)
self.square.append(row)
self.isAMine.append(mineRow)

#Plant the mines.
for i in range(self.mines):
mineSquare = random.randrange(self.x * self.y)
mine_y = mineSquare / self.x
mine_x = mineSquare % self.x
self.isAMine[mine_x][mine_y] = True
self.square[mine_x][mine_y]['text'] = 'X' #temp line; shows mines

for i in range(self.y):
for j in range(self.x):
self.square[i][j]['command'] = self.hit(i, j)

#Runs when a button (square) is clicked.
def hit(self, x, y):
if self.isAMine[x][y]:
print 'Mine found.  Location:', x, y
else:
#Look at all eight neighbors and see if they are mines.
#x>0, etc. avoid looking off the edge of the map.
if (x > 0 and y > 0) and self.isAMine[x-1][y-1]: #NW
if y > 0 and self.isAMine[x][y-1]: #N
if (x < self.x-1 and y > 0) and self.isAMine[x+1][y-1]: #NE
if x > 0 and self.isAMine[x-1][y]: #W
if x < self.x-1 and self.isAMine[x+1][y]: #E
if (x > 0 and y < self.y-1) and self.isAMine[x-1][y+1]: #SW
if y < self.y-1 and self.isAMine[x][y+1]: #S
if (x < self.x-1 and y < self.y-1) and self.isAMine[x+1][y+1]: #S

The catch is that hit() runs for *every single square*, regardless of whether I actually click on it. How do I get it to wait until it's actually clicked?

2
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by toll_booth

This is where you run hit() for every square.

``````for i in range(self.y):
for j in range(self.x):
self.square[i][j]['command'] = self.hit(i, j)``````

Print i and j if you want to check it. Also, self.hit(i, j) does not return anything so self.square[j] will always be 'None'.

Hmm. How do I get the buttons to wait to execute hit() until they are selected, then?

I got it. Figured out how to use lambda.