【问题标题】:How to change label text without overlapping using PyGame? [duplicate]如何使用 PyGame 更改标签文本而不重叠? [复制]
【发布时间】:2018-10-15 06:29:47
【问题描述】:

当我使用 font.render 然后 screen.blit 显示新分数时,新分数与旧分数重叠,即使在搜索类似问题后也找不到解决方案。可能有一个很好的解决方案?感谢您的建议。

import pygame
import sys

WIDTH = 400
HEIGHT = 400
GREY_COLOUR = [150, 150, 150]
WHITE_COLOUR = [255,255,255]
center = (int(WIDTH / 2), int(HEIGHT / 2))
CIRCLE_RADIUS = 100


class Main:
    count = 0

    def __init__(self, screen):
        self.screen = screen
        self.running = True
        self.main_loop()

    def render(self):
        pygame.display.flip()


    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_SPACE:
                    self.count+=1
                    self.showScore()

    def showScore(self):
        font = pygame.font.SysFont('Comic Sans MS', 30)
        scoretext = font.render("Score:" + str(self.count), 1, (0, 0, 0))
        screen.blit(scoretext, (center[0], center[1]-200))


    def main_loop(self):
        while self.running:
            self.handle_events()
            self.render()


pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
screen.fill(WHITE_COLOUR)
pygame.draw.circle(screen, GREY_COLOUR, center, CIRCLE_RADIUS, 2)
pygame.display.update()
game = Main(screen)

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案1】:

    我认为你可以为渲染函数提供背景,所以它不是透明的。

    以白色为例:

    scoretext = font.render("Score:" + str(self.count), True, (0, 0, 0), (255, 255, 255))
    

    如果我没记错的话,第二个参数 antialias 是一个布尔值,所以它应该是 True

    【讨论】:

    • 谢谢你,圣地亚哥。解决了总比没有好。但如果旧分数的位数多于新分数,它仍然不起作用 - 旧分数的最后一位数字没有填充空白。
    • 在这种情况下,您可能需要先清除该区域,方法是在文本区域中显示一个白色表面。也许您可以在打印下一个分数之前保留前一个分数表面的尺寸以进行清洁。其他解决方法可能是在字符串末尾添加一些空格...scoretext = font.render("Score:%s " % self.count, True, (0, 0, 0), (255, 255, 255))
    • 我认为您的决定对我的学习项目来说已经足够了。感谢您的帮助:)(当我的声望达到 15 时,投票将计入)
    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    相关资源
    最近更新 更多