Pygame按钮集成及界面切换的实现

这篇具有很好参考价值的文章主要介绍了Pygame按钮集成及界面切换的实现。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

pygame是python轻量级的游戏框架,通常用于微型小游戏的创作或者游戏编程思想的教育。pygame的功能集成程度比较低,通常需要将功能代码人工再次集成包装(模块化、类化)才能更好地减少代码量,起到复用的效果。

下面展示一段按钮集成的代码。展示了纯文本(Text), 图片(Image),纯色(ColorSurface),以及这三种对应的按钮(即附加事件触发功能)的类设计。

from calendar import c
import os
import random
import sys

import pygame
from pygame import font
from pygame.constants import MOUSEBUTTONDOWN, MOUSEMOTION


class Color:
    # 自定义颜色
    ACHIEVEMENT = (220, 160, 87)
    VERSION = (220, 160, 87)

    # 固定颜色
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    GREY = (128, 128, 128)  # 中性灰
    TRANSPARENT = (255, 255, 255, 0)  # 白色的完全透明


class Text:
    def __init__(self, text: str, text_color: Color, font_type: str, font_size: int):
        """
        text: 文本内容,如'大学生模拟器',注意是字符串形式
        text_color: 字体颜色,如Color.WHITE、COLOR.BLACK
        font_type: 字体文件(.ttc),如'msyh.ttc',注意是字符串形式
        font_size: 字体大小,如20、10
        """
        self.text = text
        self.text_color = text_color
        self.font_type = font_type
        self.font_size = font_size

        font = pygame.font.Font(os.path.join('font', (self.font_type)), self.font_size)
        self.text_image = font.render(self.text, True, self.text_color).convert_alpha()

        self.text_width = self.text_image.get_width()
        self.text_height = self.text_image.get_height()

    def draw(self, surface: pygame.Surface, center_x, center_y):
        """
        surface: 文本放置的表面
        center_x, center_y: 文本放置在表面的<中心坐标>
        """
        upperleft_x = center_x - self.text_width / 2
        upperleft_y = center_y - self.text_height / 2
        surface.blit(self.text_image, (upperleft_x, upperleft_y))


class Image:
    def __init__(self, img_name: str, ratio=0.4):
        """
        img_name: 图片文件名,如'background.jpg'、'ink.png',注意为字符串
        ratio: 图片缩放比例,与主屏幕相适应,默认值为0.4
        """
        self.img_name = img_name
        self.ratio = ratio

        self.image_1080x1920 = pygame.image.load(os.path.join('image', self.img_name)).convert_alpha()
        self.img_width = self.image_1080x1920.get_width()
        self.img_height = self.image_1080x1920.get_height()

        self.size_scaled = self.img_width * self.ratio, self.img_height * self.ratio

        self.image_scaled = pygame.transform.smoothscale(self.image_1080x1920, self.size_scaled)
        self.img_width_scaled = self.image_scaled.get_width()
        self.img_height_scaled = self.image_scaled.get_height()

    def draw(self, surface: pygame.Surface, center_x, center_y):
        """
        surface: 图片放置的表面
        center_x, center_y: 图片放置在表面的<中心坐标>
        """
        upperleft_x = center_x - self.img_width_scaled / 2
        upperleft_y = center_y - self.img_height_scaled / 2
        surface.blit(self.image_scaled, (upperleft_x, upperleft_y))


class ColorSurface:
    def __init__(self, color, width, height):
        self.color = color
        self.width = width
        self.height = height

        self.color_image = pygame.Surface((self.width, self.height)).convert_alpha()
        self.color_image.fill(self.color)

    def draw(self, surface: pygame.Surface, center_x, center_y):
        upperleft_x = center_x - self.width / 2
        upperleft_y = center_y - self.height / 2
        surface.blit(self.color_image, (upperleft_x, upperleft_y))


class ButtonText(Text):
    def __init__(self, text: str, text_color: Color, font_type: str, font_size: int):
        super().__init__(text, text_color, font_type, font_size)
        self.rect = self.text_image.get_rect()

    def draw(self, surface: pygame.Surface, center_x, center_y):
        super().draw(surface, center_x, center_y)
        self.rect.center = center_x, center_y

    def handle_event(self, command):
        self.hovered = self.rect.collidepoint(pygame.mouse.get_pos())
        if self.hovered:
            command()


class ButtonImage(Image):
    def __init__(self, img_name: str, ratio=0.4):
        super().__init__(img_name, ratio)
        self.rect = self.image_scaled.get_rect()

    def draw(self, surface: pygame.Surface, center_x, center_y):
        super().draw(surface, center_x, center_y)
        self.rect.center = center_x, center_y

    def handle_event(self, command):
        self.hovered = self.rect.collidepoint(pygame.mouse.get_pos())
        if self.hovered:
            command()


class ButtonColorSurface(ColorSurface):
    def __init__(self, color, width, height):
        super().__init__(color, width, height)
        self.rect = self.color_image.get_rect()

    def draw(self, surface: pygame.Surface, center_x, center_y):
        super().draw(surface, center_x, center_y)
        self.rect.center = center_x, center_y

    def handle_event(self, command, *args):
        self.hovered = self.rect.collidepoint(pygame.mouse.get_pos())
        if self.hovered:
            command(*args)

pygame通过死循环持续监听事件发生,而游戏内容则是通过界面刷新来完成。因此,需要游戏界面切换时,也需要在死循环中设置事件为界面刷新。

为了清晰地描述代码作用,以下仅展示最小功能,完整的pygame按钮集成及界面切换的实现可移步文末的github链接。注意下面代码也使用了上文定义的按钮类。

class InterFace():
    def __init__(self):
        pygame.init()

    def basic_background(self):
        """
        <基本背景><basic_background>\n
        返回值为背景尺寸和背景表面
        """
        # 设置logo和界面标题
        game_icon = pygame.image.load(os.path.join('image', 'college_icon.png'))
        game_caption = '大学生模拟器'
        pygame.display.set_icon(game_icon)
        pygame.display.set_caption(game_caption)

        # 设置开始界面
        show_ratio = 0.4
        size = width, height = 1080 * show_ratio, 1920 * show_ratio
        screen = pygame.display.set_mode(size)

        # 设置背景贴图
        Image('background.jpg').draw(screen, width / 2, height / 2)

        return size, screen

    def start_interface(self):
        """
        <开始界面><start_interface>
        """
        # 设置<基本背景>
        size, screen = self.basic_background()
        width, height = size

        # 设置<开始界面>文字和贴图
        Image('ink.png', ratio=0.4).draw(screen, width * 0.52, height * 0.67)  # 墨印
        Image('achievement_icon.png', ratio=0.25).draw(screen, width * 0.93, height * 0.05)  # 成就按钮

        Text('大学生模拟器', Color.BLACK, 'HYHanHeiW.ttf', 50).draw(screen, width / 2, height * 1 / 3)  # 游戏名
        Text('Alpha 0.0', Color.VERSION, 'msyh.ttc', 12).draw(screen, width / 2, height * 0.97)  # 版本号
        Text('成就', Color.ACHIEVEMENT, 'msyh.ttc', 16).draw(screen, width * 0.93, height * 0.09)  # 成就

        button_game_start = ButtonText('开始游戏', Color.WHITE, 'msyh.ttc', 23)  # 开始游戏按钮
        button_game_start.draw(screen, width / 2, height * 2 / 3)

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                
                # !此处为界面切换的关键,即进入另一死循环
                if event.type == pygame.MOUSEBUTTONDOWN:
                    button_game_start.handle_event(self.initial_attribute_interface)

            pygame.display.update()

    def initial_attribute_interface(self):
        """
        <初始属性界面><initial_attribute_interface>
        """
        # 设置基本背景
        size, screen = self.basic_background()
        width, height = size
        
        # 放置各种按钮
        Image('返回.png', ratio=0.38).draw(screen, width * 0.07, height * 0.047)
        button_back = ButtonColorSurface(Color.TRANSPARENT, 26, 26)
        button_back.draw(screen, width * 0.07, height * 0.047)

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                # !此处为界面切换的关键,即进入另一死循环
                if event.type == pygame.MOUSEBUTTONDOWN:
                    button_back.handle_event(self.start_interface)

            pygame.display.update()


if __name__ == '__main__':
    scene = InterFace()
    # 开始时选定start_interface
    scene.start_interface()

完整可运行代码文件夹:

https://github.com/AkinaZed/pygame-button-interface-switch文章来源地址https://www.toymoban.com/news/detail-506711.html

到了这里,关于Pygame按钮集成及界面切换的实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 很合适新手入门使用的Python游戏开发包pygame实例教程-01[开发环境配置与第一个界面]

    我们假定你已经安装好了我们开发python程序的sublime text,如果不知道怎么安装的可以参照我前面的博文。这里只需要解决的是配置好Pygame的问题。本篇博文主要解决开发环境配置以及第一个游戏界面的显示问题。 文章原出处: https://blog.csdn.net/haigear/article/details/130173836 没有

    2024年01月25日
    浏览(79)
  • 【Python】pygame弹球游戏实现

    游戏源码: pygame_os库:

    2024年02月12日
    浏览(44)
  • python和pygame实现烟花特效

    新年来临之际,来一个欢庆新年烟花祝贺,需要安装使用第三方库pygame,关于Python中pygame游戏模块的安装使用可见 https://blog.csdn.net/cnds123/article/details/119514520 效果图及源码 先看效果图: 源码如下: pygame在屏幕上显示字体的方法说明 使用 pygame.font.Font 函数来设置字体和大小,

    2024年02月04日
    浏览(61)
  • Python利用pygame实现飞机大战游戏

    文章目录: 一:运行效果 1.演示 2.思路和功能 二:代码 文件架构 Demo 必备知识:python图形化编程pygame游戏模块 效果图 ◕‿◕✌✌✌ Python利用pygame实现飞机大战游戏运行演示 参考:【Python游戏】1小时开发飞机大战游戏-Pygame版本(1小时40分钟) 博主提取资源: 提取

    2024年04月09日
    浏览(51)
  • 使用Pygame创建一个简单游戏界面

    首先需要安装Pygame 模块,在Python代码中添加引用。 1. 引用代码如下: 2. 定义初始化窗口函数: 在初始化窗口函数中,定义窗口大小和窗口标题。 3. 创建一个循环,不断更新界面和检测事件 加载背景图片,将背景图片对象放置在窗口上,位置(0,0) 最左角,图片有实际的

    2024年02月13日
    浏览(38)
  • python3.8.8 :pygame实现角色动画

    用途:通过不同的序列图片在界面上展示连贯的动画 结果如下:  参考文章:pygame之旅 - 知乎 (zhihu.com) 项目结构目录  角色类 角色生成类: 代码入口 结果如下:  发现出现问题,动画出现残影,看网上说需要先绘制背景,再绘制角色可以解决,随意填个颜色screen.fill(255)

    2024年02月05日
    浏览(40)
  • 使用Python的pygame库实现下雪的效果

    关于Python中pygame游戏模块的安装使用可见 https://blog.csdn.net/cnds123/article/details/119514520 先给出效果图: 源码如下: 下面给出改进版 效果图: 使用一张背景图片(我这里文件名:snow_background.jpg),和代码文件放在同一目录下  源码如下: 附:RGB 颜色表   https://www.codeeeee.com

    2024年01月19日
    浏览(41)
  • 使用Python+pygame实现贪吃蛇小游戏

    使用第三方库pygame,关于Python中pygame游戏模块的安装使用可见 https://blog.csdn.net/cnds123/article/details/119514520 给出两种实现。 第一种 运行效果如下: 游戏源码如下: 第二种 就不给出运行效果图了,你可以运行看看。 下面给出另一种实现源码: OK! 

    2024年01月16日
    浏览(49)
  • python+pygame+opencv+gpt实现虚拟数字人直播(一)

    AI技术突飞猛进,不断的改变着人们的工作和生活。数字人直播作为新兴形式,必将成为未来趋势,具有巨大的、广阔的、惊人的市场前景。它将不断融合创新技术和跨界合作,提供更具个性化和多样化的互动体验,成为未来的一种趋势。 马斯克称:“人工智能将在我们所看

    2024年02月08日
    浏览(24)
  • 基于Python的PyGame的俄罗斯方块游戏设计与实现

    近年来,随着游戏产业的突飞猛进,游戏玩家的技术也是与日俱增,当你看见游戏高手完美的表演时,你是否想过我也能达到那种水平,本程序用Python语言编写俄罗斯方块,左侧显示正在运行的游戏,右边显示下一个出现的形状、等级和积分等。游戏运行时随着等级的提高而

    2024年02月04日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包