Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/python-igra-tetris/main_tkinter.py
5925 views
1
from tkinter import *
2
from tkinter import messagebox
3
from random import choice, randrange
4
from copy import deepcopy
5
import time
6
7
W, H = 10, 20
8
TILE = 45
9
GAME_RES = W * TILE, H * TILE
10
RES = 750, 940
11
FPS = 60
12
13
14
def on_closing():
15
global app_running
16
if messagebox.askokcancel("Выход из приложения", "Хотите выйти из приложения?"):
17
app_running = False
18
#tk.destroy()
19
20
21
tk = Tk()
22
app_running = True
23
tk.protocol("WM_DELETE_WINDOW", on_closing)
24
tk.title("Tetris")
25
tk.resizable(0, 0)
26
tk.wm_attributes("-topmost", 1)
27
#tk.iconbitmap("bomb-3175208_640.ico")
28
29
sc = Canvas(tk, width=RES[0], height=RES[1], bg="red", highlightthickness=0)
30
sc.pack()
31
32
33
def get_record():
34
try:
35
with open('record') as f:
36
return f.readline()
37
except FileNotFoundError:
38
with open('record', 'w') as f:
39
f.write('0')
40
return "0"
41
42
43
def set_record(record, score):
44
rec = max(int(record), score)
45
with open('record', 'w') as f:
46
f.write(str(rec))
47
48
49
game_sc = Canvas(tk, width=W*TILE+1, height=H*TILE+1, bg="yellow", highlightthickness=0)
50
game_sc.place(x=20, y=20, anchor=NW)
51
52
img_obj1 = PhotoImage(file="img/bg.png")
53
sc.create_image(0, 0, anchor=NW, image=img_obj1)
54
55
img_obj2 = PhotoImage(file="img/bg2.png")
56
game_sc.create_image(0, 0, anchor=NW, image=img_obj2)
57
58
grid = [game_sc.create_rectangle(x * TILE, y * TILE, x * TILE+TILE, y * TILE+TILE) for x in range(W) for y in range(H)]
59
60
figures_pos = [[(-1, 0), (-2, 0), (0, 0), (1, 0)],
61
[(0, -1), (-1, -1), (-1, 0), (0, 0)],
62
[(-1, 0), (-1, 1), (0, 0), (0, -1)],
63
[(0, 0), (-1, 0), (0, 1), (-1, -1)],
64
[(0, 0), (0, -1), (0, 1), (-1, -1)],
65
[(0, 0), (0, -1), (0, 1), (1, -1)],
66
[(0, 0), (0, -1), (0, 1), (-1, 0)]]
67
68
figures = [[[x + W // 2, y + 1, 1, 1] for x, y in fig_pos] for fig_pos in figures_pos]
69
#figure_rect = pygame.Rect(0, 0, TILE - 2, TILE - 2)
70
field = [[0 for i in range(W)] for j in range(H)]
71
72
anim_count, anim_speed, anim_limit = 0, 60, 2000
73
74
score, lines = 0, 0
75
scores = {0: 0, 1: 100, 2: 300, 3: 700, 4: 1500}
76
record = "0"
77
78
sc.create_text(505, 30,text="TETRIS", font=("WiGuru 2", 50),fill="red", anchor=NW)
79
sc.create_text(535, 780,text="score:", font=("WiGuru 2", 35),fill="white", anchor=NW)
80
_score = sc.create_text(550, 840,text=str(score), font=("WiGuru 2", 35),fill="white", anchor=NW)
81
sc.create_text(525, 650,text="record:", font=("WiGuru 2", 35),fill="white", anchor=NW)
82
_record = sc.create_text(550, 710,text=record, font=("WiGuru 2", 35),fill="gold", anchor=NW)
83
84
get_color = lambda : (randrange(30, 256), randrange(30, 256), randrange(30, 256))
85
86
figure, next_figure = deepcopy(choice(figures)), deepcopy(choice(figures))
87
color, next_color = get_color(), get_color()
88
89
def rgb_to_hex(rgb):
90
return '#%02x%02x%02x' % rgb
91
92
93
# # draw figure
94
# for i in range(4):
95
# figure_rect_x = figure[i][0] * TILE
96
# figure_rect_y = figure[i][1] * TILE
97
# game_sc.create_rectangle(figure_rect_x, figure_rect_y, figure_rect_x + TILE, figure_rect_y + TILE, fill=rgb_to_hex(color))
98
#
99
# # draw next figure
100
# for i in range(4):
101
# figure_rect_x = next_figure[i][0] * TILE + 380
102
# figure_rect_y = next_figure[i][1] * TILE + 185
103
# sc.create_rectangle(figure_rect_x, figure_rect_y, figure_rect_x + TILE, figure_rect_y + TILE,
104
# fill=rgb_to_hex(next_color))
105
#
106
# for item in grid:
107
# game_sc.itemconfigure(item, fill=rgb_to_hex(get_color()))
108
#
109
# for item in grid:
110
# game_sc.itemconfigure(item, fill="")
111
112
113
def check_borders():
114
if figure[i][0] < 0 or figure[i][0] > W - 1:
115
return False
116
elif figure[i][1] > H - 1 or field[figure[i][1]][figure[i][0]]:
117
return False
118
return True
119
120
121
def move_obj(event):
122
global rotate, anim_limit, dx
123
if event.keysym == 'Up':
124
rotate = True
125
elif event.keysym == 'Down':
126
anim_limit = 100
127
elif event.keysym == 'Left':
128
dx = -1
129
elif event.keysym == 'Right':
130
dx = 1
131
132
game_sc.bind_all("<KeyPress-Up>",move_obj)
133
game_sc.bind_all("<KeyPress-Down>",move_obj)
134
game_sc.bind_all("<KeyPress-Left>",move_obj)
135
game_sc.bind_all("<KeyPress-Right>",move_obj)
136
137
dx, rotate = 0, False
138
while app_running:
139
if app_running:
140
record = get_record()
141
# move x
142
figure_old = deepcopy(figure)
143
for i in range(4):
144
figure[i][0] += dx
145
if not check_borders():
146
figure = deepcopy(figure_old)
147
break
148
# move y
149
anim_count += anim_speed
150
if anim_count > anim_limit:
151
anim_count = 0
152
figure_old = deepcopy(figure)
153
for i in range(4):
154
figure[i][1] += 1
155
if not check_borders():
156
for i in range(4):
157
field[figure_old[i][1]][figure_old[i][0]] = color
158
figure, color = next_figure, next_color
159
next_figure, next_color = deepcopy(choice(figures)), get_color()
160
anim_limit = 2000
161
break
162
# rotate
163
center = figure[0]
164
figure_old = deepcopy(figure)
165
if rotate:
166
for i in range(4):
167
x = figure[i][1] - center[1]
168
y = figure[i][0] - center[0]
169
figure[i][0] = center[0] - x
170
figure[i][1] = center[1] + y
171
if not check_borders():
172
figure = deepcopy(figure_old)
173
break
174
# check lines
175
line, lines = H - 1, 0
176
for row in range(H - 1, -1, -1):
177
count = 0
178
for i in range(W):
179
if field[row][i]:
180
count += 1
181
field[line][i] = field[row][i]
182
if count < W:
183
line -= 1
184
else:
185
anim_speed += 3
186
lines += 1
187
# compute score
188
score += scores[lines]
189
190
fig = []
191
# draw figure
192
for i in range(4):
193
figure_rect_x = figure[i][0] * TILE
194
figure_rect_y = figure[i][1] * TILE
195
fig.append(game_sc.create_rectangle(figure_rect_x, figure_rect_y, figure_rect_x + TILE, figure_rect_y + TILE, fill=rgb_to_hex(color)))
196
197
# draw field
198
for y, raw in enumerate(field):
199
for x, col in enumerate(raw):
200
if col:
201
figure_rect_x, figure_rect_y = x * TILE, y * TILE
202
fig.append(game_sc.create_rectangle(figure_rect_x, figure_rect_y, figure_rect_x + TILE,
203
figure_rect_y + TILE, fill=rgb_to_hex(col)))
204
205
fig2 = []
206
# draw next figure
207
for i in range(4):
208
figure_rect_x = next_figure[i][0] * TILE + 380
209
figure_rect_y = next_figure[i][1] * TILE + 185
210
fig2.append(sc.create_rectangle(figure_rect_x, figure_rect_y, figure_rect_x + TILE, figure_rect_y + TILE,
211
fill=rgb_to_hex(next_color)))
212
# draw titles
213
sc.itemconfigure(_score, text=str(score))
214
sc.itemconfigure(_record, text=record)
215
216
# game over
217
for i in range(W):
218
if field[0][i]:
219
set_record(record, score)
220
field = [[0 for i in range(W)] for i in range(H)]
221
anim_count, anim_speed, anim_limit = 0, 60, 2000
222
score = 0
223
for item in grid:
224
game_sc.itemconfigure(item, fill=rgb_to_hex(get_color()))
225
time.sleep(0.005)
226
tk.update_idletasks()
227
tk.update()
228
229
for item in grid:
230
game_sc.itemconfigure(item, fill="")
231
232
233
dx, rotate = 0, False
234
tk.update_idletasks()
235
tk.update()
236
for id_fig in fig: game_sc.delete(id_fig)
237
for id_fig in fig2: sc.delete(id_fig)
238
time.sleep(0.005)
239
240
tk.destroy()
241
#tk.mainloop()
242
243