Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/env python3
- from tkinter import *
- from tkinter import messagebox
- import random
- tk = Tk()
- tk.title("Пятнашки")
- tk.resizable(False, False)
- tk.bind("<Escape>", quit)
- main_frame = Frame(tk, bg="#3f3f3f", cursor="hand1", width=48*8, height=48*8, bd=10)
- main_frame.pack()
- def bones_shuffle():
- # генерация двух последовательностей: эталонной и перемешанной
- original_seq = list(range(1, 16))
- original_seq.append("*")
- vacant_position = 15
- mixed_seq = original_seq[:]
- roulette = 1, -1, 4, -4
- i = 0
- while i != 100:
- step = random.choice(roulette)
- destination = vacant_position + step
- if not (destination > 15 or destination < 0) and (abs(destination % 4 - vacant_position % 4) != 3):
- native = mixed_seq[destination]
- mixed_seq[destination] = "*"
- mixed_seq[vacant_position] = native
- vacant_position = destination
- i += 1
- return original_seq, mixed_seq, vacant_position
- def bones_put():
- # вывод поля костей-кнопок
- for i in mixed_seq:
- if i != "*":
- bone_row = mixed_seq.index(i)//4
- bone_col = mixed_seq.index(i)%4
- Button(main_frame, width=4, height=3, text=str(i)).grid(row=bone_row, column=bone_col)
- return
- def bones_move(event):
- global original_seq
- global mixed_seq
- global vacant_position
- vacant_row = vacant_position // 4
- vacant_col = vacant_position % 4
- current_pos = event.widget.grid_info()
- bone_row, bone_col = current_pos['row'], current_pos['column']
- bone_position = 4 * bone_row + bone_col
- number = mixed_seq[bone_position]
- delta_raw = abs(vacant_row - bone_row)
- delta_col = abs(vacant_col - bone_col)
- if (delta_col + delta_raw) == 1:
- event.widget.grid_forget()
- event.widget.grid(row=vacant_row, column=vacant_col)
- vacant_position, bone_position = bone_position, vacant_position
- mixed_seq[bone_position] = number
- mixed_seq[vacant_position] = "*"
- if vacant_position == 15:
- if original_seq == mixed_seq:
- if not messagebox.askyesno("Победа!", "Good for you!\nСыграешь ещё раз?"):
- quit()
- else:
- for btn in main_frame.grid_slaves():
- btn.grid_remove()
- original_seq, mixed_seq, vacant_position = bones_shuffle()
- bones_put()
- original_seq, mixed_seq, vacant_position = bones_shuffle()
- bones_put()
- main_frame.bind_class('Button', '<Button-1>', bones_move)
- tk.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement