首页 > 其他分享 >pygame封装连个常用控件

pygame封装连个常用控件

时间:2024-08-28 10:25:26浏览次数:4  
标签:控件 封装 color text self height char width pygame

#coding=utf-8

import os,sys,re,time
import pygame
import random
from win32api import GetSystemMetrics
from tkinter import messagebox

pygame.init()
pygame.display.set_caption("我的控件")

percent = 0.6
screen_width = GetSystemMetrics(0)
screen_height = GetSystemMetrics(1)
window_width = int(screen_width*percent)
window_height = int(screen_height*percent)

dt = 0
clock = pygame.time.Clock()

screen = pygame.display.set_mode((window_width, window_height))

#停止处理输入法事件
pygame.key.stop_text_input()

def showMsg(msg):
    messagebox.showinfo('提示信息', msg)

class Button:
    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.color = 'gray'
        self.text = '按钮'
        self.text_color = 'black'
        self.text_size = 12
        self.border_width = 1
        self.border_color = 'black'
        self.font_path = os.path.join(os.path.dirname(sys.argv[0]), 'simsun.ttc')
        self.my_font = pygame.font.Font(self.font_path, self.text_size)
        
    def setColor(self, color):
        self.color = color
        
    def setText(self, text):
        self.text = text
        
    def getText(self):
        return self.text
        
    def setTextColor(self, text_color):
        self.text_color = text_color
        
    def setTextSize(self, text_size):
        self.text_size = text_size
        self.my_font = pygame.font.Font(self.font_path, self.text_size)
        
    def setBorderWidth(self, border_width):
        self.border_width = border_width
        
    def setBorderColor(self, border_color):
        self.border_color = border_color
        
    def draw(self, win):
        
        pygame.draw.rect(win, self.color, (self.x, self.y, self.w, self.h))
        if self.border_width > 0:
            pygame.draw.rect(win, self.border_color, (self.x, self.y, self.w, self.h), self.border_width)
            
        text = self.my_font.render(self.text, True, self.text_color)
        myx = self.x + (self.w - text.get_width()) / 2
        myy = self.y + (self.h - text.get_height()) / 2
        win.blit(text, (myx, myy))
        
    def click(self, event):
        if self.x + self.w > event.pos[0] > self.x and self.y + self.h > event.pos[1] > self.y:
            return True
        return False
    
class Label:
    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.color = 'white'
        self.text = ''
        self.text_color = 'black'
        self.text_size = 12
        self.border_width = 0
        self.border_color = ''
        self.font_path = os.path.join(os.path.dirname(sys.argv[0]), 'simsun.ttc')
        self.my_font = pygame.font.Font(self.font_path, self.text_size)
        
    def setColor(self, color):
        self.color = color
        
    def setText(self, text):
        self.text = text
        
    def getText(self):
        return self.text
        
    def setTextColor(self, text_color):
        self.text_color = text_color
        
    def setTextSize(self, text_size):
        self.text_size = text_size
        self.my_font = pygame.font.Font(self.font_path, self.text_size)
        
    def setBorderWidth(self, border_width):
        self.border_width = border_width
        
    def setBorderColor(self, border_color):
        self.border_color = border_color
        
    def getCharWH(self):
        padding_percent_width = 0.3
        padding_percent_height = 0.3
        test_text1 = '测试字符串'
        test_text2 = self.my_font.render(test_text1, True, self.text_color)
        char_width = test_text2.get_width() / len(test_text1)
        char_height = test_text2.get_height()
        padding_width = char_width * padding_percent_width
        padding_height = char_height * padding_percent_height
        line_max_char = int((self.w - padding_width * 2) / char_width)
        
        return (char_height, padding_width, padding_height, line_max_char)
    
    def getTrueLines(self, char_height, padding_width, padding_height, line_max_char):
        texts = self.text.split("\n")
        k = 0
        for i,mytext in enumerate(texts):
            while len(mytext) > line_max_char:
                submytext = mytext[0:line_max_char]
                mytext = mytext[line_max_char:]
                k += 1
            k += 1
        return k+1
        
    def draw(self, win):
        (char_height, padding_width, padding_height, line_max_char) = self.getCharWH()
        lineNum = self.getTrueLines(char_height, padding_width, padding_height, line_max_char)
        if lineNum * char_height > self.h:
            self.h = lineNum * char_height
            
        pygame.draw.rect(win, self.color, (self.x, self.y, self.w, self.h))
        if self.border_width > 0:
            pygame.draw.rect(win, self.border_color, (self.x, self.y, self.w, self.h), self.border_width)
        
        texts = self.text.split("\n")
        k = 0
        for i,mytext in enumerate(texts):
            while len(mytext) > line_max_char:
                submytext = mytext[0:line_max_char]
                
                subtext = self.my_font.render(submytext, True, self.text_color)
                submyx = self.x + padding_width
                submyy = self.y + padding_height + char_height * k
                win.blit(subtext, (submyx, submyy))
                
                mytext = mytext[line_max_char:]
                k += 1
            
            text = self.my_font.render(mytext, True, self.text_color)
            myx = self.x + padding_width
            myy = self.y + padding_height + char_height * k
            win.blit(text, (myx, myy))
            k += 1
    
    
bt = Button(5, 5, 80, 25)
bt.setText('测试按钮')
bt.setColor('Brown')
bt.setTextColor('Gold')
bt.setBorderColor('Lime')
bt.setBorderWidth(1)

label_text = '''
我我我我我我我我我我我我我我我我我我我我我我我我
111111111111111111111111111111111111111111111
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
.。。。。。。。。。。。。。。。。。。。。。。。。
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'''.strip()
label = Label(115, 5, 250, 250)
label.setColor('Maroon')
label.setText(label_text)
label.setTextSize(18)
label.setBorderColor('Lime')
label.setBorderWidth(1)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            if bt.click(event):
                showMsg("%s被点击了" % bt.getText())
            
    keys_pressed = pygame.key.get_pressed()
    
    #ESC键
    if keys_pressed[pygame.K_ESCAPE]:
        running = False
        
    screen.fill("purple")
    
    bt.draw(screen)
    label.draw(screen)
        
    #更新显示
    pygame.display.flip()
    #pygame.display.update()
    
    dt = clock.tick(60) / 600
    
pygame.quit()

  

效果:

 

标签:控件,封装,color,text,self,height,char,width,pygame
From: https://www.cnblogs.com/xuxiaobo/p/18384105

相关文章

  • 【C#】【Winform】自定义控件、自定义事件
    https://blog.csdn.net/m0_62366581/article/details/139553373在开发桌面的过程中,有时候自带的控件样式或者功能上可能不一定能够满足我们的所有要求。这时候,我们需要自定义控件。创建类库项目把图标拖放到资源文件中添加用户控件设置样式尺寸修改代码视图其他项目中复用......
  • 使用FastAPI来开发项目,项目的目录结构如何规划的一些参考和基类封装的一些处理
    使用FastAPI开发项目时,良好的目录结构可以帮助你更好地组织代码,提高可维护性和扩展性。同样,对基类的封装,也可以进一步减少开发代码,提供便利,并减少出错的几率。下面是一个推荐的目录结构示例:my_fastapi_project/├──app/│├──__init__.py│├──main.py......
  • C++面向对象三大特性之一(封装)
    下面这篇文我来给大家分享C++面向对象三大特性之一(封装)。一、什么是封装?分装就是一个类中的私有成员,虽然类外不可以访问,但是我们提供一些公共的接口来间接让其他人访问到,例如一个人的名字我们起好之后就一般不会允许其他人改你的姓名,但是我们可以通过一些方式得到你的姓名......
  • js 封装日志上传模块,实现异常日志的上报
    封装定义日志上传模块,实现异常日志的上报,包含触发方式:1、主动调取方法上报2、覆盖原生console.error实现,收集所有console.error打印的日志3、window注册绑定error事件,触发 window.addEventListener('error',/***客户端日志上传模块,实现异常日志的上报*使用时在HTML......
  • pygame手搓贪吃蛇
    代码:#coding=utf-8importos,sys,re,timeimportpygameimportrandomfromwin32apiimportGetSystemMetricsimportcopypygame.init()pygame.display.set_caption("贪吃蛇")percent=0.6screen_width=GetSystemMetrics(0)screen_height=GetSystemM......
  • quill-editor 富文本 组件封装并实现自定义上传图片
    基于quill-editor封装一个富文本组件,并实现自定义上传图片以及视频1.下载quill-editor npminstallvue-quill-editor--save2.对插件进行自定义改造(自定义字体大小选择,自定义标题,以及自定义工具栏功能) <template><divclass="edtior-box"><quill-editor......
  • Vant4+Vue3 实现年月日时分时间范围控件
    <van-popup v-model:show="showDatePick" position="bottom" :overlay-style="{zIndex:1000}"> <van-picker-group title="时间范围" :tabs="['开始日期','结束日期']" @confirm="on......
  • 基于Material Design风格开源的Avalonia UI控件库
    前言今天大姚给大家分享一款基于MaterialDesign风格开源、免费(MITLicense)的AvaloniaUI控件库:Material.Avalonia。当前项目还处于alpha阶段。Avalonia介绍Avalonia是一个强大的框架,使开发人员能够使用.NET创建跨平台应用程序。它使用自己的渲染引擎绘制UI控件,确保在Window......
  • VBA学习(60):补充:Excel VBA 选择输入/TreeView控件/在工作表中如何顺利使用TreeView控
    上一篇文章我们分享了一例通过TreeView控件,实现会计科目的选择输入的方法,(ExcelVBA选择输入/TreeView控件):然而,当今天我打开它准备发送给索要示例文件的小伙伴的时候,咦,这是什么鬼?再进入设计模式:TreeView1这个控件,它在啊在代码窗口查看:名称怎么变成了TreeView41?难......
  • 手把手教你—搭建Vue3企业级项目规范+基础封装配置
    前言如何搭建一个简易脚手架。核心需求是输入项目命令,clone准备好的项目模板,拉到本地后,装一下依赖,就可以直接开发了。不用每次都花大量时间,去搭建项目规范和做必要的封装配置。经过简单寻找后,发现没有符合自己预期的。从0到1搭建一个具备完善规范的Vue3开发模板✨,并手把手带大......