? ? ? ? 學著網上的代碼寫了個戰(zhàn)機游戲,但在暫停游戲的時候坠非,發(fā)現實現一個簡單按鈕竟然要寫那么多的代碼敏沉,而且進行鼠標交互時,這些代碼摻雜在原有的游戲代碼中,實現看著太丑陋了盟迟,就想著抽象一個類出來秋泳,網上查了一些資料,特別是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
環(huán)境說明:
IDE:Pycharm CE
引用庫:pygame, random