Tetris Pyrhon
Tetris Pyrhon
import random
pygame.init()
SHAPES = [
[[1, 1, 1, 1]],
[[1, 1], [1, 1]],
[[1, 1, 1], [0, 1, 0]],
[[1, 1, 1], [1, 0, 0]],
[[1, 1, 1], [0, 0, 1]],
[[1, 1, 0], [0, 1, 1]],
[[0, 1, 1], [1, 1, 0]]
]
clock = pygame.time.Clock()
def new_block():
shape = random.choice(SHAPES)
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0,
255))
block = {
'shape': shape,
'color': color,
'x': WIDTH // 2 - len(shape[0]) * GRID_SIZE // 2,
'y': 0
}
return block
def draw_block(block):
for row in range(len(block['shape'])):
for col in range(len(block['shape'][0])):
if block['shape'][row][col] == 1:
pygame.draw.rect(screen, block['color'], (block['x'] + col *
GRID_SIZE, block['y'] + row * GRID_SIZE, GRID_SIZE, GRID_SIZE))
pygame.draw.rect(screen, WHITE, (block['x'] + col * GRID_SIZE,
block['y'] + row * GRID_SIZE, GRID_SIZE, GRID_SIZE), 2)
def main():
running = True
current_block = new_block()
grid = [[False] * (WIDTH // GRID_SIZE) for _ in range(HEIGHT // GRID_SIZE)]
block_fallen = False
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and not block_fallen:
if event.key == pygame.K_LEFT and current_block['x'] > 0:
current_block['x'] -= GRID_SIZE
elif event.key == pygame.K_RIGHT and current_block['x'] < WIDTH -
len(current_block['shape'][0]) * GRID_SIZE:
current_block['x'] += GRID_SIZE
elif event.key == pygame.K_DOWN and current_block['y'] < HEIGHT -
len(current_block['shape']) * GRID_SIZE:
current_block['y'] += GRID_SIZE
if not block_fallen:
if current_block['y'] < HEIGHT - len(current_block['shape']) *
GRID_SIZE:
current_block['y'] += fall_speed
else:
block_fallen = True
draw_block(current_block)
pygame.display.flip()
screen.fill(BLACK)
clock.tick(FPS)
pygame.quit()
if __name__ == "__main__":
main()