我正在开发一款井字游戏,该游戏的功能是将列表中的连字符替换为 X 和 O 以形成网格。我也是 python 的初学者,所以这段代码会很笨重。问题是我希望游戏可以重新玩,但我找不到将列表重置为开始时使用的连字符的方法。这是一段简化的代码,可以更好地说明问题:list = ["-","-","-", "X","O"]def replace(): list[0] = list[3]def main(): replace() play_again = input ("play again?") if play_again == "yes": main() else: exit() main()这使得列表从["-","-","-", "X","O"]变为["X","-","-", "X","O"],从而使游戏正常运行。我希望能够做的是以某种方式回到list玩家["-","-","-", "X","O"]再次玩游戏的时候。不幸的是,该列表似乎停留在["X","-","-", "X","O"]. 我试过了:list = ["-","-","-", "X","O"]在上方添加replace()list[0] = "-"在上方添加replace()这些选项都不起作用。是否可以将 的值重置list为我开始时的值?如果是这样,我应该如何处理这个问题?
1 回答
噜噜哒
TA贡献1784条经验 获得超7个赞
使您的代码“工作”的最简单的更改是:
def main():
global list
list = ["-","-","-", "X","O"]
replace()
play_again = input ("play again?")
if play_again == "yes":
main()
else:
exit()
(虽然这不是我从头开始做这件事的方式——但你已经指出笨重的代码是可以的/预期的,所以我不打算在这里尝试修复它。)
这也将起作用,并且不需要global声明:
def main():
list[:] = ["-","-","-", "X","O"]
replace()
play_again = input ("play again?")
if play_again == "yes":
main()
else:
exit()
添加回答
举报
0/150
提交
取消