此代码是重复的,因此我应该使用辅助函数来调用此函数还是对其进行封装?
if exitcode==0:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
else:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(youwin, (0,0))
screen.blit(text, textRect)
唯一的区别是if-else语句screen.blit(youwin / youlose, (0,0))
和text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0) / (255,0,0))
的倒数第二行
这是我使用助手功能所做的,但无法运行:
if exitcode==0:
initialize_game()
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
produce_text_on_screen()
else:
initialize_game()
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
produce_text_on_screen()
def initialize_game():
pygame.font.init()
font = pygame.font.Font(None, 24)
def produce_text_on_screen():
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
NameError:未定义名称“ initialize_game”。 一些帮助会很棒,谢谢!!
答案 0 :(得分:0)
在Python中,函数定义的顺序很重要。在幕后,def
只是一个赋值,在执行时赋给函数名称。这意味着函数定义必须先于其使用:
def initialize_game():
pygame.font.init()
font = pygame.font.Font(None, 24)
def produce_text_on_screen():
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
if exitcode==0:
initialize_game()
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
produce_text_on_screen()
else:
initialize_game()
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
produce_text_on_screen()
或更准确地说,定义不一定总是要在源代码中排在首位,它们只必须先被执行 ,以便在使用时定义名称。
答案 1 :(得分:0)
您可以使用三元运算符(value1 if condition else value2
):
result = gameover if exitcode == 0 else youwin
color = (255, 0, 0) if exitcode == 0 else (0, 255, 0)
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: " + str(accuracy) + "%", True, color)
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery + 24
screen.blit(result, (0, 0))
screen.blit(text, textRect)
当然,创建函数绝不是一个坏主意。
def show_final_screen(result, color, accuracy):
# ...
if exitcode == 0:
show_final_screen(gameover, (255, 0, 0), accuracy)
else
show_final_screen(youwin, (0, 255, 0), accuracy)