gpt4 book ai didi

python - 如何实现列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:33 25 4
gpt4 key购买 nike

我正在尝试创建一个井字棋游戏;但我遇到了一点麻烦。我创建了一个包含数字的列表,因此当选择该数字时,它会更改为 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)

最佳答案

我猜你想要的是一个带有字符串而不是数字的板,最初填充有单个空格的字符串。您可以为此板使用单个列表或二维数组

单个列表实现

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'

打印二维列表的示例:

>>> 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

关于python - 如何实现列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20224889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com