python游戏开发实战:游戏按钮

一.效果

二.简介

    游戏中,按钮是必不可少的控件.但是pygame并没有给我们提供相关的功能.那么只能自己写一个啦.

    演示工程的下载地址:https://pan.baidu.com/s/1dCgCs8t2FPn1DstRyAF84g

三.相关代码

    Button.py:

class Button:
    NORMAL=0
    MOVE=1
    DOWN=2
    def __init__(self,x,y,text,imgNormal,imgMove=None,imgDown=None,callBackFunc=None,font=None,rgb=(0,0,0)):
        """
        初始化按钮的相关参数
        :param x: 按钮在窗体上的x坐标
        :param y: 按钮在窗体上的y坐标
        :param text: 按钮显示的文本
        :param imgNormal: surface类型,按钮正常情况下显示的图片
        :param imgMove: surface类型,鼠标移动到按钮上显示的图片
        :param imgDown: surface类型,鼠标按下时显示的图片
        :param callBackFunc: 按钮弹起时的回调函数
        :param font: pygame.font.Font类型,显示的字体
        :param rgb: 元组类型,文字的颜色
        """
        #初始化按钮相关属性
        self.imgs=[]
        if not imgNormal:
            raise Exception("请设置普通状态的图片")
        self.imgs.append(imgNormal)     #普通状态显示的图片
        self.imgs.append(imgMove)       #被选中时显示的图片
        self.imgs.append(imgDown)       #被按下时的图片
        for i in range(2,0,-1):
            if not self.imgs[i]:
                self.imgs[i]=self.imgs[i-1]

        self.callBackFunc=callBackFunc      #触发事件
        self.status=Button.NORMAL       #按钮当前状态
        self.x=x
        self.y=y
        self.w=imgNormal.get_width()
        self.h=imgNormal.get_height()
        self.text=text
        self.font=font
        #文字表面
        self.textSur=self.font.render(self.text,True,rgb)

    def draw(self,destSuf):
        dx=(self.w/2)-(self.textSur.get_width()/2)
        dy=(self.h/2)-(self.textSur.get_height()/2)
        #先画按钮背景
        if self.imgs[self.status]:
            destSuf.blit(self.imgs[self.status], [self.x, self.y])
        #再画文字
        destSuf.blit(self.textSur,[self.x+dx,self.y+dy])

    def colli(self,x,y):
        #碰撞检测
        if self.x<x<self.x+self.w and self.y<y<self.y+self.h:
            return True
        else:
            return False

    def getFocus(self,x,y):
        #按钮获得焦点时
        if self.status==Button.DOWN:
            return
        if self.colli(x,y):
            self.status=Button.MOVE
        else:
            self.status=Button.NORMAL

    def mouseDown(self,x,y):
        if self.colli(x,y):
            self.status = Button.DOWN

    def mouseUp(self):
        if self.status==Button.DOWN:    #如果按钮的当前状态是按下状态,才继续执行下面的代码
            self.status=Button.NORMAL   #按钮弹起,所以还原成普通状态
            if self.callBackFunc:       #调用回调函数
                return self.callBackFunc()

相关方法说明:

def draw(self,destSur):用来绘制按钮,destSur是你要绘制的地方,一般是窗体的surface

def colli(self,x,y):检测鼠标是否在按钮范围内,x,y是鼠标坐标.返回值True:在范围内,False:不再范围内

def mouseDown(self,x,y):鼠标按下的时候调用的方法,功能是令按钮的显示状态变为按下状态

扫描二维码关注公众号,回复: 2680127 查看本文章

def mouseUp(self):鼠标弹起时调用的方法,并且会触发按钮的回调函数,返回值是回调函数的返回值

使用:

下面的代码依赖了三个按钮图片,请把图片文件与代码文件放在同一文件夹下.

main.py:

import pygame

from Button import Button

# 初始化pygame
pygame.init()
winSur = pygame.display.set_mode([300, 300])

# 加载按钮图片
surBtnNormal = pygame.image.load("./btn_normal.png").convert_alpha()
surBtnMove = pygame.image.load("./btn_move.png").convert_alpha()
surBtnDown = pygame.image.load("./btn_down.png").convert_alpha()

#按钮使用的字体
btnFont = pygame.font.SysFont("lisu", 40)

# 按钮的回调函数
def btnCallBack():
    print("我被按下了")


# 创建按钮
btn1 = Button(30, 50, "按钮测试", surBtnNormal, surBtnMove, surBtnDown, btnCallBack,btnFont,(255,0,0))
btn2 = Button(30, 150, "", surBtnNormal, surBtnMove, surBtnDown, btnCallBack,btnFont)

# 游戏主循环
while True:
    mx, my = pygame.mouse.get_pos()  # 获得鼠标坐标

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()
        elif event.type == pygame.MOUSEMOTION:  # 鼠标移动事件
            # 判断鼠标是否移动到按钮范围内
            btn1.getFocus(mx, my)
            btn2.getFocus(mx, my)

        elif event.type == pygame.MOUSEBUTTONDOWN:  # 鼠标按下
            if pygame.mouse.get_pressed() == (1, 0, 0): #鼠标左键按下
                btn1.mouseDown(mx,my)
                btn2.mouseDown(mx, my)

        elif event.type == pygame.MOUSEBUTTONUP:  # 鼠标弹起
            btn1.mouseUp()
            btn2.mouseUp()

    pygame.time.delay(16)
    winSur.fill((0, 0, 0))
    #绘制按钮
    btn1.draw(winSur)
    btn2.draw(winSur)
    #刷新界面
    pygame.display.flip()

猜你喜欢

转载自blog.csdn.net/qq_39687901/article/details/80853127