首页 > 解决方案 > Python:如何使用函数调用来切换大小写以进行 Pygame 显示

问题描述

我正在尝试做一个简单的应用程序,用不同的参数调用相同的函数。

这是代码片段:

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def message_display(text, size, x, y): 
    #print(pygame.font.get_fonts())
    font = pygame.font.Font(None, size) 
    text_surface, text_rectangle = text_objects(text, font) 
    text_rectangle.center = (x, y) 
    gameDisplay.blit(text_surface, text_rectangle) 

def countdown(count_case):
    
    print("Checking Case")
    print(count_case)

    switcher={
            1: message_display("starting in 5", 40, display_width / 2, (display_height + 400) / 2),
            2: message_display("starting in 4", 40, display_width / 2, (display_height + 400) / 2),
            3: message_display("starting in 3", 40, display_width / 2, (display_height + 400) / 2),
            4: message_display("starting in 2", 40, display_width / 2, (display_height + 400) / 2),
            5: message_display("starting in 1", 40, display_width / 2, (display_height + 400) / 2)
            }
    func = switcher.get(count_case,"Invalid Countdown")
    return func()

我可以通过检查来初始化 Pygame 屏幕并count_case正确传递给函数。countdown()print()

但是,我主要不知道message_display基于count_case' 值正确调用和执行函数的语法;1 到 5。提前致谢。

标签: pythonfunctionpygameswitch-statement

解决方案


你根本不需要听写/开关。您可以改为根据输入格式化显示的字符串

def countdown(count_case):
    if count_case < 1 or count_case > 5:
        raise ValueError("count_case must be between 1 and 5")
    return message_display(f"starting in {6 - count_case}", 40, display_width / 2, (display_height + 400) / 2)

推荐阅读