在多个函数之间传递变量| Python 3
谢谢你阅读这篇文章。我想用AI和其他东西制作一个高级的Tictatcoe游戏。我需要在不同的函数之间传递spots(s1-s9)变量。我已经研究了相当一段时间了,我想得到一个答案。以下是我需要执行的部分代码:在多个函数之间传递变量| Python 3,python,python-3.x,variables,Python,Python 3.x,Variables,谢谢你阅读这篇文章。我想用AI和其他东西制作一个高级的Tictatcoe游戏。我需要在不同的函数之间传递spots(s1-s9)变量。我已经研究了相当一段时间了,我想得到一个答案。以下是我需要执行的部分代码: def set_spots(s1, s2, s3, s4, s5, s6, s7, s8, s9): return s1,s2,s3,s4,s5,s6,s7,s8,s9 def print_spots(): print('\n') print(str(s1) +
def set_spots(s1, s2, s3, s4, s5, s6, s7, s8, s9):
return s1,s2,s3,s4,s5,s6,s7,s8,s9
def print_spots():
print('\n')
print(str(s1) + ' | ' + str(s2) + ' | ' + str(s3))
print('--+---+--')
print(str(s4) + ' | ' + str(s5) + ' | ' + str(s6))
print('--+---+--')
print(str(s7) + ' | ' + str(s8) + ' | ' + str(s9))
def game_loop():
set_spots(1,2,3,4,5,6,7,8,9)
print_spots()
game_loop()
我希望能够在任何函数中设置点,就像我有一个turnX函数一样。就像我有:
def turnx(): #This isnt in this code though
#if stuff == other stuff (just example):
set_spots('X','O',3,4,5,6,7,8,9)
但结果是:
NameError: name 's1' is not defined
因此,基本上,我需要程序询问用户他们的x或o将被放置在电路板上的什么位置(你不必担心),然后存储该值以打印出来。就像我在游戏中将1改为X一样,它需要被存储以便可以打印出来。帮你自己一个忙,将这些点表示为一个列表。然后在调用set spots时将该列表存储在变量中,并将其传递到打印:
def set_spots(s1, s2, s3, s4, s5, s6, s7, s8, s9):
return [s1,s2,s3,s4,s5,s6,s7,s8,s9]
def print_spots( spots ):
s1,s2,s3,s4,s5,s6,s7,s8,s9 = spots
print('\n')
print(str(s1) + ' | ' + str(s2) + ' | ' + str(s3))
print('--+---+--')
print(str(s4) + ' | ' + str(s5) + ' | ' + str(s6))
print('--+---+--')
print(str(s7) + ' | ' + str(s8) + ' | ' + str(s9))
def game_loop():
spots = set_spots(1,2,3,4,5,6,7,8,9)
print_spots(spots )
game_loop()
我认为您应该尝试在打印点上使用设置点的变量:
def print_spots(s1, s2, s3, s4, s5, s6, s7, s8, s9):
return s1,s2,s3,s4,s5,s6,s7,s8,s9):
print('\n')
print(str(s1) + ' | ' + str(s2) + ' | ' + str(s3))
print('--+---+--')
print(str(s4) + ' | ' + str(s5) + ' | ' + str(s6))
print('--+---+--')
print(str(s7) + ' | ' + str(s8) + ' | ' + str(s9))
def game_loop():
print_spots(1,2,3,4,5,6,7,8,9)
print_spots()
game_loop()
如果这不起作用,那么我不确定您是否可以在不需要不必要的
set\u spots()
函数的情况下执行此操作。
您只需要一个阵列:
def turnx(s):
if 1 == 1: # (a condition):
s = ['X','O',3,4,5,6,7,8,9]
return s
def print_spots(s):
print('\n')
print(str(s[0]) + ' | ' + str(s[1]) + ' | ' + str(s[2]))
print('--+---+--')
print(str(s[3]) + ' | ' + str(s[4]) + ' | ' + str(s[5]))
print('--+---+--')
print(str(s[6]) + ' | ' + str(s[7]) + ' | ' + str(s[8]))
def game_loop():
spots = [1,2,3,4,5,6,7,8,9] # Use an array
print_spots(spots)
spots = turnx(spots)
print_spots(spots)
game_loop()
这将产生:
1 | 2 | 3
--+---+--
4 | 5 | 6
--+---+--
7 | 8 | 9
X | O | 3
--+---+--
4 | 5 | 6
--+---+--
7 | 8 | 9
谢谢你的回答,我稍后再看。我现在得走了。那没有意义,因为你不能在返回语句后键入代码