使用pygame 编写俄罗斯方块游戏

news2024/10/5 18:27:44

项目地址:https://gitee.com/wyu_001/mypygame/tree/master/game
可执行程序

这个游戏主要使用pygame库编写俄罗斯方块游戏,demo主要演示了pygame开发游戏的主要设计方法和实现代码

下面是游戏界面截图
在这里插入图片描述
游戏主界面:

在这里插入图片描述
直接上代码:

# !/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
  @author: spring.wang
  @license: 
  @contact: wyu_01@163.com
  @software: tetris
  @file: tetris1.py
  @time: 2024/2/20 17:26
  @description:

  pyinstaller.exe  -F -w --distpath D:\myproject\python\pygame\bin\tetris  --workpath D:\myproject\python\pygame\bin\temp --specpath D:\myproject\python\pygame\bin\temp D:\myproject\python\pygame\game\tetris.py
  
  '''

import pygame
import random
import time
import sys

# 游戏窗口尺寸
WINDOW_WIDTH = 200
WINDOW_HEIGHT = 400

# 方块尺寸
BLOCK_SIZE = 20

# 初始化 Pygame
pygame.init()

# 初始化窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))

class Block:
    def __init__(self, shape, color):
        self.shape = shape
        self.color = color
        self.x = WINDOW_WIDTH // 2 - BLOCK_SIZE
        self.y = 0
        self.timer = 0
        self.fall_speed = 10
        self.move_speed = 1
        self.max_speed = 3

    def set_speed(self):

        self.move_speed += 1
        if self.move_speed > self.max_speed:
            self.move_speed = self.max_speed

    def reset_speed(self):
        self.move_speed = 1

    def move_up(self):
        self.y -= BLOCK_SIZE

    def move_down(self):
        self.y += BLOCK_SIZE

    def move_left(self):
        self.x -= BLOCK_SIZE

    def move_right(self):
        self.x += BLOCK_SIZE

    def rotate(self):
        self.shape = [[row[i] for row in self.shape][::-1] for i in range(len(self.shape[0]))]
        # print(self.shape)

    def draw(self):
        for i in range(len(self.shape)):
            for j in range(len(self.shape[i])):
                if self.shape[i][j] == 1:
                    pygame.draw.rect(window, self.color,
                                     (self.x + j * BLOCK_SIZE, self.y  + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))



class Tetris:

    # 方块颜色
    BLACK = (0, 0, 0)
    CYAN = (0, 255, 255)
    YELLOW = (255, 255, 0)
    PURPLE = (255, 0, 255)
    GREEN = (0, 255, 0)
    RED = (255, 0, 0)
    ORANGE = (255, 165, 0)
    BLUE = (0, 0, 255)
    WHITE = (255, 255, 255)
    # 定义方块形状
    SHAPES = [
      [[1, 1, 1, 1]],
      [[1, 1], [1, 1]],
      [[1, 1, 0], [0, 1, 1]],
      [[0, 1, 1], [1, 1, 0]],
      [[1, 1, 1], [0, 1, 0]],
      [[1, 1, 1], [1, 0, 0]],
      [[1, 1, 1], [0, 0, 1]]
    ]

    # 定义方块颜色
    COLORS = [CYAN, YELLOW, PURPLE, GREEN, RED, ORANGE, BLUE]

    def __init__(self):
        self.score = 0
        self.timer = 0
        self.fall_speed = 1
        self.FPS = 60
        self.game_running = True

        pygame.display.set_caption("俄罗斯方块")
        self.clock = pygame.time.Clock()

        self.grid = [[self.BLACK] * (WINDOW_WIDTH // BLOCK_SIZE) for _ in range(WINDOW_HEIGHT // BLOCK_SIZE)]
        self.block = Block(random.choice(self.SHAPES), random.choice(self.COLORS))

        self.key_down_time = None
        self.key_left_time = None
        self.key_right_time = None

        self.down_flag = True
        self.direction = 0
    def draw_grid(self):
        for x in range(0, WINDOW_WIDTH, BLOCK_SIZE):
            pygame.draw.line(window, self.BLACK, (x, 0), (x, WINDOW_HEIGHT))
        for y in range(0, WINDOW_HEIGHT, BLOCK_SIZE):
          pygame.draw.line(window, self.BLACK, (0, y), (WINDOW_WIDTH, y))

    def check_collision(self):
        for i in range(len(self.block.shape)):
            for j in range(len(self.block.shape[i])):
                if self.block.shape[i][j] == 1:
                    if self.block.y + (i + 1) * BLOCK_SIZE >= WINDOW_HEIGHT or \
                            self.block.x + j * BLOCK_SIZE < 0 or \
                            self.block.x + j * BLOCK_SIZE >= WINDOW_WIDTH or \
                            self.grid[self.block.y // BLOCK_SIZE + i + 1][self.block.x // BLOCK_SIZE + j] != self.BLACK:
                        return True
        return False

    def event_handler(self):
        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.game_running = False
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    self.key_left_time = time.time()
                    self.block.move_left()
                    if self.check_collision():
                        self.block.move_right()
                elif event.key == pygame.K_RIGHT:
                    self.key_right_time = time.time()
                    self.block.move_right()
                    if self.check_collision():
                        self.block.move_left()
                elif event.key == pygame.K_DOWN:
                    if not self.check_collision():
                        self.key_down_time = time.time()
                        self.block.move_down()
                elif event.key == pygame.K_UP:
                    self.block.rotate()
                    if self.check_collision():
                        for _ in range(3):
                            self.block.rotate()
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    self.key_left_time = None
                    self.down_flag = True
                    self.timer = 0
                    self.direction = 0
                if event.key == pygame.K_RIGHT:
                    self.key_right_time = None
                    self.down_flag = True
                    self.timer = 0
                    self.direction = 0
                if event.key == pygame.K_DOWN:
                    self.key_down_time = None
                    self.timer=0
    def update(self):
        if self.timer >= 1 / self.fall_speed:
            self.timer -= 1 / self.fall_speed

            if not self.check_collision() and self.down_flag:
                self.block.move_down()
            elif not self.check_collision():
                if self.direction == 1:
                    self.block.move_left()
                    if self.check_collision():
                        self.block.move_right()
                if self.direction == 2:
                    self.block.move_right()
                    if self.check_collision():
                        self.block.move_left()
            else:
                for i in range(len(self.block.shape)):
                    for j in range(len(self.block.shape[i])):
                        if self.block.shape[i][j] == 1:
                            # print(block.y // BLOCK_SIZE + i, block.x // BLOCK_SIZE + j,i,j)
                            self.grid[self.block.y // BLOCK_SIZE + i][self.block.x // BLOCK_SIZE + j] = self.block.color

                self.score += self.clear_rows()

                if self.score%20 == 0 and self.score != 0 :
                    self.fall_speed += 1
                self.block = Block(random.choice(self.SHAPES), random.choice(self.COLORS))

                if self.check_collision():
                    self.game_running = False

        current_time = time.time()
        if self.key_down_time is not None and (current_time - self.key_down_time) > 0.1:  # 假设0.1秒后开始加速
            self.key_down_time = current_time
            self.timer += 1 / self.fall_speed*2

        if self.key_left_time is not None and (current_time - self.key_left_time) > 0.1:  # 假设0.1秒后开始加速
            self.key_left_time = current_time
            self.down_flag = False
            self.direction = 1
            self.timer += 1 / self.fall_speed*20

        if self.key_right_time is not None and (current_time - self.key_right_time) > 0.1:  # 假设0.1秒后开始加速
            self.key_right_time = current_time
            self.down_flag = False
            self.direction = 2
            self.timer += 1 / self.fall_speed*20
        # 绘制
        window.fill(self.BLACK)

        for i in range(len(self.grid)):
            for j in range(len(self.grid[i])):
                pygame.draw.rect(window, self.grid[i][j], (j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)

        self.block.draw()
        self.draw_grid()
        self.draw_score()
        pygame.display.flip()

    def clear_rows(self):
        full_rows = []
        for i in range(len(self.grid)):
            if not self.BLACK in self.grid[i]:
                full_rows.append(i)

        for row in full_rows:
            del self.grid[row]
            self.grid.insert(0, [self.BLACK] * (WINDOW_WIDTH // BLOCK_SIZE))

        return len(full_rows)

    def draw_score(self):
        font = pygame.font.Font('resource/font/simfang.ttf', 12)
        font.set_bold(True)
        text = font.render("SCORE: " + str(self.score), True, self.WHITE)
        window.blit(text, (10, 10))

    def game_over(self):
        font = pygame.font.Font('resource/font/COOPBL.TTF', 24)
        text = font.render("GAME OVER", True, self.RED)
        window.blit(text, (WINDOW_WIDTH // 2 - text.get_width() // 2, WINDOW_HEIGHT // 2 - text.get_height() // 2))

        pygame.display.flip()
        pygame.time.wait(2000)

    def play_music(self):
        pygame.mixer.init()
        pygame.mixer.music.load('resource/music/gotime.mp3')
        pygame.mixer.music.play(-1)

    def run(self):
        self.play_music()
        self.game_running = True

        while self.game_running:
            dt = self.clock.tick(self.FPS) / 1000
            self.timer += dt
            self.event_handler()
            self.update()
        self.game_over()

class ImageButton():
    def __init__(self, x, y, image_normal, image_hover=None):
        self.rect = image_normal.get_rect(topleft=(x, y))
        self.normal_image = image_normal
        self.hover_image = image_hover if image_hover is not None else image_normal
        self.image = self.normal_image
        self.clicked = False

    def draw(self):
        mouse_pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(mouse_pos):
            self.image = self.hover_image
        else:
            self.image = self.normal_image

        window.blit(self.image, self.rect)

    def check_click(self):
        mouse_pressed = pygame.mouse.get_pressed()[0]
        if self.rect.collidepoint(pygame.mouse.get_pos()) and mouse_pressed:
            self.clicked = True
            return True
        else:
            self.clicked = False
            return False

def draw_title():

    font = pygame.font.Font('resource/font/COOPBL.TTF', 40)
    text = font.render("TETRIS", True, (11, 161, 225))
    window.blit(text, (WINDOW_WIDTH // 2 - text.get_width() // 2, WINDOW_HEIGHT // 4 - text.get_height() // 2))


if __name__ == "__main__":

    # 创建开始按钮
    # 加载开始按钮图片(确保图片文件路径正确)
    start_button_img_normal = pygame.image.load('resource/icon/start.png')
    start_button_img_hover = pygame.image.load('resource/icon/start_hover.png')  # 可选:如果需要鼠标悬停效果

    background_image = pygame.image.load('resource/icon/back.png')

    start_button = ImageButton(WINDOW_WIDTH // 2 - start_button_img_normal.get_width() // 2,
                               WINDOW_HEIGHT // 2 - start_button_img_normal.get_height() // 2,
                               start_button_img_normal,
                               start_button_img_hover)
    # 游戏主循环
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if start_button.check_click():
                    Tetris().run()
        window.fill((0, 0, 0))  # 填充背景色
        window.blit(background_image, (0, 0))  # 绘制背景图片
        draw_title()
        start_button.draw()  # 绘制按钮
        pygame.display.flip()

    pygame.quit()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1466959.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

RabbitMQ 部署方式选择

部署模式 RabbitMQ支持多种部署模式&#xff0c;可以根据应用的需求和规模选择适合的模式。以下是一些常见的RabbitMQ部署模式&#xff1a; 单节点模式&#xff1a; 最简单的部署方式&#xff0c;所有的RabbitMQ组件&#xff08;消息存储、交换机、队列等&#xff09;都运行在…

Redis可视化工具——RedisInsight

文章目录 1. 下载2. 安装3. RedisInsight 添加 Redis 数据库4. RedisInsight 使用 RedisInsight 是 Redis 官方出品的可视化管理工具&#xff0c;支持 String、Hash、Set、List、JSON 等多种数据类型的管理&#xff0c;同时集成了 RedisCli&#xff0c;可进行终端交互。 1. 下载…

数组与指针相关

二级指针与指针数组 #include <stdio.h> #include <stdlib.h> int main() { // 定义一个指针数组&#xff0c;每个元素都是一个指向int的指针 int *ptr_array[3]; // 为指针数组的每个元素分配内存 ptr_array[0] malloc(2*sizeof(int)); ptr_array[1] m…

转运机器人,AGV底盘小车:打造高效、精准的汽车电子生产线

为了满足日益增长的市场需求&#xff0c;保持行业领先地位&#xff0c;某汽车行业电子产品企业引入富唯智能AMR智能搬运机器人及其智能物流解决方案&#xff0c;采用自动化运输措施优化生产节拍和搬运效率&#xff0c;企业生产效率得到显著提升。 项目背景&#xff1a; 1、工厂…

PyTorch概述(二)---MNIST

NIST Special Database3 具体指的是一个更大的特殊数据库3&#xff1b;该数据库的内容为手写数字黑白图片&#xff1b;该数据库由美国人口普查局的雇员手写 NIST Special Database1 特殊数据库1&#xff1b;该数据库的内容为手写数字黑白图片&#xff1b;该数据库的图片由高…

GitCode配置ssh

下载SSH windows设置里选“应用” 选“可选功能” 添加功能 安装这个 坐等安装&#xff0c;安装好后可以关闭设置。 运行 打开cmd 执行如下指令&#xff0c;启动SSH服务。 net start sshd设置开机自启动 把OpenSSH服务添加到Windows自启动服务中&#xff0c;可避免每…

mysql的日志文件在哪?

阅读本文之前请参阅----MySQL 数据库安装教程详解&#xff08;linux系统和windows系统&#xff09; MySQL的日志文件通常包括错误日志、查询日志、慢查询日志和二进制日志等。这些日志文件的位置取决于MySQL的安装和配置。以下是一些常见的日志文件位置和如何找到它们&#xff…

【kubernetes】二进制部署k8s集群之,多master节点负载均衡以及高可用(下)

↑↑↑↑接上一篇继续部署↑↑↑↑ 之前已经完成了单master节点的部署&#xff0c;现在需要完成多master节点以及实现k8s集群的高可用 一、完成master02节点的初始化操作 二、在master01节点基础上&#xff0c;完成master02节点部署 步骤一&#xff1a;准备好master节点所需…

调用 Python 函数遗漏括号 ( )

调用 Python 函数遗漏括号 1. Example - error2. Example - correctionReferences 1. Example - error name "Forever Strong" print(name.upper()) print(name.lower)FOREVER STRONG <built-in method lower of str object at 0x0000000002310670>---------…

【ArcGIS】利用高程进行坡度分析:区域面/河道坡度

在ArcGIS中利用高程进行坡度分析 坡度ArcGIS实操案例1&#xff1a;流域面上坡度计算案例2&#xff1a;河道坡度计算2.1 案例数据2.2 操作步骤 参考 坡度 坡度是地表单元陡缓的程度&#xff0c;通常把坡面的垂直高度和水平距离的比值称为坡度。 坡度的表示方法有百分比法、度数…

单片机04__基本定时器__毫秒微秒延时

基本定时器__毫秒微秒延时 基本定时器介绍&#xff08;STM32F40x&#xff09; STM32F40X芯片一共包含14个定时器&#xff0c;这14个定时器分为3大类&#xff1a; 通用定时器 10个 TIM9-TIM1和TIM2-TIM5 具有基本定时器功能&#xff0c; 还具有输入捕获&#xff0c;输出比较功…

yarn install:unable to get local issuer certificate

一、问题描述 今天在Jenkins上发布项目时&#xff0c;遇到一个报错&#xff1a; error Error: unable to get local issuer certificateat TLSSocket.onConnectSecure (node:_tls_wrap:1535:34)at TLSSocket.emit (node:events:513:28)at TLSSocket._finishInit (node:_tls_w…

PLC_博图系列☞基本指令“取反RLO”

PLC_博图系列☞基本指令“取反RLO” 文章目录 PLC_博图系列☞基本指令“取反RLO”背景介绍取反RLO说明示例 关键字&#xff1a; PLC、 西门子、 博图、 Siemens 、 取反RLO 背景介绍 这是一篇关于PLC编程的文章&#xff0c;特别是关于西门子的博图软件。我并不是专业的PLC…

谷歌Gemma开源了

1、Gemma的表现 自从大模型横空出世之后&#xff0c;大部分大模型都是闭源的&#xff0c;只有少部分模型选择开源。谷歌推出了全新的开源模型系列Gemma&#xff0c;相比谷歌之前的 Gemini模型&#xff0c;Gemma 更加轻量&#xff0c;可以免费使用&#xff0c;模型权重也一并开…

详解编译和链接!

目录 1. 翻译环境和运行环境 2. 翻译环境 2.1 预处理 2.2 编译 2.3 汇编 2.4 链接 3. 运行环境 4.完结散花 悟已往之不谏&#xff0c;知来者犹可追 创作不易&#xff0c;宝子们&#xff01;如果这篇文章对你们…

Vue+SpringBoot打造开放实验室管理系统

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、研究内容2.1 实验室类型模块2.2 实验室模块2.3 实验管理模块2.4 实验设备模块2.5 实验订单模块 三、系统设计3.1 用例设计3.2 数据库设计 四、系统展示五、样例代码5.1 查询实验室设备5.2 实验放号5.3 实验预定 六、免责说明 一、摘…

多窗口编程

六、多窗口编程 QMessageBox消息对话框&#xff08;掌握&#xff09; QMessageBox继承自QDialog&#xff0c;显示一个模态对话框。用于用户前台信息通知或询问用户问题&#xff0c;并接收问题答案。 QDialog的Qt源码中&#xff0c;派生类往往都是一些在特定场合下使用的预设好的…

【Vuforia+Unity】AR03-圆柱体物体识别(Cylinder Targets)

1.创建数据库模型 这个是让我们把生活中类似圆柱体和圆锥体的物体进行AR识别所选择的模型 Bottom Diameter:底部直径 Top Diameter:顶部直径 Side Length:圆柱侧面长度 请注意&#xff0c;您不必上传所有三个部分的图片&#xff0c;但您需要先为侧面曲面关联一个图像&#…

Threejs 实现3D影像地图,Json地图,地图下钻

1.使用threejs实现3D影像地图效果&#xff0c;整体效果看起来还可以&#xff0c;底层抽象了基类&#xff0c;实现了通用&#xff0c;对任意省份&#xff0c;城市都可以只替换数据&#xff0c;即可轻松实现效果。 效果如下&#xff1a; 链接https://www.bilibili.com/video/BV1…

[AutoSar]BSW_Com1 Can通信入门

目录 关键词平台说明一、车身CAN简介二、相关模块三、Can报文分类及信号流路径3.1 应用报文3.2 应用报文&#xff08;多路复用multiplexer&#xff09;3.3 诊断报文3.4 网络管理报文3.5 XCP报文&#xff08;标定报文&#xff09; 关键词 嵌入式、C语言、autosar、OS、BSW 平台…