如何解决如何在不复制粘贴的情况下复制一个函数以进行一些更改以创建另一个函数
def welcome():
exit_game = False
while not exit_game:
global red,green
game_window.fill((233,109,102))
screen_text("welcome to snakes",black,160,240)
screen_text("press spacebar to play",144,260)
pygame.draw.rect(game_window,red,[76,425,70,32])
pygame.draw.rect(game_window,green,[355,32])
screen_text("PLAY",86,432)
screen_text("QUIT",365,432)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_game = True
if event.type == pygame.MOUSEBUTTONDOWN:
print(event.button)
if 425<pygame.mouse.get_pos()[1]<457:
if 76<pygame.mouse.get_pos()[0]<146 :
try:
pygame.mixer.music.load(os.path.join(dir,song_num))
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play()
except Exception as e:
print("Could not load the music")
game_loop()
if 355<pygame.mouse.get_pos()[0]<425:
exit_game = True
if 425<pygame.mouse.get_pos()[1]<457:
if 76<pygame.mouse.get_pos()[0]<146 :
red = (255,0)
if 355<pygame.mouse.get_pos()[0]<425:
green = (0,255,0)
else :
red = (200,0)
green = (0,200,0)
pass
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
try:
pygame.mixer.music.load(os.path.join(dir,song_num))
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play()
except Exception as e:
print("Could not load the music")
game_loop()
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
之后,我想在用户按下p
时制作一个暂停屏幕,其中我复制了上面的函数并对其进行了修改,例如
def paused():
while pause:
global red,102))
screen_text("paused",240)
# screen_text("",135,32])
screen_text("CONTINUE",432)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
print(event.button)
if 425<pygame.mouse.get_pos()[1]<457:
if 76<pygame.mouse.get_pos()[0]<76+ 135 :
try:
pygame.mixer.music.unpause()
except Exception as e:
print("Could not load the music")
unpause()
if 355<pygame.mouse.get_pos()[0]<425:
pygame.quit()
exit()
if 425<pygame.mouse.get_pos()[1]<457:
if 76<pygame.mouse.get_pos()[0]<76 + 135:
red = (255,0)
pygame.display.update()
clock.tick(60)
我只想改变一些东西,比如暂停音乐和改变按钮和按键的功能。
有没有其他方法可以做到这一点而不是复制它?我可以像在类中一样继承并更改一些代码或添加更多更改吗?
解决方法
为您要在较大函数中更改的每个内容设置一个条件参数。也许类似于以下内容。
welcome=1
pause=0
def myfunction(variable=""):
if welcome:
print("welcome") # set some buttons/music
variable=1
print(variable)
if pause:
print("pause") # set different buttons/music
variable=2
print(variable)
if welcome:
print("do something unique")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。