pygame研究之利用sprite的UI架构实现

2022-01-02  本文已影响0人  tiger_AI

        学着网上的代码写了个战机游戏,但在暂停游戏的时候,发现实现一个简单按钮竟然要写那么多的代码,而且进行鼠标交互时,这些代码掺杂在原有的游戏代码中,实现看着太丑陋了,就想着抽象一个类出来,网上查了一些资料,特别是pygame的UI实现,各种方式都有,但是感觉都只是为了解决具体问题而写的代码段,通用性不太好,当时正沉迷于pygame的精髓sprite类中,就觉得这个东西应该是可以解决困局的好工具,于是就有了下面的代码。

        这个类核心是解决了UI控件的可遍历性,对鼠标是否“点击到自己”的判断,以及通过自定义的pygam.event实现与其它模块通讯,已经具有了一定的通用性。如果需要扩展其它类型的控件,只需要添加UI控件类型参数,在这个类里写不同的实现即可。


import pygameas pg

# 所有全局常量(下面全部大写的都是全局常量)

from Settingimport *

class ButtonSprite(pg.sprite.Sprite):

def __init__(self, _ID, _backpic, _pos_x, _pos_y):

# 重载父类

        super().__init__()

# 具体动作

        self.ID = _ID

self.image = pg.image.load(_backpic)

self.rect =self.image.get_rect()

if _pos_x >=0:

self.rect.x = _pos_x

elif _pos_x == -1:

self.rect.x = (SCREEN_RECT.width -self.rect.width) //2

        if _pos_y >=0:

self.rect.y = _pos_y

elif _pos_y == -1:

self.rect.y = (SCREEN_RECT.height -self.rect.height) //2

    def is_active(self, _pos):

_active =False

        # 0=x, 1=y

        if self.rect.x < _pos[0] <=self.rect.x +self.rect.widthand \

self.rect.y < _pos[1] <=self.rect.y +self.rect.height:

_active =True

        return _active

def execute(self, _msg=''):

# print('excute', self.ID)

        if self.ID =='GAMEEXIT':

_event = pg.event.Event(GAME_EXIT_EVENT)

pg.event.post(_event)

elif self.ID =='GAMERESTART':

_event = pg.event.Event(GAME_RESTART_EVENT)

pg.event.post(_event)

资源链接:https://pan.baidu.com/s/1-bKJFIEMghuU42mJFElSnQ提取码:78ds

环境说明:

IDE:Pycharm CE

引用库:pygame, random

上一篇 下一篇

猜你喜欢

热点阅读