首页 > 解决方案 > Pygame:打破文本行以适应屏幕

问题描述

所以,我正在开发一个客户端-服务器应用程序,其中客户端向服务器请求一些信息,并在接收到它后,客户端在 Pygame 屏幕上显示信息。问题是我从服务器获得的信息以列表的形式出现(因为我使用了 pickle 库来发送它),并且我无法将此列表分成单独的行以适应屏幕。

例如,这是来自服务器端的代码,用于发送有关服务器的 cpu 使用情况、内存等信息:

def mostra_uso_cpu_e_ram(socket_cliente):
    info1 =('Usuario solicitou Informações de uso de processamento e Memória')
    resposta = []
    cpu = ('Porcentagem: ',psutil.cpu_percent())
    resposta.append(cpu)
    processador = ('Nome e modelo do processador: ',cpuinfo.get_cpu_info()['brand'])
    resposta.append(processador)
    arquitetura = ('Arquitetura: ',cpuinfo.get_cpu_info()['arch'])
    resposta.append(arquitetura)
    palavra = ('Palavra do processador:', cpuinfo.get_cpu_info()['bits'])
    resposta.append(palavra)
    ftotal = ('Frequência total do processador:', cpuinfo.get_cpu_info()['hz_actual'])
    resposta.append(ftotal)
    fuso = ('Frequência de uso:', psutil.cpu_freq()[0])
    resposta.append(fuso)
    disk = ('Porcentagem de uso do disco:', psutil.disk_usage('/')[3])
    resposta.append(disk)
    mem = psutil.virtual_memory()
    mem_percent = mem.used/mem.total
    memoria = ('Porcentagem de memória usada:', mem_percent)
    resposta.append(memoria)
    bytes_resp = pickle.dumps(resposta)
    socket_cliente.send(bytes_resp)
    print(info1)

这是客户端:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 9999))

bytes_resp = s.recv(1024)
lista = pickle.loads(bytes_resp)

# Pygame screen and surface settings 
largura_tela = 800
altura_tela = 600
tela = pygame.display.set_mode((largura_tela, altura_tela))
background = pygame.Surface(tela.get_size())
tela.blit(background, (0,0))

#function used to break lines but shows nothing
#indentation seems a little lot to the right because it's inside another block of text

       def drawText(surface, text, rect, color, font, aa=False, bkg=None):
            rect = pygame.Rect(rect)
            text = str(lista)
            y = rect.top
            lineSpacing = -2

            fontHeight = font.size("Tg")[1]

            while text:
                i = 1

                if y + fontHeight > rect.bottom:
                    break

                # determine maximum width of line
                while font.size(text[:i])[0] < rect.width and i < len(text):
                    i += 1

                # if we've wrapped the text, then adjust the wrap to the last word      
                if i < len(text): 
                    i = text.rfind(" ", 0, i) + 1

                # render the line and blit it to the surface
                if bkg:
                    image = font.render(text[:i], 1, color, bkg)
                    image.set_colorkey(bkg)
                else:
                    image = font.render(text[:i], aa, color)

                surface.blit(image, (rect.left, y))
                y += fontHeight + lineSpacing

                text = text[i:]

            return text
        
        drawText(background, str(lista), (30,400,1300,350), verde, font, aa=True, bkg=None)

我要渲染的列表是这个:

[('Porcentagem: ', 15.2), ('Nome e modelo do processador: ', 'Intel(R) Core(TM) i5-4288U CPU @ 2.60GHz'), ('Arquitetura: ', 'X86_64'), ('Palavra do processador:', 64), ('Frequência total do processador:', '2.6000 GHz'), ('Frequência de uso:', 2600), ('Porcentagem de uso do disco:', 11.1), ('Porcentagem de memória usada:', 0.48642539978027344)]

我的问题是:如何将这些列表分成几行,或者至少让它们适合 pygame 表面边界?从 pygame 网站获得了这个功能,但我不确定我哪里出错了?

标签: pythonpython-3.xpygame

解决方案


以下是将列表转换为文本行列表的方法:

lst = [('Porcentagem: ', 15.2), ('Nome e modelo do processador: ', 'Intel(R) Core(TM) i5-4288U CPU @ 2.60GHz'), ('Arquitetura: ', 'X86_64'), ('Palavra do processador:', 64), ('Frequência total do processador:', '2.6000 GHz'), ('Frequência de uso:', 2600), ('Porcentagem de uso do disco:', 11.1), ('Porcentagem de memória usada:', 0.48642539978027344)]


lines = [''.join(map(str, items)) for items in lst]
print(lines)

输出:

['Porcentagem: 15.2', 'Nome e modelo do processador: Intel(R) Core(TM) i5-4288U CPU @ 2.60GHz', 'Arquitetura: X86_64', 'Palavra do processador:64', 'Frequência total do processador:2.6000 GHz', 'Frequência de uso:2600', 'Porcentagem de uso do disco:11.1', 'Porcentagem de memória usada:0.48642539978027344']

由于您没有提供MRE,因此我无法轻松对其进行测试。一个潜在的问题可能是该drawText()函数看起来像是假设字体中的字符都具有相同的宽度,但并非所有字体都如此。


推荐阅读