[英]How would I use functions to make my code not as repetitive and more efficient?
[英]how can I replace this repetitive code with a more efficient function?
我目前正在 python 中构建 Tictac 脚趾游戏。 我已经完成了游戏,现在正试图让代码更有效率。 对于这个问题的上下文,我的井字游戏板是使用字典绘制的,并使用用户输入进行更改,如下所示:
spots = {1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
如果用户在游戏完成后给出某个输入,我有一个 function 来循环游戏。 function 看起来像这样:
def wants_to_play_again(spots):
play_again = input('Do you wanna play again?\n Press (a) to continue... \n Press any other key to exit the game: ')
if play_again == 'a':
print('\n')
return True
else:
print('\nSee you later! Thanks for playing')
return False
稍后在游戏本身的代码中,我说如果上面的 function 返回 true,那么我重置板,它看起来像这样:
if wants_to_play_again(spots) is True:
spots = {1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
available_spots = [1, 2, 3, 4, 5, 6, 7, 8, 9]
continue
else:
break
我的问题是,如果棋盘返回平局,我会在游戏循环中再次重用这段代码^。 我的问题是如何压缩这段代码,这样我就不必使用 5 行代码来重置 board 和 available_spots 元素。 我可以把它变成只需要写一次的 function 吗? 这可能吗? 谢谢您的帮助。
def wants_to_play_again(spots):
play_again = input('Do you wanna play again?\n Press (a) to continue... \n
Press any other key to exit the game: ')
if play_again == 'a':
spots = {1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
available_spots = [1, 2, 3, 4, 5, 6, 7, 8, 9]
return
else:
print('\nSee you later! Thanks for playing')
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.