Path: blob/master/python-igra-tetris/main_tkinter.py
5925 views
from tkinter import *1from tkinter import messagebox2from random import choice, randrange3from copy import deepcopy4import time56W, H = 10, 207TILE = 458GAME_RES = W * TILE, H * TILE9RES = 750, 94010FPS = 60111213def on_closing():14global app_running15if messagebox.askokcancel("Выход из приложения", "Хотите выйти из приложения?"):16app_running = False17#tk.destroy()181920tk = Tk()21app_running = True22tk.protocol("WM_DELETE_WINDOW", on_closing)23tk.title("Tetris")24tk.resizable(0, 0)25tk.wm_attributes("-topmost", 1)26#tk.iconbitmap("bomb-3175208_640.ico")2728sc = Canvas(tk, width=RES[0], height=RES[1], bg="red", highlightthickness=0)29sc.pack()303132def get_record():33try:34with open('record') as f:35return f.readline()36except FileNotFoundError:37with open('record', 'w') as f:38f.write('0')39return "0"404142def set_record(record, score):43rec = max(int(record), score)44with open('record', 'w') as f:45f.write(str(rec))464748game_sc = Canvas(tk, width=W*TILE+1, height=H*TILE+1, bg="yellow", highlightthickness=0)49game_sc.place(x=20, y=20, anchor=NW)5051img_obj1 = PhotoImage(file="img/bg.png")52sc.create_image(0, 0, anchor=NW, image=img_obj1)5354img_obj2 = PhotoImage(file="img/bg2.png")55game_sc.create_image(0, 0, anchor=NW, image=img_obj2)5657grid = [game_sc.create_rectangle(x * TILE, y * TILE, x * TILE+TILE, y * TILE+TILE) for x in range(W) for y in range(H)]5859figures_pos = [[(-1, 0), (-2, 0), (0, 0), (1, 0)],60[(0, -1), (-1, -1), (-1, 0), (0, 0)],61[(-1, 0), (-1, 1), (0, 0), (0, -1)],62[(0, 0), (-1, 0), (0, 1), (-1, -1)],63[(0, 0), (0, -1), (0, 1), (-1, -1)],64[(0, 0), (0, -1), (0, 1), (1, -1)],65[(0, 0), (0, -1), (0, 1), (-1, 0)]]6667figures = [[[x + W // 2, y + 1, 1, 1] for x, y in fig_pos] for fig_pos in figures_pos]68#figure_rect = pygame.Rect(0, 0, TILE - 2, TILE - 2)69field = [[0 for i in range(W)] for j in range(H)]7071anim_count, anim_speed, anim_limit = 0, 60, 20007273score, lines = 0, 074scores = {0: 0, 1: 100, 2: 300, 3: 700, 4: 1500}75record = "0"7677sc.create_text(505, 30,text="TETRIS", font=("WiGuru 2", 50),fill="red", anchor=NW)78sc.create_text(535, 780,text="score:", font=("WiGuru 2", 35),fill="white", anchor=NW)79_score = sc.create_text(550, 840,text=str(score), font=("WiGuru 2", 35),fill="white", anchor=NW)80sc.create_text(525, 650,text="record:", font=("WiGuru 2", 35),fill="white", anchor=NW)81_record = sc.create_text(550, 710,text=record, font=("WiGuru 2", 35),fill="gold", anchor=NW)8283get_color = lambda : (randrange(30, 256), randrange(30, 256), randrange(30, 256))8485figure, next_figure = deepcopy(choice(figures)), deepcopy(choice(figures))86color, next_color = get_color(), get_color()8788def rgb_to_hex(rgb):89return '#%02x%02x%02x' % rgb909192# # draw figure93# for i in range(4):94# figure_rect_x = figure[i][0] * TILE95# figure_rect_y = figure[i][1] * TILE96# game_sc.create_rectangle(figure_rect_x, figure_rect_y, figure_rect_x + TILE, figure_rect_y + TILE, fill=rgb_to_hex(color))97#98# # draw next figure99# for i in range(4):100# figure_rect_x = next_figure[i][0] * TILE + 380101# figure_rect_y = next_figure[i][1] * TILE + 185102# sc.create_rectangle(figure_rect_x, figure_rect_y, figure_rect_x + TILE, figure_rect_y + TILE,103# fill=rgb_to_hex(next_color))104#105# for item in grid:106# game_sc.itemconfigure(item, fill=rgb_to_hex(get_color()))107#108# for item in grid:109# game_sc.itemconfigure(item, fill="")110111112def check_borders():113if figure[i][0] < 0 or figure[i][0] > W - 1:114return False115elif figure[i][1] > H - 1 or field[figure[i][1]][figure[i][0]]:116return False117return True118119120def move_obj(event):121global rotate, anim_limit, dx122if event.keysym == 'Up':123rotate = True124elif event.keysym == 'Down':125anim_limit = 100126elif event.keysym == 'Left':127dx = -1128elif event.keysym == 'Right':129dx = 1130131game_sc.bind_all("<KeyPress-Up>",move_obj)132game_sc.bind_all("<KeyPress-Down>",move_obj)133game_sc.bind_all("<KeyPress-Left>",move_obj)134game_sc.bind_all("<KeyPress-Right>",move_obj)135136dx, rotate = 0, False137while app_running:138if app_running:139record = get_record()140# move x141figure_old = deepcopy(figure)142for i in range(4):143figure[i][0] += dx144if not check_borders():145figure = deepcopy(figure_old)146break147# move y148anim_count += anim_speed149if anim_count > anim_limit:150anim_count = 0151figure_old = deepcopy(figure)152for i in range(4):153figure[i][1] += 1154if not check_borders():155for i in range(4):156field[figure_old[i][1]][figure_old[i][0]] = color157figure, color = next_figure, next_color158next_figure, next_color = deepcopy(choice(figures)), get_color()159anim_limit = 2000160break161# rotate162center = figure[0]163figure_old = deepcopy(figure)164if rotate:165for i in range(4):166x = figure[i][1] - center[1]167y = figure[i][0] - center[0]168figure[i][0] = center[0] - x169figure[i][1] = center[1] + y170if not check_borders():171figure = deepcopy(figure_old)172break173# check lines174line, lines = H - 1, 0175for row in range(H - 1, -1, -1):176count = 0177for i in range(W):178if field[row][i]:179count += 1180field[line][i] = field[row][i]181if count < W:182line -= 1183else:184anim_speed += 3185lines += 1186# compute score187score += scores[lines]188189fig = []190# draw figure191for i in range(4):192figure_rect_x = figure[i][0] * TILE193figure_rect_y = figure[i][1] * TILE194fig.append(game_sc.create_rectangle(figure_rect_x, figure_rect_y, figure_rect_x + TILE, figure_rect_y + TILE, fill=rgb_to_hex(color)))195196# draw field197for y, raw in enumerate(field):198for x, col in enumerate(raw):199if col:200figure_rect_x, figure_rect_y = x * TILE, y * TILE201fig.append(game_sc.create_rectangle(figure_rect_x, figure_rect_y, figure_rect_x + TILE,202figure_rect_y + TILE, fill=rgb_to_hex(col)))203204fig2 = []205# draw next figure206for i in range(4):207figure_rect_x = next_figure[i][0] * TILE + 380208figure_rect_y = next_figure[i][1] * TILE + 185209fig2.append(sc.create_rectangle(figure_rect_x, figure_rect_y, figure_rect_x + TILE, figure_rect_y + TILE,210fill=rgb_to_hex(next_color)))211# draw titles212sc.itemconfigure(_score, text=str(score))213sc.itemconfigure(_record, text=record)214215# game over216for i in range(W):217if field[0][i]:218set_record(record, score)219field = [[0 for i in range(W)] for i in range(H)]220anim_count, anim_speed, anim_limit = 0, 60, 2000221score = 0222for item in grid:223game_sc.itemconfigure(item, fill=rgb_to_hex(get_color()))224time.sleep(0.005)225tk.update_idletasks()226tk.update()227228for item in grid:229game_sc.itemconfigure(item, fill="")230231232dx, rotate = 0, False233tk.update_idletasks()234tk.update()235for id_fig in fig: game_sc.delete(id_fig)236for id_fig in fig2: sc.delete(id_fig)237time.sleep(0.005)238239tk.destroy()240#tk.mainloop()241242243