import pygame
import random
pygame.init()
screen_width = 300
screen_height = 600
block_size = 30
colors = [
(0, 0, 0),
(255, 0, 0),
(0, 150, 0),
(0, 0, 255),
(255, 120, 0),
(255, 255, 0),
(180, 0, 255),
(0, 220, 220)
]
shapes = [
[[1, 1, 1, 1]],
[[1, 1, 1], [0, 1, 0]],
[[1, 1], [1, 1]],
[[0, 1, 1], [1, 1, 0]],
[[1, 1, 0], [0, 1, 1]],
[[1, 0, 0], [1, 1, 1]],
[[0, 0, 1], [1, 1, 1]]
]
grid = [[0 for _ in range(10)] for _ in range(20)]
def create_piece():
shape = random.choice(shapes)
piece = {
'shape': shape,
'color': random.randint(1, len(colors) - 1),
'x': 3,
'y': 0
}
return piece
def draw_piece(screen, piece):
shape = piece['shape']
color = colors[piece['color']]
for y, row in enumerate(shape):
for x, cell in enumerate(row):
if cell:
pygame.draw.rect(screen, color, ((piece['x'] + x) * block_size, (piece['y'] + y) * block_size, block_size, block_size))
def check_collision(grid, piece):
shape = piece['shape']
for y, row in enumerate(shape):
for x, cell in enumerate(row):
if cell:
if piece['y'] + y >= 20 or piece['x'] + x < 0 or piece['x'] + x >= 10 or grid[piece['y'] + y][piece['x'] + x]:
return True
return False
def merge_piece(grid, piece):
shape = piece['shape']
for y, row in enumerate(shape):
for x, cell in enumerate(row):
if cell:
grid[piece['y'] + y][piece['x'] + x] = piece['color']
def clear_lines(grid):
lines_cleared = 0
for y in range(20):
if all(grid[y]):
del grid[y]
grid.insert(0, [0 for _ in range(10)])
lines_cleared += 1
return lines_cleared
def main():
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("俄罗斯方块")
clock = pygame.time.Clock()
piece = create_piece()
fall_time = 0
fall_speed = 0.3
running = True
while running:
screen.fill(colors[0])
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
piece['x'] -= 1
if check_collision(grid, piece):
piece['x'] += 1
if event.key == pygame.K_RIGHT:
piece['x'] += 1
if check_collision(grid, piece):
piece['x'] -= 1
if event.key == pygame.K_DOWN:
piece['y'] += 1
if check_collision(grid, piece):
piece['y'] -= 1
if event.key == pygame.K_UP:
rotated_piece = list(zip(*reversed(piece['shape'])))
if not check_collision(grid, {'shape': rotated_piece, 'x': piece['x'], 'y': piece['y'], 'color': piece['color']}):
piece['shape'] = rotated_piece
fall_time += clock.get_rawtime()
clock.tick()
if fall_time / 1000 >= fall_speed:
fall_time = 0
piece['y'] += 1
if check_collision(grid, piece):
piece['y'] -= 1
merge_piece(grid, piece)
lines_cleared = clear_lines(grid)
piece = create_piece()
if check_collision(grid, piece):
running = False
for y in range(20):
for x in range(10):
pygame.draw.rect(screen, colors[grid[y][x]], (x * block_size, y * block_size, block_size, block_size), 0)
draw_piece(screen, piece)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()