微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:如何使用 Pygame 显示的函数调用切换大小写

如何解决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",3: message_display("starting in 3",4: message_display("starting in 2",5: message_display("starting in 1",(display_height + 400) / 2)
            }
    func = switcher.get(count_case,"Invalid Countdown")
    return func()

我能够通过检查 count_case 来初始化 Pygame 屏幕并将 countdown() 正确传递到 print() 函数中。

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

解决方法

表达式

message_display("starting in 5",40,display_width / 2,(display_height + 400) / 2)

是一个函数调用。因此,您实际上将 message_display 的返回值存储在字典中。只需存储一个带有参数的元组:

switcher = {
    1: ("starting in 5",(display_height + 400) / 2),2: ("starting in 4",3: ("starting in 3",4: ("starting in 2",5: ("starting in 1",(display_height + 400) / 2)
}

使用星号 (*) 运算符(“unzip”)调用函数:

message_display(*switcher[count_case])

countdown 函数:

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

    switcher={
        1: ("starting in 5",display_width // 2,(display_height + 400) // 2),(display_height + 400) // 2)
    }
    return message_display(*switcher[count_case])
,

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

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}",(display_height + 400) / 2)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。