改变转向不正常工作

时间:2016-09-18 19:17:54

标签: python tic-tac-toe

只是卡在我的代码中,正在寻找其他来源,但还有其他实现,我必须是盲目的......但看起来函数仍然指向一个变量,在我开始时理解我是否调用函数返回'更改',函数返回到代码中的某个位置,当它不应该到达声明的早期变量时,但是从函数返回的那个变量和下一个调用相同函数的应该再次切换我的变量(X和O),只需剪切一块这段代码:得到X或O(我选择的是什么),打印变量是否正确,但是函数输出是XXX等等...(我刚开始学习,但只是卡在这里!)

def choice():
    choice = input("You want to have x or o?: ")
    if choice == 'x':
        human = 'X'
        computer = 'O'
    else: 
        human = 'O'
        computer = 'X'
    return human, computer

human, computer = choice()
print("human is ", human)
print("computer is ", computer)

def next_player(turn):
    if turn == 'X':
        return 'O'
    else:
        return 'X'

turn = 'X'

print("turn is ", turn)
turn = next_player(turn) # was here: next_player(turn) and so below!!
print("after next player function turn is ", turn)
turn = next_player(turn)
print("after next player function turn is ", turn)

3 个答案:

答案 0 :(得分:1)

您正在turn中返回next_player()

def next_player(turn):
    if turn == 'X':
        turn = 'O'
    if turn == 'O':
        turn = 'X'
    return turn # <<< Here.

如果您想指定新转弯,请尝试执行以下操作:

turn = next_player(turn)

而不是:

next_player(turn)

答案 1 :(得分:1)

def next_player(turn):
if turn == 'X':
    turn = 'O'
if turn == 'O':
    turn = 'X'
return turn

此变量返回保存在哪里?我不相信它正在更新你的转弯&#39;变量,因此你只是打印&#39; X&#39;一遍又一遍。

答案 2 :(得分:0)

  1. second&#34; if&#34;应该是一个&#34; elif&#34;。 看看你的代码,你总是回来&#34; X&#34;现在。
  2. 变量&#34;转&#34;不是一个全局变量。如果你通过next_player&#34;转&#34;作为一个参数,你正在复制变量的值&#34;转&#34;含蓄。变量&#34;转&#34;函数内部与变量&#34;转&#34;不一样外面的功能!
  3. 从next_player(转弯)获取正确的值:turn = next_player(转)