以下是一个基于Python和Pygame的简单俄罗斯方块游戏生成代码:
```
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小
WINDOW_WIDTH = 480
WINDOW_HEIGHT = 600
BLOCK_SIZE = 30
MAP_WIDTH = 10
MAP_HEIGHT = 20
# 设置颜色
WHITE = (255, 255, 255)
GREY = (128, 128, 128)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# 设置游戏界面
surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# 设置字体
font = pygame.font.SysFont(None, 36)
# 设置方块形状
shapes = [
[(0, 0), (1, 0), (0, 1), (1, 1)], # 方块
[(0, 0), (1, 0), (2, 0), (3, 0)], # 长条形
[(0, 0), (1, 0), (2, 0), (2, 1)], # L 形
[(0, 0), (1, 0), (2, 0), (0, 1)], # 反 L 形
[(1, 0), (2, 0), (0, 1), (1, 1)], # Z 形
[(0, 0), (1, 0), (1, 1), (2, 1)], # 反 Z 形
[(0, 1), (1, 1), (2, 1), (1, 0)] # T 形
]
# 定义方块函数
class Block:
def __init__(self):
self.x = MAP_WIDTH // 2
self.y = 0
self.type = random.randint(0, len(shapes) - 1)
self.color = random.choice([RED, GREEN, BLUE, YELLOW])
# 左移方块
def left(self, grid):
if self.x > 0 and grid[self.y][self.x - 1] == -1:
self.x -= 1
return True
else:
return False
# 右移方块
def right(self, grid):
if self.x < MAP_WIDTH - 1 and grid[self.y][self.x + 1] == -1:
self.x += 1
return True
else:
return False
# 下移方块
def down(self, grid):
if self.y < MAP_HEIGHT - 1 and grid[self.y + 1][self.x] == -1:
self.y += 1
return True
else:
return False
# 旋转方块
def rotate(self, grid):
new_shape = []
for x, y in self.get_rotated_shape():
if x < 0 or x >= MAP_WIDTH or y >= MAP_HEIGHT or grid[y][x] != -1:
return False
else:
new_shape.append((x, y))
self.shape = new_shape
return True
# 获取旋转后的方块形状
def get_rotated_shape(self):
rotated_shape = []
cx, cy = self.x + 0.5, self.y + 0.5
for x, y in self.shape:
rx = (x - cx) * 0 + (y - cy) * -1 + cx
ry = (x - cx) * 1 + (y - cy) * 0 + cy
rotated_shape.append((int(rx), int(ry)))
return rotated_shape
# 绘制方块
def draw(self, surface):
for x, y in self.shape:
pygame.draw.rect(surface, self.color, (BLOCK_SIZE * (self.x + x), BLOCK_SIZE * (self.y + y), BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(surface, BLACK, (BLOCK_SIZE * (self.x + x), BLOCK_SIZE * (self.y + y), BLOCK_SIZE, BLOCK_SIZE), 2)
# 判断方块是否到达底部