Advertisement
ignacy123

saper

Jun 1st, 2024 (edited)
477
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. import tkinter as tk
  2. import random
  3.  
  4.  
  5. def create_board(size, num_mines):
  6.     board = [['0' for _ in range(size)] for _ in range(size)]
  7.     mines = 0
  8.     while mines < num_mines:
  9.         x = random.randint(0, size - 1)
  10.         y = random.randint(0, size - 1)
  11.         if board[x][y] != 'M':
  12.             board[x][y] = 'M'
  13.             mines += 1
  14.     return board
  15.  
  16.  
  17. def print_board(board):
  18.     for row in board:
  19.         print(' '.join(str(cell) for cell in row))
  20.  
  21.  
  22. def create_gui_board(root, board):
  23.     buttons = []
  24.     for i in range(len(board)):
  25.         row = []
  26.         for j in range(len(board[i])):
  27.             btn = tk.Button(root, text=' ', width=2, height=1)
  28.             btn.grid(row=i, column=j)
  29.             btn.bind('<Button-1>', lambda event, x=i, y=j: on_left_click(x, y))
  30.             btn.bind('<Button-3>', lambda event, x=i, y=j: on_right_click(x, y))
  31.             row.append(btn)
  32.         buttons.append(row)
  33.     return buttons
  34.  
  35.  
  36. def on_left_click(x, y):
  37.     if not buttons[x][y].flagged:  # Sprawdź, czy przycisk nie jest oznaczony flagą
  38.         if board[x][y] == 'M':
  39.             buttons[x][y].config(text='M', bg='red')
  40.         else:
  41.             buttons[x][y].config(text=board[x][y], state='disabled')
  42.         buttons[x][y].bind('<Button-3>', lambda event: None)  # Dezaktywuj kliknięcie prawym przyciskiem
  43.  
  44.  
  45. def on_right_click(x, y):
  46.     if buttons[x][y].flagged:
  47.         buttons[x][y].config(bg='SystemButtonFace')  # Przywróć domyślny kolor
  48.         buttons[x][y].flagged = False
  49.     else:
  50.         buttons[x][y].config(bg='orange')  # Oznacz jako flaga
  51.         buttons[x][y].flagged = True
  52.  
  53.  
  54. size = 10
  55. num_mines = 10
  56. board = create_board(size, num_mines)
  57. print_board(board)
  58.  
  59. root = tk.Tk()
  60. root.title("Saper")
  61.  
  62. buttons = create_gui_board(root, board)
  63.  
  64. # Dodanie atrybutu flagged do każdego przycisku
  65. for i in range(size):
  66.     for j in range(size):
  67.         buttons[i][j].flagged = False
  68.  
  69. root.mainloop()
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement