如何在Pygame中显示与矩形位置相关的数字?

时间:2017-07-18 13:18:39

标签: python text fonts numbers pygame

我想在屏幕上移动矩形,让我们垂直说出并附加一个动态变化的数字并表示rect的位置,它甚至可能吗?非常感谢我的整个项目取决于此。

2 个答案:

答案 0 :(得分:1)

这是一个示例代码,显示按下鼠标左键时鼠标光标的位置。在这种情况下,"数字动态变化"是鼠标光标位置。

正如您在代码中看到的,我使用等宽字体(Windows中的Courier New),因此数字中的任何前导空格都不会改变数字的大小 - 带空格的数字12需要屏幕数量与199数量相同。每次通过主循环,每秒约60次,谢谢 在timer.tick(60)语句中,字符串是根据所需的数字构建的,然后从字符串构建一个名为text的表面,然后将表面布置到屏幕上。

是否清楚如何将此应用于您的情况?

"""A pygame "game" that shows the position of the mouse cursor while 
the left mouse button is pressed."""

import pygame

pygame.init()
screen = pygame.display.set_mode([800,600])
pygame.display.set_caption("Show the Position of the Mouse while Dragging")
BLACK= (0, 0, 0)
RED = (255, 0, 0)
timer = pygame.time.Clock()
font = pygame.font.SysFont("Courier New", 24)
mouse_is_down = False

keep_going = True
while keep_going:
    # Handle events.
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            keep_going = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            if pygame.mouse.get_pressed()[0]:    # Left mouse button
                mouse_is_down = True
        if event.type == pygame.MOUSEBUTTONUP:
            if not pygame.mouse.get_pressed()[0]:    # Left mouse button
                mouse_is_down = False

    # Draw the screen.
    screen.fill(BLACK)    
    if mouse_is_down:
        position = pygame.mouse.get_pos()
        position_string = 'Mouse position: ({:3d}, {:3d})'.format(*position)
    else:
        position_string = ''

    text = font.render(position_string, True, RED)
    text_rect = text.get_rect()
    text_rect.right = screen.get_rect().right - 10
    text_rect.y = 10
    screen.blit(text, text_rect)
    pygame.display.update()
    timer.tick(60)

pygame.quit()

答案 1 :(得分:1)

每次矩形位置发生变化时(例如,如果发生MOUSEMOTION事件),您需要重新渲染文本表面,然后在当前矩形位置将其blit。

import sys
import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    font = pg.font.Font(None, 32)
    font_color = (100, 200, 150)
    rect = pg.Rect(20, 200, 80, 50)
    txt_surf = font.render(str(rect.topleft), True, font_color)
    selected = None
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEBUTTONDOWN:
                if selected:
                    selected = None
                elif rect.collidepoint(event.pos):
                    selected = rect
            elif event.type == pg.MOUSEMOTION:
                if selected:
                    selected.center = event.pos
                    txt_surf = font.render(str(rect.topleft), True, font_color)

        screen.fill((30, 30, 30))
        pg.draw.rect(screen, font_color, rect, 2)
        screen.blit(txt_surf, (rect.right+10, rect.top))

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()