import pygame
import random
# 定义常量
GRID_SIZE = 30 # 每个小方格的像素大小
GRID_WIDTH = 10 # 游戏区域的宽度(多少个小方格)
GRID_HEIGHT = 20 # 游戏区域的高度(多少个小方格)
SCREEN_WIDTH = GRID_SIZE * GRID_WIDTH # 屏幕宽度
SCREEN_HEIGHT = GRID_SIZE * GRID_HEIGHT # 屏幕高度
FPS = 30 # 帧率
FALL_SPEED = 1 # 正常下落速度
FAST_FALL_SPEED = 20 #快速下落速度
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
# 定义方块形状
SHAPES = [
[[1, 1, 1, 1]], # I
[[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]], # L
[[0, 0, 1], [1, 1, 1]], # J
[[0, 1, 0], [1, 1, 1]], # T
]
SHAPE_COLORS = [CYAN, YELLOW, GREEN, RED, BLUE, MAGENTA, RED] #每个形状对应的颜色
# 方块类
class Block:
def __init__(self, shape):
self.shape = shape
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.x = GRID_WIDTH // 2 - len(shape[0]) // 2 # 初始位置在顶部中间
self.y = 0 # 初始位置在顶部
self.rotation = 0 #初始旋转角度为0
def rotate(self):
"""顺时针旋转方块"""
rotated_shape = list(zip(*self.shape[::-1]))
return rotated_shape
def get_rotated_shape(self):
"""获取旋转后的形状,但不实际旋转"""
rotated_shape = list(zip(*self.shape[::-1]))
return rotated_shape
def draw(self, screen):
"""绘制方块"""
for i, row in enumerate(self.shape):
for j, cell in enumerate(row):
if cell:
pygame.draw.rect(
screen,
self.color,
(
(self.x + j) * GRID_SIZE,
(self.y + i) * GRID_SIZE,
GRID_SIZE,
GRID_SIZE,
),
)
def collides(self, board, dx=0, dy=0, rotated=False):
"""检测碰撞"""
shape_to_check = self.get_rotated_shape() if rotated else self.shape
for i, row in enumerate(shape_to_check):
for j, cell in enumerate(row):
if cell:
x = self.x + j + dx
y = self.y + i + dy
if (
x < 0
or x >= GRID_WIDTH
or y >= GRID_HEIGHT
or (y >= 0 and board[y][x] != 0)
):
return True
return False
# 游戏类
class Tetris:
def __init__(self):
pygame.init()
pygame.font.init()
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("俄罗斯方块")
self.clock = pygame.time.Clock()
self.font = pygame.font.SysFont("Arial", 30) #使用Arial字体,大小为30
self.board = [[0] * GRID_WIDTH for _ in range(GRID_HEIGHT)] # 初始化游戏区域
self.current_block = self.new_block() # 创建第一个方块
self.next_block = self.new_block() #创建下一个方块
self.score = 0 #初始化分数
self.game_over = False #游戏是否结束
self.fall_speed = FALL_SPEED #初始化下降速度
def new_block(self):
"""创建一个新的随机方块"""
return Block(random.choice(SHAPES))
def hard_drop(self):
"""方块直接落到底部"""
while not self.current_block.collides(self.board, dy=1):
self.current_block.y += 1
self.lock_block()
def lock_block(self):
"""将方块锁定在游戏区域中"""
for i, row in enumerate(self.current_block.shape):
for j, cell in enumerate(row):
if cell:
x = self.current_block.x + j
y = self.current_block.y + i
self.board[y][x] = self.current_block.color # 将方块颜色信息存入board
self.clear_lines() # 检测并消除已满的行
self.current_block = self.next_block #更新当前方块为下一个方块
self.next_block = self.new_block() #创建下一个方块
if self.current_block.collides(self.board):
self.game_over = True # 如果新的方块出现时就碰撞,则游戏结束
def clear_lines(self):
"""清除已满的行"""
lines_cleared = 0 #清除的行数
for i in range(GRID_HEIGHT):
if all(self.board[i]): # 如果该行所有格子都有颜色
del self.board[i] # 删除该行
self.board.insert(0, [0] * GRID_WIDTH) # 在顶部插入一个空行
lines_cleared +=1
self.score += lines_cleared ** 2 * 100 #分数计算
def draw_grid(self):
"""绘制游戏区域网格"""
for x in range(0, SCREEN_WIDTH, GRID_SIZE):
pygame.draw.line(self.screen, GRAY, (x, 0), (x, SCREEN_HEIGHT))
for y in range(0, SCREEN_HEIGHT, GRID_SIZE):
pygame.draw.line(self.screen, GRAY, (0, y), (SCREEN_WIDTH, y))
def draw_board(self):
"""绘制游戏区域中的方块"""
for i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
if self.board[i][j]:
pygame.draw.rect(
self.screen,
self.board[i][j],
(j * GRID_SIZE, i * GRID_SIZE, GRID_SIZE, GRID_SIZE),
)
def draw_next_block(self):
"""绘制下一个方块"""
font = self.font
text = font.render("Next:", True, WHITE)
self.screen.blit(text, (SCREEN_WIDTH + 10, 10))
next_block = self.next_block
x_offset = SCREEN_WIDTH + 10
y_offset = 50
for i, row in enumerate(next_block.shape):
for j, cell in enumerate(row):
if cell:
pygame.draw.rect(
self.screen,
next_block.color,
(
x_offset + j * GRID_SIZE,
y_offset + i * GRID_SIZE,
GRID_SIZE,
GRID_SIZE,
),
)
def draw_score(self):
"""绘制分数"""
font = self.font
text = font.render("Score: " + str(self.score), True, WHITE)
self.screen.blit(text, (10, 10))
def run(self):
"""游戏主循环"""
fall_time = 0 # 记录下落时间
while True:
dt = self.clock.get_time() #获取上一帧所用的时间
fall_time += dt #累积下落时间
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if not self.current_block.collides(self.board, dx=-1):
self.current_block.x -= 1
if event.key == pygame.K_RIGHT:
if not self.current_block.collides(self.board, dx=1):
self.current_block.x += 1
if event.key == pygame.K_UP:
rotated_shape = self.current_block.get_rotated_shape()
if not self.current_block.collides(self.board, rotated=True):
self.current_block.shape = self.current_block.rotate()
if event.key == pygame.K_SPACE:
self.hard_drop() # 直接落到底部
fall_time = 0 #硬降后重置下降时间
# 长按空格加速下落
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
self.fall_speed = FAST_FALL_SPEED #加速下落
else:
self.fall_speed = FALL_SPEED #恢复正常下落速度
# 方块下落
if fall_time / 1000 >= (1 / self.fall_speed) : #下落频率取决于fall_speed
fall_time = 0 #重置下落时间
if not self.current_block.collides(self.board, dy=1):
self.current_block.y += 1
else:
self.lock_block() # 碰撞后锁定方块
# 绘制画面
self.screen.fill(BLACK) #黑色背景
self.draw_grid() #绘制网格
self.draw_board() #绘制board里的方块
self.current_block.draw(self.screen) #绘制当前方块
self.draw_next_block() #绘制下一个方块
self.draw_score() #绘制分数
# 游戏结束画面
if self.game_over:
font = pygame.font.SysFont("Arial", 60)
text = font.render("Game Over!", True, RED)
text_rect = text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
self.screen.blit(text, text_rect)
pygame.display.flip() # 刷新屏幕
self.clock.tick(FPS) # 控制帧率
if __name__ == "__main__":
game = Tetris()
game.run()