我使用python制作了一个that游戏,所以我在choose_position()函数中遇到了问题,它可以根据玩家选择的数字(1比9)设置行和插槽,但是行和槽总是0,所以它总是第一个列表中的第一个组件,不会改变,我也不知道为什么。
下面是用户选择5(所以行应该等于1,槽等于2)但仍然行和槽都是0的例子:

from tabnanny import check
board = [["-","-","-"],["-","-","-"],["-","-","-"]]
def print_board(board):
for row in board:
for slot in row:
print(f"{slot}",end=" ")
print()
def current_user(user):
if user: return "x"
else:return "o"
def choose_position(choice,row,slot):
print("this is choice:",choice,type(choice))#just checking the choice value and type
if choice in [1,2,3]:
row = 0
slot = choice-1
elif choice in [4,5,6]:
row = 1
slot = choice-4
elif choice in [7,8,9]:
row = 2
slot = choice -7
def limit(choice):
if int(choice)>9 or int(choice)<1:
print("please enter a number between 1 and 9 if you would be so good")
return True
else: return False
def isnum(choice):
if not choice.isnumeric():
print("Please enter a valid number if you would be so good")
return True
else: return False
def check_input(choice):
if isnum(choice): return True
if limit(choice): return True
return False
def quit(choice):
if choice == "q": return True
else: return False
user = True #x means true,false means o
turns = 0
row = 0
slot = 0
while turns < 9:
print(turns)
print_board(board)
active_user = current_user(user)
choice = input("enter a position between 1 and 9:\n")
if quit(choice):break
if check_input(choice):
print("oups wrong")
continue
choose_position(int(choice),row,slot)
print(row,slot)#just checking row and slot values
board[row][slot] = active_user
turns+=1
user = not user发布于 2022-06-16 14:04:11
您的问题是,您通过值传递变量。这意味着如果调用choose_position(int(choice),row,slot),python将生成row和slot值的本地副本(仅在choose_position()中有效)。在函数期间,只有这些局部变量在返回时被更改和丢弃。具有相同名称的“外部”变量将永远不会更改。
您应该研究“”和关键字"ref“。或者,您可以将这些值返回为list (甚至更好的是元组),并将它们分配给传入的值。如下所示:
(row, slot) = choose_position(int(choice))在你的功能中,你会写:
return (row, slot)https://stackoverflow.com/questions/72647072
复制相似问题