我写了一个井字游戏程序,一切正常,但是当我输入数字 7 时,它说:选择不可用!也就是说,好像 7 无法与 available(location, board) 函数中的 7 进行比较。我不明白错误在哪里。
from IPython.display import clear_output #to clear the output (specific to Jupyter notebooks and ipython)
from random import randint
def draw(board):
for row in board:
print ("\t {} | {} | {}".format(*row))
print ("\t ","-"*10)
def available(location, board):
for row in board:
for col in row:
if location == col:
return False
else:
return True
def mark(player, location, board):
for row in board:
if location in row:
ind = row.index(location)
row.pop(ind)
row.insert(ind, player)
def check_win(board):
if board[0][0] == board[1][0] and board[1][0] == board[2][0]:
return True
elif board[0][1] == board[1][1] and board[1][1] == board[2][1]:
return True
elif board[0][2] == board[1][2] and board[1][2] == board[2][2]:
return True
elif board[0][0] == board[0][1] and board[0][1] == board[0][2]:
return True
elif board[1][0] == board[1][1] and board[1][1] == board[1][2]:
return True
elif board[2][0] == board[2][1] and board[2][1] == board[2][2]:
return True
elif board[0][0] == board[1][1] and board[1][1] == board[2][2]:
return True
elif board[0][2] == board[1][1] and board[1][1] == board[2][0]:
return True
else:
return False
def check_tie(board):
for row in board:
for col in row:
if col.isdigit():
return False
break
else:
return True
def dashes():
print("o" + 35 *'-' + "o")
def display(message):
print("|{:^35s}|".format(message))
def main():
# initializing game
board = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3']]
# select the first player randomly
player = ['X', 'O']
turn = randint(0, 1)
win = False
tie = False
while(not win and not tie):
# switch players
turn = (turn + 1) % 2
current_player = player[turn] # contains 'X' or 'O'
clear_output()
# display header
dashes()
display("TIC TAC TOE")
dashes()
# display game board
print()
draw(board)
print()
# display footer
dashes()
# player select a location to mark
while True:
location = input("|{:s} Turn, select a number (1, 9): ".format(current_player))
if available(location, board):
break # Only the user input loop, main loop does NOT break
else:
print("Selection not available!")
dashes()
# mark selected location with player symbol ('X' or 'O')
mark(current_player, location, board)
# check for win
win = check_win(board)
# check for tie
tie = check_tie(board)
# Display game over message after a win or a tie
clear_output()
# display header
dashes()
display("TIC TAC TOE")
dashes()
# display game board (Necessary to draw the latest selection)
print()
draw(board)
print()
# display footer
dashes()
display("Game Over!")
if(tie):
display("Tie!")
elif(win):
display("Winner:")
display(current_player)
dashes()
main()
更正了错误。这是解决方案: