用Python编写俄罗斯方块游戏

游戏概述

本游戏是一个基于 Pygame 库的俄罗斯方块游戏,玩家需要控制下落的方块,使其拼接成完整的一行或多行并消除,以获得得分

游戏规则

  • 玩家需要控制下落的方块,使其拼接成完整的一行或多行并消除,以获得得分。
  • 方块可以左右移动,旋转或加速下落。
  • 当方块下落到底部或与其他方块重叠时,就固定在当前位置,不能再移动或旋转。
  • 当所有方块堆叠到屏幕顶部时,游戏结束。
  • 游戏界面

    游戏界面包括如下元素:

  • 俄罗斯方块区域:用于显示下落的方块和已固定的方块。
  • 得分区域:用于显示当前得分。
  • 游戏结束提示:当游戏结束时,屏幕上方会显示 GAME OVER。
  • 游戏实现

    游戏的实现采用了 Pygame 库,主要包括如下几个部分:

  • 方块类:用于表示每个方块。
  • 形状类:用于表示每个下落的形状,包括方块的颜色和位置。
  • 碰撞检测:用于检测形状是否与其他方块重叠。
  • 游戏逻辑:包括控制形状的移动,旋转和加速下落,以及消除完整的行等。
  • 游戏界面:用于显示游戏界面和更新得分等。
  • 运行环境

    本游戏需要 Python 3 和 Pygame 库。可以在 Windows、Mac 或 Linux 平台上运行.

    运行方法

    在安装了 Python 3 和 Pygame 库的环境下,可以直接运行 tetris.py 文件来启动游戏。

    代码实现

    import pygame
    import random
    
    # 初始化 Pygame
    pygame.init()
    
    # 游戏界面大小
    screen_width = 800
    screen_height = 600
    
    # 定义颜色
    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)
    
    # 定义方块大小
    block_size = 20
    
    # 定义游戏界面
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("俄罗斯方块")
    
    # 定义字体
    font = pygame.font.SysFont(None, 25)
    
    def draw_text(text, color, x, y):
        """绘制文字"""
        img = font.render(text, True, color)
        screen.blit(img, (x, y))
    
    class Block(pygame.sprite.Sprite):
        """方块类"""
    
        def __init__(self, color, width, height):
            super().__init__()
    
            self.image = pygame.Surface([width, height])
            self.image.fill(WHITE)
            self.image.set_colorkey(WHITE)
    
            pygame.draw.rect(self.image, color, [0, 0, width, height])
    
            self.rect = self.image.get_rect()
    
        def update(self):
            """更新方块位置"""
            self.rect.y += block_size
    
    class Shape:
        """形状类"""
    
        shapes = [
            [[1, 1, 1, 1]],
            [[1, 0, 0], [1, 1, 1]],
            [[0, 0, 1], [1, 1, 1]],
            [[1, 1], [1, 1]],
            [[0, 1, 1], [1, 1, 0]],
            [[1, 1, 0], [0, 1, 1]],
            [[0, 1, 0], [1, 1, 1]]
        ]
    
        def __init__(self, x, y):
            self.x = x
            self.y = y
            self.shape = random.choice(Shape.shapes)
            self.color = random.choice([RED, GREEN, BLUE, YELLOW])
    
            self.blocks = []
    
            for i in range(len(self.shape)):
                for j in range(len(self.shape[i])):
                    if self.shape[i][j] == 1:
                        block = Block(self.color, block_size, block_size)
                        block.rect.x = self.x + j * block_size
                        block.rect.y = self.y + i * block_size
                        self.blocks.append(block)
    
        def update(self):
            """更新形状位置"""
            for block in self.blocks:
                block.rect.y += block_size
    
        def move_left(self):
            """向左移动形状"""
            for block in self.blocks:
                block.rect.x -= block_size
    
        def move_right(self):
            """向右移动形状"""
            for block in self.blocks:
                block.rect.x += block_size
    
        def rotate(self):
            """旋转形状"""
            old_shape = self.shape
            new_shape = []
    
            for i in range(len(old_shape[0])):
                new_row = []
                for j in range(len(old_shape)):
                    new_row.append(old_shape[len(old_shape) - j - 1][i])
                new_shape.append(new_row)
    
            self.shape = new_shape
    
            self.blocks = []
    
            for i in range(len(self.shape)):
                for j in range(len(self.shape[i])):
                    if self.shape[i][j] == 1:
                        block = Block(self.color, block_size, block_size)
                        block.rect.x = self.x + j * block_size
                        block.rect.y = self.y + i * block_size
                        self.blocks.append(block)
    
    def check_collision(shape, blocks):
        """检查形状是否与其他方块重叠"""
        for block in shape.blocks:
            for b in blocks:
                if block.rect.colliderect(b.rect):
                    return True
        return False
    
    def check_gameover(blocks):
        """检查游戏是否结束"""
        for block in blocks:
            if block.rect.y <= 0:
                return True
        return False
    
    def main():
        """游戏主函数"""
        # 创建方块组
        all_blocks = pygame.sprite.Group()
    
        # 创建形状
        current_shape = Shape(3 * block_size, 0)
    
        # 游戏循环
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        current_shape.move_left()
                        if check_collision(current_shape, all_blocks):
                            current_shape.move_right()
                    elif event.key == pygame.K_RIGHT:
                        current_shape.move_right()
                        if check_collision(current_shape, all_blocks):
                            current_shape.move_left()
                    elif event.key == pygame.K_UP:
                        current_shape.rotate()
                        if check_collision(current_shape, all_blocks):
                            current_shape.rotate()
                            current_shape.rotate()
                            current_shape.rotate()
                    elif event.key == pygame.K_DOWN:
                        current_shape.update()
                        if check_collision(current_shape, all_blocks):
                            current_shape.blocks.pop()
                            all_blocks.add(current_shape.blocks)
                            current_shape = Shape(3 * block_size, 0)
    
            # 更新形状位置
            current_shape.update()
    
            # 检查是否与其他方块重叠
            if check_collision(current_shape, all_blocks):
                current_shape.blocks.pop()
                all_blocks.add(current_shape.blocks)
                current_shape = Shape(3 * block_size, 0)
    
            # 绘制游戏界面
            screen.fill(BLACK)
    
            all_blocks.draw(screen)
            current_shape.blocks.draw(screen)
    
            pygame.draw.rect(screen, GRAY, [0, 0, screen_width, screen_height], 4)
    
            # 更新游戏界面
            pygame.display.update()
    
            # 检查游戏是否结束
            if check_gameover(all_blocks):
                draw_text("GAME OVER", WHITE, screen_width / 2 - 60, screen_height / 2 - 12)
                pygame.display.update()
                pygame.time.wait(3000)
                pygame.quit()
                quit()
    
            # 控制游戏速度
            pygame.time.wait(300)
    
    if __name__ == "__main__":
        main()
    
    
    物联沃分享整理
    物联沃-IOTWORD物联网 » 用Python编写俄罗斯方块游戏

    发表评论