我试图创造一个井字游戏;但我有一点点麻烦。 我创建了一个包含数字的列表,因此当选择该数字时,它会更改为x或o。然而,当我的电路板打印时,它的数字为0,1,2,3,4,5,6,7,8,我不希望它们是这样的。 我的问题是如何更改空列表中的字符?我会使用索引还是有另一种方法
board = [0,1,2,
3,4,5,
6,7,8]
def gameBoard():
print(" " "a" " " "b" " " "c")
print(" ""-------------")
print(("1"),("|"),board[0],"|",board[1], "|" ,board[2], "|")
print(" ""-------------")
print(("2"),("|"),board[3],"|",board[4], "|" ,board[5], "|")
print(" ""-------------")
print(("3"),("|"),board[6],"|",board[7], "|" ,board[8], "|")
print(" ""-------------")
while True:
user_input = input("Enter your move: ")
if user_input == "a1":
user_input = "0"
elif user_input == "a2":
user_input = "3"
elif user_input == "a3":
user_input="6"
elif user_input == "b1":
user_input = "1"
elif user_input == "b2":
user_input = "4"
elif user_input== "b3":
user_input = "7"
elif user_input == "c1":
user_input = "2"
elif user_input == "c2":
user_input = "5"
elif user_input == "c3":
user_input = "8"
else:
print("invalid coordinates")
user_input= int(user_input)
答案 0 :(得分:1)
我猜你想要的是一个带字符串的电路板,而不是数字,最初用单个空格的字符串填充。您可以为此电路板或二维数组使用单个列表
单一列表实施
board = [" "," "," "," "," "," "," "," "," "]
来自控制台的示例:
>>> board = [" "," "," "," "," "," "," "," "," "]
>>> board[2] = "X"
>>> board
[' ', ' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
>>> board[0]
' '
>>> board[2]
'X'
>>>
二维数组实现
board = [[" "," "," "],[" "," "," "],[" "," "," "]]
来自控制台的示例:
>>> board = [[" "," "," "],[" "," "," "],[" "," "," "]]
>>> board[1][2] = "O"
>>> board
[[' ', ' ', ' '], [' ', ' ', 'O'], [' ', ' ', ' ']]
>>> board[0][1]
' '
>>> board[1][2]
'O'
打印2D列表的示例:
>>> board = [["X"," ","X"],[" ","X"," "],["X"," ","X"]]
>>> for row in board:
string = ""
for element in row:
string = string + element
print(string)
X X
X
X X
答案 1 :(得分:0)
使用二维列表!
board = [[0,0,0],
[0,0,0],
[0,0,0]]
然后只使用您想要的值等。然后参考只是:
board[row][column]
编辑:我有点误读了这个问题,而不是0到9,你可以把它们都变成空字符串,即。
board[i] = ''
或使用字典将数字映射到字符串
board[5] = ''
答案 2 :(得分:0)
您可以使用字典:
board = {0:'X', 1:'O', 2:' ',
3:'X', 4:'O', 5:' ',
6:'X', 7:'O', 8:' ',
}
print board[1] # will print O
board[1] = 'X'
print board[1] # will print X
答案 3 :(得分:0)
您的问题并不完全是因为您没有在每次迭代时更新游戏板。但是,这里有一些建议:
user_input = '1'
等所有语句都可以设置为use_input = 1
,以避免显式调用int
。board[user_input] = 'X'
或board[user_input] = 'O'
来更改列表的值,具体取决于播放器。答案 4 :(得分:0)
从您的代码中,您填写的板有0 - 8。如果您检查板[7]它将返回7。
我认为你想用空格初始化电路板,因此电路板[7]将返回''(空格)。
你可以做板= ['','','','','','','','','']
或者更干净,
board = [''] * 9
希望这会有所帮助:) 使用矩阵对于实现来说也不是一个坏主意,但与您尝试解决的问题不同