Skip to content
The Chat Archive
grok-3-preview-02-24· xAI LMArena Human Preference 140K

用python写一个俄罗斯方块游戏,控制键为上下左右箭头,如果长按空格键,积木方块直接掉到底下

  1. User

    用python写一个俄罗斯方块游戏,控制键为上下左右箭头,如果长按空格键,积木方块直接掉到底下

  2. Assistant

    下面是一个使用 Python 和 Pygame 库实现的俄罗斯方块游戏代码。这个实现包含了基本的俄罗斯方块功能,包括方块移动、旋转、加速下落以及得分系统。

    import pygame
    import random
    
    # 初始化 Pygame
    pygame.init()
    
    # 定义颜色
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    CYAN = (0, 255, 255)
    YELLOW = (255, 255, 0)
    MAGENTA = (255, 0, 255)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    ORANGE = (255, 165, 0)
    
    # 游戏窗口设置
    BLOCK_SIZE = 30
    GRID_WIDTH = 10
    GRID_HEIGHT = 20
    SCREEN_WIDTH = BLOCK_SIZE * (GRID_WIDTH + 6)
    SCREEN_HEIGHT = BLOCK_SIZE * GRID_HEIGHT
    
    # 创建游戏窗口
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("俄罗斯方块")
    
    # 定义方块形状
    SHAPES = [
        [[1, 1, 1, 1]],  # I
        [[1, 1], [1, 1]],  # O
        [[1, 1, 1], [0, 1, 0]],  # T
        [[1, 1, 1], [1, 0, 0]],  # L
        [[1, 1, 1], [0, 0, 1]],  # J
        [[1, 1, 0], [0, 1, 1]],  # S
        [[0, 1, 1], [1, 1, 0]]   # Z
    ]
    
    # 方块颜色
    COLORS = [CYAN, YELLOW, MAGENTA, ORANGE, BLUE, GREEN, RED]
    
    class Tetris:
        def __init__(self):
            self.grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
            self.current_piece = self.new_piece()
            self.game_over = False
            self.score = 0
            self.clock = pygame.time.Clock()
            self.fall_time = 0
            self.fall_speed = 500  # 每500ms下落一格
    
        def new_piece(self):
            # 随机选择一个方块形状
            shape_idx = random.randint(0, len(SHAPES) - 1)
            return {
                'shape': SHAPES[shape_idx],
                'color': COLORS[shape_idx],
                'x': GRID_WIDTH // 2 - len(SHAPES[shape_idx][0]) // 2,
                'y': 0
            }
    
        def valid_move(self, piece, x, y):
            for i in range(len(piece['shape'])):
                for j in range(len(piece['shape'][0])):
                    if piece['shape'][i][j]:
                        new_x = x + j
                        new_y = y + i
                        if (new_x < 0 or new_x >= GRID_WIDTH or 
                            new_y >= GRID_HEIGHT or 
                            (new_y >= 0 and self.grid[new_y][new_x])):
                            return False
            return True
    
        def merge_piece(self):
            for i in range(len(self.current_piece['shape'])):
                for j in range(len(self.current_piece['shape'][0])):
                    if self.current_piece['shape'][i][j]:
                        self.grid[self.current_piece['y'] + i][self.current_piece['x'] + j] = self.current_piece['color']
            self.clear_lines()
            self.current_piece = self.new_piece()
            if not self.valid_move(self.current_piece, self.current_piece['x'], self.current_piece['y']):
                self.game_over = True
    
        def clear_lines(self):
            lines_cleared = 0
            for i in range(GRID_HEIGHT):
                if all(self.grid[i]):
                    del self.grid[i]
                    self.grid.insert(0, [0 for _ in range(GRID_WIDTH)])
                    lines_cleared += 1
            self.score += lines_cleared * 100
    
        def rotate_piece(self):
            # 旋转方块
            piece = self.current_piece
            rotated_shape = list(zip(*piece['shape'][::-1]))
            rotated_shape = [list(row) for row in rotated_shape]
            old_shape = piece['shape']
            piece['shape'] = rotated_shape
            if not self.valid_move(piece, piece['x'], piece['y']):
                piece['shape'] = old_shape
    
        def drop_piece(self):
            # 方块直接掉到底部
            piece = self.current_piece
            while self.valid_move(piece, piece['x'], piece['y'] + 1):
                piece['y'] += 1
            self.merge_piece()
    
        def run(self):
            running = True
            while running:
                self.fall_time += self.clock.get_rawtime()
                self.clock.tick()
    
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        running = False
                    elif event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_LEFT:
                            if self.valid_move(self.current_piece, self.current_piece['x'] - 1, self.current_piece['y']):
                                self.current_piece['x'] -= 1
                        elif event.key == pygame.K_RIGHT:
                            if self.valid_move(self.current_piece, self.current_piece['x'] + 1, self.current_piece['y']):
                                self.current_piece['x'] += 1
                        elif event.key == pygame.K_DOWN:
                            if self.valid_move(self.current_piece, self.current_piece['x'], self.current_piece['y'] + 1):
                                self.current_piece['y'] += 1
                        elif event.key == pygame.K_UP:
                            self.rotate_piece()
                        elif event.key == pygame.K_SPACE:
                            self.drop_piece()
    
                if self.fall_time >= self.fall_speed:
                    self.fall_time = 0
                    if self.valid_move(self.current_piece, self.current_piece['x'], self.current_piece['y'] + 1):
                        self.current_piece['y'] += 1
                    else:
                        self.merge_piece()
    
                screen.fill(BLACK)
                self.draw_grid()
                self.draw_piece(self.current_piece)
                self.draw_score()
    
                if self.game_over:
                    font = pygame.font.SysFont(None, 48)
                    text = font.render("Game Over", True, WHITE)
                    screen.blit(text, (SCREEN_WIDTH // 2 - 100, SCREEN_HEIGHT // 2))
                    pygame.display.flip()
                    pygame.time.wait(2000)
                    running = False
    
                pygame.display.flip()
    
            pygame.quit()
    
        def draw_grid(self):
            for i in range(GRID_HEIGHT):
                for j in range(GRID_WIDTH):
                    if self.grid[i][j]:
                        pygame.draw.rect(screen, self.grid[i][j],
                                       (j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE - 1, BLOCK_SIZE - 1))
    
            # 绘制网格线
            for i in range(GRID_HEIGHT + 1):
                pygame.draw.line(screen, WHITE, (0, i * BLOCK_SIZE), (GRID_WIDTH * BLOCK_SIZE, i * BLOCK_SIZE))
            for j in range(GRID_WIDTH + 1):
                pygame.draw.line(screen, WHITE, (j * BLOCK_SIZE, 0), (j * BLOCK_SIZE, GRID_HEIGHT * BLOCK_SIZE))
    
        def draw_piece(self, piece):
            for i in range(len(piece['shape'])):
                for j in range(len(piece['shape'][0])):
                    if piece['shape'][i][j]:
                        pygame.draw.rect(screen, piece['color'],
                                       ((piece['x'] + j) * BLOCK_SIZE, (piece['y'] + i) * BLOCK_SIZE, BLOCK_SIZE - 1, BLOCK_SIZE - 1))
    
        def draw_score(self):
            font = pygame.font.SysFont(None, 36)
            text = font.render(f"Score: {self.score}", True, WHITE)
            screen.blit(text, (GRID_WIDTH * BLOCK_SIZE + 10, 10))
    
    if __name__ == "__main__":
        game = Tetris()
        game.run()
    

    代码说明:

    1. 依赖库:需要安装 Pygame 库,可以通过 pip install pygame 安装。
    2. 游戏功能:
      • 使用上下左右箭头键控制方块的移动和旋转。
      • 按住空格键可以让方块直接掉到底部。
      • 游戏会自动检测并清除满行,并计算得分。
      • 当方块无法再生成时,游戏结束。
    3. 代码结构:
      • Tetris 类封装了游戏逻辑,包括方块的生成、移动、旋转、合并等。
      • run 方法是游戏的主循环,处理用户输入、方块下落和屏幕绘制。
      • valid_move 方法用于检测方块移动是否合法。
      • draw_grid 和 draw_piece 方法负责绘制游戏界面。

    操作说明:

    • 左箭头:向左移动方块。
    • 右箭头:向右移动方块。
    • 下箭头:加速方块下落。
    • 上箭头:旋转方块。
    • 空格键:方块直接掉到底部。
    • 关闭窗口:退出游戏。

    运行游戏:

    将代码保存为 .py 文件(如 tetris.py),然后在命令行中运行 python tetris.py 即可开始游戏。

    扩展建议:

    1. 添加背景音乐和音效。
    2. 实现难度等级(随着得分增加,方块下落速度加快)。
    3. 添加预览下一个方块的功能。
    4. 优化游戏界面,添加开始菜单和暂停功能。

    希望这个代码对你有帮助!如果有任何问题,欢迎提问!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.