Infinite loop due to calling functions

Viewed 58

I am attempting to make Minesweeper in python using Tkinter. I have completed all of the initial logic but I am having trouble with the squares with zero surrounding bombs. The program is meant to open all of the surrounding squares when a square with zero surrounding bombs is clicked. The problem here is that it somehow creates an infinite loop. This may be due to the fact that I am calling the function click multiple times using a for loop but I am not sure if this is correct or how to fix it. My code so far:

import tkinter as tk
from random import choices
from math import floor
##•

def openSurroundings(i):
    trash = [i+1, i+8, i+9, i+10, i-1, i-8, i-9, i-10]
    for a in trash:
        if a<81:
            click(floor(a/9), a-((a//9)*9))

def click(row, col):
    text = numbers[row][col]
    widget = buttons[row][col]
    widget.grid_forget()
    clickSurrounding = False
    if text == 0:
        text = ''
        clickSurrounding = True
    lab = tk.Label(window, text = text, height = 2, width = 5)
    lab.grid(row = row, column = col)
    if clickSurrounding == True:
        openSurroundings((row*9)+col)
    
def placeBombs():
    global widgets, bombs
    numOfBombs = 10 
    widgets = list(range(1, (len(buttons)**2)+1))
    bombs = choices(widgets, k = numOfBombs)

def findNumbers():
    global numbers
    numbers = []
    lis_num = []
    for i in widgets:
        if i in bombs:
            lis_num.append('•')
            continue
        else:
            trash = [i+1, i+8, i+9, i+10, i-1, i-8, i-9, i-10]
            num = 0
            for a in trash:
                if a > 0 and a in bombs:
                    num += 1
            lis_num.append(num)
    for i in range(0, len(lis_num), 9):
        numbers.append(lis_num[i:i + 9])

    

window = tk.Tk()
window.title('Minesweeper')
sideLen = 9 
row_index = 0
cell_index = 0
buttons = []
while row_index != sideLen:
    button_row = []
    while cell_index != sideLen:
        button = tk.Button(window, width=5, height = 2, command=lambda row_index=row_index, cell_index=cell_index: click(row_index, cell_index))
        button_row.append(button)
        button.grid(row=row_index, column=cell_index)
        cell_index += 1
    buttons.append(button_row)
    cell_index = 0
    row_index += 1

placeBombs()
findNumbers()
0 Answers
Related