【发布时间】:2021-06-27 22:57:20
【问题描述】:
我对 Python 很陌生(上个月开始学习 Udemy 课程,然后编写了我的第一行 Python 代码),所以我希望有人可以就某个方面提供仁慈的建议我正在开发的交互式井字游戏项目。注意:这是一个两人游戏,其中两个玩家将使用同一台计算机。
问题:
我正在尝试编写一个函数,该函数将接收 1-9 范围内的用户输入(“位置”),将该输入作为整数存储在一个名为“板”的空列表中,然后将位置替换为称为“标记”的变量(“X”或“O”)。
我的代码:
# POSITION IS SUPPOSED TO BE AN INT THAT IS STORED IN A LIST CALLED "BOARD"
board = [''] * 9
marker = ''
position = ''
def place_marker(board, marker, position):
# while our position is an acceptable value
while position not in range(1,9+1):
position = int(input("Choose a number from 1 through 9: " ))
board.append(position)
print(board)
# NOW HOW DO I MAKE SURE THAT THE POSITION CORRESPONDS WITH EACH MARKER?
解决方案尝试失败:
我有点忘记了我失败的解决方案尝试,但这里是其中之一:
board = [''] * 9
marker = ''
position = ''
def place_marker(board, marker, position):
# while our position is an acceptable value
while position not in range(1,9+1):
position = int(input("Choose a number from 1 through 9: " ))
board.append(position)
# at the board's position, place marker 'X' or 'O'
board[position] = marker
print(board)
这导致:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-197-76194c5efcbd> in <module>
----> 1 board[position]
TypeError: list indices must be integers or slices, not str
也许我一次尝试做太多事情。我尝试参考文档以及 W3Schools 和 Real Python 等其他资源,但我似乎无法为我的生活找出解决方案。如果有人能指出我的不足或出错的地方,或者在正确的方向上给我一两条线索,我将非常感激。
【问题讨论】:
-
board.append(position)不应在while循环内。 -
您不应该在
board上附加任何内容。 -
board不是一个空列表,您填写的是:board = [''] * 9 -
position不应该是函数参数,如果你在函数中分配它。 -
列表索引从 0 开始,而不是 1。
标签: python list append tic-tac-toe