我试图使用while循环在两个用户之间交替切换,但是我的代码被卡在“whilefirst\u player\u move is True:”循环上。我怎样才能解决这个问题,让我的while循环通过两个玩家的回合。你知道吗
我尝试过在不同的地方添加“continue”和“break”,并尝试过将布尔值向上切换,但似乎没有任何效果。你知道吗
word_fragment = ''
first_player_move = True
while True:
while first_player_move is True:
added_letter = input('Which single letter would you like to add to the fragment? ')
word_fragment += added_letter
print('The current word fragment is: ' + word_fragment)
print('It is now ' + player2_name + "'s turn.")
if word_fragment in open('data.txt').read() and len(word_fragment) > 3:
print('I am sorry, you just lost. ' + player2_name + ' is the winner!')
# call a function to end the game
break
while first_player_move is False:
added_letter = input('Which single letter would you like to add to the fragment? ')
word_fragment += added_letter
print('The current word fragment is: ' + word_fragment)
print('It is now ' + player1_name + "'s turn.")
if word_fragment in open('data.txt').read() and len(word_fragment) > 3 :
print('I am sorry, you just lost. ' + player1_name + ' is the winner!')
# call a function to end the game
break
我希望输出贯穿每个玩家的回合,并最终打印“它现在是'下一个玩家的回合'”,但相反,它一直打印出相同的名称,为下一个玩家回合,这是告诉我,代码是卡在两个while循环的第一个。你知道吗
下面的方法可能效果更好。其目的是尽量避免重复代码,而是使用变量来帮助:
它使用
player_name
来保存当前播放器的名称,对于每个循环,first_player_move
在True
和False
之间切换。你知道吗因为
first_player_move
没有变为false
,所以当内部循环结束时,外部循环开始一个新的循环并再次调用内部循环。你知道吗顺序流程为:
True
#so truefirst_player_move
是True
#如此真实执行内部块,然后
breaks
,转到第一个循环,重复上面的步骤输入第一个循环=>;
True
#so truefirst_player_move
是True
#所以是真的在第一个循环中,您永远不会将第一个玩家移动设置为false(在第二个循环中也永远不会将其设置为true)。你知道吗
我建议将打印内容(“现在”+player2\u name+“'s turn.”)移动到if中,然后进行修改:
与第二个玩家循环相当。你知道吗
我还要确认一下你的胜负情况。如果有人负责创建包含在数据.txt如果碎片超过3个字符,它们就会丢失。是这样吗?你知道吗
如果是这样的话,还有一个小小的优化,可以用来缩小数据.txt. 去掉3个或更少字符的所有单词,就可以删除len(word\u fragment)>;3约束。你知道吗
我想你还会遇到另一个问题。。。如果玩家得到了一个相当大的碎片,但仍然没有匹配到任何一个碎片,会发生什么数据.txt?你知道吗
您可能需要考虑创建一个连接条件。例如,在主“while True”循环的末尾,测试长度>;中最长的单词数据.txt打成平手。你知道吗
进一步的风格建议。玩家的回合不需要使用循环:
加分,如果你能得到与只有一个提示\u然后\u测试代码和球员之间的名字切换通过。你知道吗
相关问题 更多 >
编程相关推荐