-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
414 lines (348 loc) · 12.2 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
"""
Plan:
use numpy array to represent every square of cubes
the moving piece not in numpy array but added on
once there's sth under the moving piece, STOP
when it stop, moving piece added
then check if there's a line that can be cleared, SO CLEAR IT and move all lines
for each piece his color, color stored in dict, (e.g. {0:"yellow", 1:"red",2:"blue",3:"green", ...})
speed up in each level for dynamics
pieces:
- I
- O
- S
- Z
- L
- J
- T
Why this project:
I want to start freelancing but didn't code for 3 months, so I try to get back to coding
don't worry if it's not like the original, it would be even better !
"""
import pygame
import numpy as np
import random
import time
import sys
pygame.init()
COLORS = {
1:"blue",
2:"red",
3:"green",
4:"yellow",
5:"cyan",
6:"magenta",
7:"maroon"
}
PIECES = { #x,y
1:((-1,0),(0,0),(1,0),(2,0)), #I
#1:((-1,-1),(0,-1),(1,-1),(2,-1)), #I to test too much up
2:((0,0),(0,1),(1,0),(1,1)), #O
3:((0,0),(0,1),(1,0),(-1,1)), #S
4:((0,0),(0,1),(-1,0),(1,1)), #Z
5:((0,0),(-1,0),(1,0),(-1,1)), #L
6:((0,0),(-1,0),(1,0),(1,1)), #J
7:((0,0),(-1,0),(1,0),(0,1)) #T
#6:((0,0),(0,1),(-1,1))
}
NPIECES = tuple(PIECES.keys())
GRID_CUBE_SIZE = (10,20) #x,y
NUMBER_NEXT_PIECES = 3
DELAY_CONTROL_H = 0.1 # to go left or right
DELAY_CONTROL_V = 0.1 # to go down
CLEAR_LINES_POINTS = {
0: 0,
1:100,
2:300,
3:500,
4:800
}
LINES_CLEARED_BY_LEVEL = 10
# DESIGN SETTINGS
CUBE_SIZE = 30
GRID_POS = (CUBE_SIZE*4+20,0)
NEXT_POS=(GRID_CUBE_SIZE[0]*CUBE_SIZE+GRID_POS[0]+10, 10)
NEXT_BETWEEN_TEXT_PIECES=20
NEXT_BETWEEN_PIECES=20
HOLD_POS = (10,10)
HOLD_SPACE_TEXT_PIECES=20
HOLD_SPACE_PIECES=20
SCREEN_SIZE = ((GRID_CUBE_SIZE[0]+8)*CUBE_SIZE+40,GRID_CUBE_SIZE[1]*CUBE_SIZE)
SCORE_POS = (10,SCREEN_SIZE[1]-10)
SCORE_SPACE_PIECES=20
SCREEN_COLOR = "darkgray"
GRID_COLOR = "black"
CUBES_LIMIT_COLOR = "white"
NEXT_STYLE=pygame.font.Font(None, 24),True,"white"
SCORE_STYLE=pygame.font.Font(None, 24),True,"white"
HOLD_STYLE=pygame.font.Font(None, 24),True,"white"
##
debug_mode = hasattr(sys, 'gettrace') and sys.gettrace()
#print(sys.gettrace())
printd = print if debug_mode else lambda *x, **y:None
def render(style,text):
return style[0].render(text, *style[1:])
def flip_coords(x,y):
"""convert UI coords to numpy coords"""
return y,x
def update_speed_moving():
global speed_moving
if level<=10:
speed_moving = 1-0.1*(level-1)
else:
speed_moving = 0.05
#speed_moving = 0.5
def new_piece(setup_cpiece_id=True):
global cpiece_id, cpiece_pos, cpiece_cubes, grid, holded_used, score, lines, level, level_old
#clear lines
lines_cleared_piece = 0
for nline in range(GRID_CUBE_SIZE[1]):
if np.all(grid[nline]):
grid = np.delete(grid,nline,axis=0)
#print(cubes)
grid = np.vstack((empty_line, grid))
lines_cleared_piece += 1
#print(grid)
pass
#lines_cleared_level+=lines_cleared_piece
lines+=lines_cleared_piece
level = lines//LINES_CLEARED_BY_LEVEL + 1
if level != level_old: # that means level up
level_old = level
printd("LEVEL UP")
update_speed_moving()
score += CLEAR_LINES_POINTS[lines_cleared_piece]
if setup_cpiece_id:
cpiece_id = next_pieces.pop(0)
next_pieces.append(random.choice(NPIECES))
holded_used = False
cpiece_pos = [int(GRID_CUBE_SIZE[0])//2, 0] #x,y
cpiece_cubes = PIECES[cpiece_id]
holded_used = False
#print("w")
while True:
try:
#print(r)
if add_cpiece_to_grid(): # successful
return
else: # conflicts or piece too much up, re-check for up
cpiece_pos[1]+=1
except IndexError: # game over, verified until piece down
print("game over")
def add_cpiece_to_grid():
global cubes_w_cpiece
grid_w_cpiece_cache = grid.copy()
for cube in cpiece_cubes:
cube_pos = cpiece_pos[0]+cube[0], cpiece_pos[1]+cube[1]
printd("condition", 0<=cube_pos[0])
printd("hello", cube_pos[0])
if not (0<=cube_pos[0]<GRID_CUBE_SIZE[0] and 0<=cube_pos[1]<GRID_CUBE_SIZE[1]): # verif if it cross limits
return False
# if not 0<=cube_pos[0]<10:
# cpiece_pos[0] -= moving_h #cancel the move
if grid_w_cpiece_cache[flip_coords(*cube_pos)]: # conflicts ?
return False
grid_w_cpiece_cache[flip_coords(*cube_pos)] = cpiece_id
cubes_w_cpiece = grid_w_cpiece_cache
return True
def move_v(delta_v):
cpiece_pos[1] += delta_v
if not add_cpiece_to_grid(): # the piece finally placed
cpiece_pos[1] -= delta_v
global moving_v
moving_v = 0
global grid
grid = cubes_w_cpiece
#remove lines !
new_piece()
return True
# def adjust_cpiece_pos():
# global cpiece_pos
# while True:
# cubes_pos = []
# for cube in cpiece_cubes:
# cube_pos = cpiece_pos[0]+cube[0], cpiece_pos[1]+cube[1]
# if cube_pos[0]<0:
# cpiece_pos
# zpiece_cubes = tuple(zip(cpiece_cubes))
# cpiece_pos = (
# cpiece_pos[0] + min(zpiece_cubes[0]),
# cpiece_pos[1] + min(zpiece_cubes[1])
# )
grid = np.zeros(flip_coords(*GRID_CUBE_SIZE))
#cubes = array = np.random.randint(0, 5, size=GRID_CUBE_SIZE)
cube_surfaces = {}
pieces_surfaces = {}
for piece_id, color in COLORS.items():
cube_surface = pygame.Surface((CUBE_SIZE, CUBE_SIZE))
cube_surface.fill(color)
cube_surfaces[piece_id] = cube_surface
piece_cubes = PIECES[piece_id]
xs, ys = zip(*piece_cubes)
min_x, min_y = min(xs), min(ys)
x_dim, y_dim = max(xs)-min_x+1, max(ys)-min_y+1
piece_cubes = tuple((x-min_x,y-min_y) for x,y in piece_cubes)
pass
piece_size = (CUBE_SIZE*x_dim, CUBE_SIZE*y_dim)
piece_surface = pygame.Surface(piece_size,pygame.SRCALPHA)
piece_surface.fill((0,0,0,0))
for cube in piece_cubes:
piece_surface.blit(cube_surface, (cube[0]*CUBE_SIZE, cube[1]*CUBE_SIZE))
pieces_surfaces[piece_id] = piece_surface
screen = pygame.display.set_mode(SCREEN_SIZE)
clock = pygame.time.Clock()
pygame.mixer.init()
pygame.mixer.music.load("music.mp3")
pygame.mixer.music.play(loops=-1)
running = True
next_pieces = [random.choice(NPIECES) for _ in range(NUMBER_NEXT_PIECES)]
if 1:
pass
#next_pieces[0] = 1
score = 0
empty_line = np.zeros((1,GRID_CUBE_SIZE[0]))
next_time_moving = time.time()
next_time_moving_h = 0
next_time_moving_v = 0
moving_h = 0
moving_v = 0
holded_piece = 0
lines = 0
level_old = 0
new_piece()
next_time_moving += speed_moving
#adjust_cpiece_pos()
# Create grid_surface
grid_surface = pygame.Surface((GRID_CUBE_SIZE[0]*CUBE_SIZE, GRID_CUBE_SIZE[1]*CUBE_SIZE))
grid_surface.fill(GRID_COLOR)
for y in range(GRID_CUBE_SIZE[1]):
pygame.draw.line(
grid_surface,
CUBES_LIMIT_COLOR,
(0,y*CUBE_SIZE),
(GRID_CUBE_SIZE[0]*CUBE_SIZE,y*CUBE_SIZE),
1)
for x in range(GRID_CUBE_SIZE[0]):
pygame.draw.line(
grid_surface,
CUBES_LIMIT_COLOR,
(x*CUBE_SIZE,0),
(x*CUBE_SIZE,GRID_CUBE_SIZE[1]*CUBE_SIZE),
1)
while running:
screen.fill(SCREEN_COLOR)
screen.blit(grid_surface,GRID_POS)
# pygame.draw.line(
# screen,
# "white",
# (GRID_POS[0],CUBE_SIZE*y+GRID_POS[1]),
# (GRID_POS[1]+GRID_CUBE_SIZE[1]*CUBE_SIZE,CUBE_SIZE*y+GRID_POS[1]),
# 1)
for event in pygame.event.get():
#printd(event)
if event.type == pygame.QUIT:
running=False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
next_time_moving_h = time.time()
moving_h = -1
elif event.key == pygame.K_RIGHT:
next_time_moving_h = time.time()
moving_h = 1
elif event.key == pygame.K_DOWN:
next_time_moving_v = time.time()
moving_v = 1
elif event.key == pygame.K_UP: # turn the piece
cpiece_cubes_backup = cpiece_cubes
cpiece_cubes = tuple((cube[1], -cube[0]) for cube in cpiece_cubes)
if not add_cpiece_to_grid():
cpiece_cubes = cpiece_cubes_backup
pass
elif event.unicode == "c":
if not holded_used:
if holded_piece:
cpiece_id, holded_piece = holded_piece, cpiece_id
new_piece(setup_cpiece_id=False)
else:
holded_piece = cpiece_id
new_piece()
holded_used = True
elif event.unicode == " ": # hard drop
while not move_v(1):
score += 2
elif event.type == pygame.KEYUP:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
moving_h = 0
elif event.key == pygame.K_DOWN:
moving_v = 0
if time.time() > next_time_moving:
next_time_moving += speed_moving
move_v(1)
if moving_h and time.time() > next_time_moving_h:
next_time_moving_h += DELAY_CONTROL_H
cpiece_pos[0] += moving_h
printd(cpiece_pos)
if not add_cpiece_to_grid():
cpiece_pos[0] -= moving_h # cancel the h move
#print("hello2")
moving_h = 0
if moving_v and time.time() > next_time_moving_v: # soft drop
printd(next_time_moving_v)
next_time_moving_v += DELAY_CONTROL_V
#cpiece_pos[1] += moving_v
move_v(moving_v)
score += moving_v
for y in range(GRID_CUBE_SIZE[1]):
for x in range(GRID_CUBE_SIZE[0]):
piece_id = cubes_w_cpiece[flip_coords(x,y)]
if piece_id != 0:
cube_surface = cube_surfaces[piece_id]
screen.blit(cube_surface, (CUBE_SIZE*x+GRID_POS[0], CUBE_SIZE*y+GRID_POS[1]))
# DESIGN
surface_next = render(NEXT_STYLE,"Next")
y=NEXT_POS[1]
screen.blit(surface_next,NEXT_POS)
y+=surface_next.get_height()+NEXT_BETWEEN_TEXT_PIECES
for next_piece in next_pieces:
piece_surface=pieces_surfaces[next_piece]
screen.blit(piece_surface, (NEXT_POS[0],y))
y+=CUBE_SIZE*2+NEXT_BETWEEN_PIECES
surface_hold = render(SCORE_STYLE,"Hold")
y=HOLD_POS[1]
screen.blit(surface_hold, HOLD_POS)
if holded_piece:
y+=surface_hold.get_height()+HOLD_SPACE_TEXT_PIECES
piece_surface=pieces_surfaces[holded_piece]
screen.blit(piece_surface,(10,y))
y=SCORE_POS[1]
printd(y)
for text in (
f"Level: {level}",
f"Lines: {lines}",
f"Score: {score}",
):
surface = render(HOLD_STYLE,text)
screen.blit(surface, surface.get_rect(bottomleft=(SCORE_POS[0],y)))
y-=surface.get_height()+SCORE_SPACE_PIECES
# score_text = f"Score: {score}"
# score_surface = pygame.font.Font(None, 24).render(score_text, True, "white")
# score_rect = score_surface.get_rect(topleft=(CUBE_SIZE*GRID_CUBE_SIZE[0],0))
# screen.blit(score_surface, score_rect)
# level_text = f"Level: {level}"
# level_surface = pygame.font.Font(None, 24).render(level_text, True, "white")
# level_rect = level_surface.get_rect(topleft=(CUBE_SIZE*GRID_CUBE_SIZE[0],50))
# screen.blit(level_surface, level_rect)
# lines_surface = pygame.font.Font(None, 24).render(f"Lines cleared: {lines_cleared_total}", True, "white")
# lines_rect = lines_surface.get_rect(topleft=(CUBE_SIZE*GRID_CUBE_SIZE[0],100))
# screen.blit(lines_surface, lines_rect)
#screen.blit(pieces_surfaces[2],(0,0))
# SHOW NEXT PIECES
# for piece in next_pieces:
# piece_surface =
clock.tick(60) # fps
printd(next_pieces)
#printd("score",score,"level",level,"lines cleared total",lines_cleared_total, "speed moving",speed_moving)
#print("showed?")
pygame.display.flip()
pygame.mixer.music.stop()
pygame.quit()