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.
            adjMines = 0
            if (x > 0 and y > 0) and self.isAMine[x-1][y-1]: #NW
                adjMines+=1
            if y > 0 and self.isAMine[x][y-1]: #N
                adjMines+=1
            if (x < self.x-1 and y > 0) and self.isAMine[x+1][y-1]: #NE
                adjMines+=1
            if x > 0 and self.isAMine[x-1][y]: #W
                adjMines+=1
            if x < self.x-1 and self.isAMine[x+1][y]: #E
                adjMines+=1
            if (x > 0 and y < self.y-1) and self.isAMine[x-1][y+1]: #SW
                adjMines+=1
            if y < self.y-1 and self.isAMine[x][y+1]: #S
                adjMines+=1
            if (x < self.x-1 and y < self.y-1) and self.isAMine[x+1][y+1]: #S
                adjMines+=1
            if adjMines>0:
                self.square[x][y]['text'] = adjMines

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?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.