Python Tic Tac Toe代码问题

时间:2018-03-10 07:45:42

标签: python-3.x

我尝试使用Python创建一个tic tac toe游戏,但它无法正常工作。有人可以看看它并告诉我是否犯了错误吗?

当我运行游戏时,它只打印电路板,然后要求输入x。一旦我键入,游戏就打印出一块板并关闭。

def tic_tac_toe(): 

   end = False 
   win_combinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
   board = [1,2,3,4,5,6,7,8,9]
   def draw():
      print(board[0], board[1], board[2]) 
      print(board[3], board[4], board[5])
      print(board[6], board[7], board[8])
      print()
   def player_option_check():
      while True:
        try:
            arg1 = input("please enter number")
            arg1 = int(arg1)
            if arg1 in range(0,9):
                return arg1 - 1
            else:
                print ('not a number on he board')
        except:
            print('this is not a number re try')

   def player_X():

     choice = player_option_check()
     board[choice] = 'x'

   def player_y():

     choice = player_option_check()
     board[choice] = 'y'

   def check_winner_x ():
     for a in win_combinations:
         if board[a[0]] == board[a[1]] == board[a[2]] == 'o':
             print('player o wins')
             return True 
         if board[a[0]] == board[a[1]] == board[a[2]] == 'x':
             print('player x wins')
             return True 
     for a in range(9):
        if board[a] == "X" or board[a] == "O":
             count += 1
     if count == 9:
        print("The game ends in a Tie\n")
        return True
while not end:
    draw()
    end = check_winner_x
    if end == True:
        break
    else:
        player_X()
        draw()
        end = check_winner_x
        if end == True:
            break
        else:
            player_y()
            draw()
        if end==True:
            again_play=print(input("would u like to play again press (y/n)"))
            again_play == "y"
            tic_tac_toe()
        else:
            print('thanks for playing')
            break
tic_tac_toe()

那么请你帮我找一下代码中的错误。这是在Python 3中。

1 个答案:

答案 0 :(得分:0)

我假设这是因为你没有调用check_winner_x,只是将其分配给值end(在循环结束时可能print(end)以查看它的值)。

这意味着当您返回while语句时,end将注册为"truthy",因为它不再设置为false,并且循环将退出。< / p>

尝试实际调用check_winner_x

end = check_winner_x()

不确定其他任何可能有错误的东西,但这绝对是一个开始。