Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as tk
- import random
- def create_board(size, num_mines):
- board = [['0' for _ in range(size)] for _ in range(size)]
- mines = 0
- while mines < num_mines:
- x = random.randint(0, size - 1)
- y = random.randint(0, size - 1)
- if board[x][y] != 'M':
- board[x][y] = 'M'
- mines += 1
- return board
- def print_board(board):
- for row in board:
- print(' '.join(str(cell) for cell in row))
- def create_gui_board(root, board):
- buttons = []
- for i in range(len(board)):
- row = []
- for j in range(len(board[i])):
- btn = tk.Button(root, text=' ', width=2, height=1)
- btn.grid(row=i, column=j)
- btn.bind('<Button-1>', lambda event, x=i, y=j: on_left_click(x, y))
- btn.bind('<Button-3>', lambda event, x=i, y=j: on_right_click(x, y))
- row.append(btn)
- buttons.append(row)
- return buttons
- def on_left_click(x, y):
- if not buttons[x][y].flagged: # Sprawdź, czy przycisk nie jest oznaczony flagą
- if board[x][y] == 'M':
- buttons[x][y].config(text='M', bg='red')
- else:
- buttons[x][y].config(text=board[x][y], state='disabled')
- buttons[x][y].bind('<Button-3>', lambda event: None) # Dezaktywuj kliknięcie prawym przyciskiem
- def on_right_click(x, y):
- if buttons[x][y].flagged:
- buttons[x][y].config(bg='SystemButtonFace') # Przywróć domyślny kolor
- buttons[x][y].flagged = False
- else:
- buttons[x][y].config(bg='orange') # Oznacz jako flaga
- buttons[x][y].flagged = True
- size = 10
- num_mines = 10
- board = create_board(size, num_mines)
- print_board(board)
- root = tk.Tk()
- root.title("Saper")
- buttons = create_gui_board(root, board)
- # Dodanie atrybutu flagged do każdego przycisku
- for i in range(size):
- for j in range(size):
- buttons[i][j].flagged = False
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement