下面是一个简单的俄罗斯方块游戏的Python代码示例,使用了`pygame`库来实现图形界面和游戏逻辑。
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)
COLORS = [
(0, 255, 255), # 青色
(255, 255, 0), # 黄色
(255, 165, 0), # 橙色
(0, 0, 255), # 蓝色
(0, 255, 0), # 绿色
(255, 0, 0), # 红色
(128, 0, 128) # 紫色
]
# 定义屏幕大小
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
# 定义游戏区域大小
PLAY_WIDTH = 10 # 10个方块宽
PLAY_HEIGHT = 20 # 20个方块高
# 定义形状
SHAPES = [
[[1, 1, 1, 1]], # I
[[1, 1, 1], [0, 1, 0]], # T
[[1, 1], [1, 1]], # O
[[0, 1, 1], [1, 1, 0]], # S
[[1, 1, 0], [0, 1, 1]], # Z
[[1, 0, 0], [1, 1, 1]], # J
[[0, 0, 1], [1, 1, 1]] # L
]
# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("俄罗斯方块")
# 时钟
clock = pygame.time.Clock()
# 创建游戏区域
def create_grid(locked_positions={}):
grid = [[BLACK for _ in range(PLAY_WIDTH)] for _ in range(PLAY_HEIGHT)]
for y in range(PLAY_HEIGHT):
for x in range(PLAY_WIDTH):
if (x, y) in locked_positions:
grid[y][x] = locked_positions[(x, y)]
return grid
# 绘制网格
def draw_grid(surface, grid):
for y in range(PLAY_HEIGHT):
for x in range(PLAY_WIDTH):
pygame.draw.rect(surface, grid[y][x], (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
for y in range(PLAY_HEIGHT):
pygame.draw.line(surface, GRAY, (0, y * BLOCK_SIZE), (SCREEN_WIDTH, y * BLOCK_SIZE))
for x in range(PLAY_WIDTH):
pygame.draw.line(surface, GRAY, (x * BLOCK_SIZE, 0), (x * BLOCK_SIZE, SCREEN_HEIGHT))
# 创建形状
def create_shape():
shape = random.choice(SHAPES)
color = random.choice(COLORS)
return {'shape': shape, 'color': color, 'x': PLAY_WIDTH // 2 - len(shape[0]) // 2, 'y': 0}
# 绘制形状
def draw_shape(surface, shape):
for y, row in enumerate(shape['shape']):
for x, cell in enumerate(row):
if cell:
pygame.draw.rect(surface, shape['color'], ((shape['x'] + x) * BLOCK_SIZE, (shape['y'] + y) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
# 检查碰撞
def check_collision(grid, shape):
for y, row in enumerate(shape['shape']):
for x, cell in enumerate(row):
if cell:
if shape['x'] + x < 0 or shape['x'] + x >= PLAY_WIDTH or shape['y'] + y >= PLAY_HEIGHT or grid[shape['y'] + y][shape['x'] + x] != BLACK:
return True
return False
# 合并形状到网格
def merge_shape(grid, shape):
for y, row in enumerate(shape['shape']):
for x, cell in enumerate(row):
if cell:
grid[shape['y'] + y][shape['x'] + x] = shape['color']
# 清除满行
def clear_rows(grid):
full_rows = []
for y, row in enumerate(grid):
if all(cell != BLACK for cell in row):
full_rows.append(y)
for y in full_rows:
del grid[y]
grid.insert(0, [BLACK for _ in range(PLAY_WIDTH)])
return len(full_rows)
# 主游戏循环
def main():
locked_positions = {}
grid = create_grid(locked_positions)
current_shape = create_shape()
next_shape = create_shape()
fall_time = 0
fall_speed = 0.3
score = 0
running = True
while running:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
clock.tick()
if fall_time / 1000 >= fall_speed:
fall_time = 0
current_shape['y'] += 1
if check_collision(grid, current_shape):
current_shape['y'] -= 1
merge_shape(grid, current_shape)
rows_cleared = clear_rows(grid)
score += rows_cleared * 100
current_shape = next_shape
next_shape = create_shape()
if check_collision(grid, current_shape):
running = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
current_shape['x'] -= 1
if check_collision(grid, current_shape):
current_shape['x'] += 1
if event.key == pygame.K_RIGHT:
current_shape['x'] += 1
if check_collision(grid, current_shape):
current_shape['x'] -= 1
if event.key == pygame.K_DOWN:
current_shape['y'] += 1
if check_collision(grid, current_shape):
current_shape['y'] -= 1
if event.key == pygame.K_UP:
rotated_shape = list(zip(*reversed(current_shape['shape'])))
if not check_collision(grid, {'shape': rotated_shape, 'x': current_shape['x'], 'y': current_shape['y']}):
current_shape['shape'] = rotated_shape
draw_grid(screen, grid)
draw_shape(screen, current_shape)
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
main()
```
### 代码说明:
1. **游戏区域**:游戏区域是一个10x20的网格,每个方块的大小为30x30像素。
2. **形状**:定义了7种不同的形状,每种形状由不同的方块组成。
3. **碰撞检测**:在移动或旋转形状时,会检测是否与已固定的方块或边界发生碰撞。
4. **清除行**:当一行被填满时,该行会被清除,并且上方的方块会下移。
5. **游戏结束**:当新生成的形状无法放置时,游戏结束。
### 运行代码:
1. 确保安装了`pygame`库,可以通过`pip install pygame`安装。
2. 运行代码后,游戏窗口会弹出,使用方向键控制方块的移动和旋转。
这个代码是一个简单的俄罗斯方块实现,可以根据需要进行扩展和优化。