Untitled
unknown
plain_text
a year ago
2.1 kB
13
Indexable
import tkinter as tk import random # Инициализация игрового поля def init_game(): global puzzle, empty_cell puzzle = [[i + j * 4 for i in range(1, 5)] for j in range(4)] empty_cell = (3, 3) puzzle[empty_cell[0]][empty_cell[1]] = 16 mix_puzzle() # Перемешивание игрового поля def mix_puzzle(): global puzzle, empty_cell actions = ['Up', 'Down', 'Left', 'Right'] for _ in range(1000): action = random.choice(actions) move(action) # Перемещение фишек def move(action): global puzzle, empty_cell x, y = empty_cell if action == 'Up' and x > 0: puzzle[x][y], puzzle[x - 1][y] = puzzle[x - 1][y], puzzle[x][y] empty_cell = (x - 1, y) elif action == 'Down' and x < 3: puzzle[x][y], puzzle[x + 1][y] = puzzle[x + 1][y], puzzle[x][y] empty_cell = (x + 1, y) elif action == 'Left' and y > 0: puzzle[x][y], puzzle[x][y - 1] = puzzle[x][y - 1], puzzle[x][y] empty_cell = (x, y - 1) elif action == 'Right' and y < 3: puzzle[x][y], puzzle[x][y + 1] = puzzle[x][y + 1], puzzle[x][y] empty_cell = (x, y + 1) update_puzzle() # Обновление игрового поля def update_puzzle(): for i in range(4): for j in range(4): label = tk.Label(frame, text=str(puzzle[i][j]), width=5, height=2) label.grid(row=i, column=j) # Создание графического интерфейса root = tk.Tk() root.title("Пятнашки") frame = tk.Frame(root) frame.pack() # Кнопки управления up_button = tk.Button(root, text="Вверх", command=lambda: move('Up')) up_button.pack(side=tk.LEFT) down_button = tk.Button(root, text="Вниз", command=lambda: move('Down')) down_button.pack(side=tk.LEFT) left_button = tk.Button(root, text="Влево", command=lambda: move('Left')) left_button.pack(side=tk.LEFT) right_button = tk.Button(root, text="Вправо", command=lambda: move('Right')) right_button.pack(side=tk.LEFT) # Инициализация игры init_game() root.mainloop()
Editor is loading...
Leave a Comment