Pygame - текст по центру в движущемся прямоугольнике

Я делаю игру с числами в pygame, и у меня есть квадраты, которые будут падать с верхней части экрана вниз, имея числовое значение, и это число отображается на каждом квадрате. Я изо всех сил пытаюсь получить текст по центру квадрата, и это усложняется, когда каждое число может содержать от 1 до 4 цифр.

class sqr:
    def __init__(self):
        self.colours = [(255,0,0), (0,255,0), (0,0,255)]
        self.Xpositions = [0,125,245,365,485]
        self.OnScreen = False
        self.X = random.choice(self.Xpositions) 
        self.Y = 0
        self.colour = random.choice(self.colours)
        self.number = random.choice([20,40,80])
        self.numberFont =  pygame.font.Font("TitilliumWeb-Black.ttf", 48)

    def drawSquare(self, colour,  X, Y):
        pygame.draw.rect(screen, colour, (X, Y, 120, 120))

    def numberTextFunc(self, X, Y):
        numberText = self.numberFont.render(f"{self.number}", True, (87, 63, 63))
        screen.blit(numberText, (X , Y))

square = sqr()

gameRunning = True
while gameRunning:

    background = screen.fill((0,100,140))
    
    #draw lines for grid
    for i in range(5):
        pygame.draw.rect(screen, (0,0,0), (line[i], 0 , 5, 800))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameRunning = False

    #square
    square.drawSquare(square.colour, square.X, square.Y)
    square.numberTextFunc(square.X, square.Y)
    square.OnScreen = True

    square.Y += 1

    if square.Y >= 680:
        square.Y = 680

    pygame.display.update()

person logan9997    schedule 09.07.2021    source источник


Ответы (1)


Используйте pygame.Surface.get_rect, чтобы получить текстовый прямоугольник. pygame.Surface.get_rect.get_rect() возвращает прямоугольник размером < em>Surface, который всегда начинается с (0, 0). Установите центр текстового прямоугольника по центру квадрата. Используйте текст reectnagle для blit текста. Второй аргумент blit является либо кортежем (x, y), либо прямоугольником. В случае прямоугольника учитывается только верхний левый угол прямоугольника. Поэтому вы можете передать текстовый прямоугольник непосредственно в blit:

class sqr:
    # [...]

    def numberTextFunc(self, X, Y):
        numberText = self.numberFont.render(f"{self.number}", True, (87, 63, 63))
        rect = pygame.Rect(X, Y, 120, 120)
        textRect = numberText.get_rect(center = rect.center)
        screen.blit(numberText, textRect)

Вы можете упростить свой код. X и Y являются атрибутами объекта. Следовательно, нет необходимости передавать координаты методам:

class sqr:
    def __init__(self):
        self.colours = [(255,0,0), (0,255,0), (0,0,255)]
        self.Xpositions = [0,125,245,365,485]
        self.OnScreen = False
        self.X = random.choice(self.Xpositions) 
        self.Y = 0
        self.colour = random.choice(self.colours)
        self.number = random.choice([20,40,80])
        self.numberFont =  pygame.font.Font("TitilliumWeb-Black.ttf", 48)

    def drawSquare(self, colour):
        pygame.draw.rect(screen, colour, (self.X, self.Y, 120, 120))

    def numberTextFunc(self):
        numberText = self.numberFont.render(f"{self.number}", True, (87, 63, 63))
        rect = pygame.Rect(self.X, self.Y, 120, 120)
        textRect = numberText.get_rect(center = rect.center)
        screen.blit(numberText, textRect)
gameRunning = True
while gameRunning:

    background = screen.fill((0,100,140))

    #draw lines for grid
    for i in range(5):
        pygame.draw.rect(screen, (0,0,0), (line[i], 0 , 5, 800))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameRunning = False

    #square
    square.drawSquare(square.colour)
    square.numberTextFunc()
    square.OnScreen = True

    square.Y += 1
    if square.Y >= 680:
        square.Y = 680

    pygame.display.update()
person Rabbid76    schedule 09.07.2021