簡體   English   中英

Python游戲| TypeError:“ NoneType”類型的參數不可迭代

[英]Python Game | TypeError: argument of type 'NoneType' is not iterable

因此,我正在閱讀一本python書籍,並被要求創建一個井字游戲並相對理解我的代碼。 是時候運行程序了,我得到了這個奇怪的錯誤

TypeError:“ NoneType”類型的參數不可迭代

完整的錯誤是:

Traceback (most recent call last):
   File "Tac Tac Toe Game revised.py", line 182, in <module>
     main()
   File "Tac Tac Toe Game revised.py", line 173, in main
     move = human_move(board, human)
   File "Tac Tac Toe Game revised.py", line 100, in human_move
     while move not in legal:
TypeError: argument of type 'NoneType' is not iterable

這是它在line 173引用的代碼

def main():
    display_instruction()
    computer,human = pieces()
    turn = X
    board = new_board()
    display_board(board)

   while not winner(board):
       if turn == human:
           move = human_move(board, human)
           board[move] == human
       else:
           move = computer_move(board,computer,human)
           board[move] == computer
       display_board(board)
       congrats_winner(the_winner,computer, human)

在以下功能中發生錯誤:

def human_move(board,human):
'''Get human move'''
legal = legal_moves(board)
move = None
while move not in legal:
    move = ask_number('Where will you move? (0-8): ',0, NUM_SQUARES)
    if move not in legal:
        print ('\nThat square is already occupied, foolish human. Choose another.\n')
print('Fine...')
return move

我嘗試將move = None更改為move = ' '但這沒什么區別。 有任何想法嗎?

根據要求,這里是legal_moves的函數

def legal_moves(board):
'''Creates a legal list of moves'''
   moves = []
   for square in range(NUM_SQUARES):
      if board[square] == EMPTY:
          moves.append(square)

您需要返回moves列表:

def legal_moves(board):
    '''Creates a legal list of moves'''
    moves = []
    for square in range(NUM_SQUARES):
        if board[square] == EMPTY:
            moves.append(square)
    return moves

您忘記退還legal_moves中的任何內容

一個很好的解決方案是使用“屈服方”代替移動列表

您的問題是您無法對none變量執行while循環,而您嘗試不進行任何計數,所以這就是問題所在...

如果您對您的代碼不滿意,請幫忙

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM