【发布时间】:2021-08-15 20:36:01
【问题描述】:
在这里学习 Python,对于任何无知深表歉意。背景 - 制作井字游戏的作业。完成了目标,但现在正在尝试处理异常。在某一时刻,由于某种原因,我的一个变量被无类型传递。下面列出了有问题的代码choice 是有问题的变量,应该是一个列表。奇怪的是它可以正常工作,除非用户首先在板上选择一个已经选择的位置,然后在函数的下一次迭代中发生故障。
def user_choice():
global board
row_choice = 0
column_choice = 0
if player_1 == True: # check whose turn
print("Player 1, ")
else:
print("Player 2, ")
while row_choice not in [1, 2, 3]: # loop until input is correct
row_choice = int(input("\tPlease select the row in which you would like to place your mark" +
" (1, 2, or 3 from top to bottom): "))
if row_choice not in [1, 2, 3]:
print("Sorry, you did not pick a valid number")
while column_choice not in [1, 2, 3]: # loop until input is correct
column_choice = int(input("\tPlease select the column in which you would like to place your mark" +
" (1, 2, or 3 from left to right): "))
if column_choice not in [1, 2, 3]:
print("Sorry you did not pick a valid number")
choice = [(row_choice - 1), (column_choice - 1)] # assign user input to list
if board[choice[0]][choice[1]] != " ": # checks to see if spot already has a mark in it
print("Sorry, the other player has already picked that spot. Please pick another spot.")
user_choice()
else:
# print(choice)
# print(type(choice))
return choice
我很想听听其他方法,但我想知道这里发生了什么(请用初学者的话!)
如果需要,我的代码中引发错误的实际部分是
def update_board(choice):
global board
if player_1 == True:
board[choice[0]][choice[1]] = 'X' # replace nested list index with user input according to list passed
else:
board[choice[0]][choice[1]] = 'O'
board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
def game_on():
answer = input("Ready to play (Y/N)? ").upper()
if answer == "Y":
while winner == " ":
print_board()
update_board(user_choice())
test_win()
change_player()
game_over()
elif answer == "N":
print("No problem, run program again when you are ready.")
else:
print('Not a valid input. Please restart the program.')
编辑:固定缩进/添加了board 变量/添加了驱动游戏的主函数game_on。抱歉,3 天来一直在努力学习糟糕的术语。
【问题讨论】:
-
你需要修复你的缩进;完全不清楚代码的哪些部分在
user_choice中,哪些不在。 -
“作为无类型通过”是什么意思? 每件事都有一个类型。
-
如果用户选择了一个已经被占用的位置,你递归地调用
user_choice()- 并且丢弃它的返回值,隐式返回None。 -
不要使用递归来实现开放式循环。你只是要求
RecursionError。 -
使用循环而不是递归。