我刚刚开始编码,我正在尝试用Python 3制作一个Tic Tac Toe程序。这是我尝试过的最大的项目,我似乎做得很好,但我遇到了一个我无法弄清楚的问题。
我的电路板编号为1到9.当我使用参数move1和user1运行此功能时,它应该将电路板上的相应位置更改为用户的字符X或O.
print("Player 1 goes first. Select your square")
move1 = input("> ")
def new_move(number_of_moves, user):
if number_of_moves == '1':
square1 = user
if number_of_moves == '2':
square2 = user
if number_of_moves == '3':
square3 = user
if number_of_moves == '4':
square4 = user
if number_of_moves == '5':
square5 = user
if number_of_moves == '6':
square6 = user
if number_of_moves == '7':
square7 = user
if number_of_moves == '8':
square8 = user
if number_of_moves == '9':
square9 = user
new_move(move1, user1)
tictactoe()
但是,当我运行该功能时,它不会将相应方块的值更改为用户的角色。它根本不会改变任何东西。我一直在墙上敲我的头试图弄清楚为什么无济于事。就像我说的那样,我对此非常陌生,所以任何帮助都会受到赞赏。谢谢!
答案 0 :(得分:0)
因为square#
中的new_move
被视为本地变量。
局部变量仅存在于new_move
函数中。它不在函数外部引用。
您可以通过将它们设为全局来更改它。
def new_move(number_of_moves, user):
global square1, square2, square3, square4, square5, square6, square7, square8, square9
if number_of_moves == '1':
square1 = user
if number_of_moves == '2':
square2 = user
if number_of_moves == '3':
square3 = user
if number_of_moves == '4':
square4 = user
if number_of_moves == '5':
square5 = user
if number_of_moves == '6':
square6 = user
if number_of_moves == '7':
square7 = user
if number_of_moves == '8':
square8 = user
if number_of_moves == '9':
square9 = user
实际上,我不推荐这个,但它会起作用。
有关详细信息,请参阅 Using global variables in a function other than the one that created them
答案 1 :(得分:-1)
Naetmul的例子是正确的,但我建议你减少你的代码。为此,我使用了一个列表。
targetSDKVersion
无论如何,我在列表中将0作为默认值,因为我不知道变量是什么print("Player 1 goes first. Select your square")
move1 = input("> ")
squares = [0,0,0,0,0,0,0,0,0] # Use a list to reduce the size of your code.
def new_move(square, user):
if square.isdigit():
try: squares[square-1] = user
except: print("Incorrect value.")
else:
print("Incorrect value.")
new_move(move1, user1)
tictactoe()
;)