The Issue
I have a function legalMove(array, int)
that is meant to take in a 15 problem's current state in the form of an array and then make a move based on a numerical command. For some reason, this function is mutating the array that I put into the array spot. Why is this and how can I fix the issue? I thought that variables within functions would remain local to that function, and would only be able to change the program level variable if I put in a line like currentState = legalMove(currentState, command)
Code
Suggested array input: currentState = [8,13,1,4,2,14,0,5,3,12,10,7,11,6,9,15]
def legalMove(currentBoard, cmd):
#First, do the move
#0 = UP
#1 = RIGHT
#2 = LEFT
#3 = DOWN
blankPOS = currentBoard.index(0)
if cmd == 0: #go up
try:
exchangePOS = blankPOS - 4
numberE = currentBoard[exchangePOS]
# do the switch
currentBoard[exchangePOS] = 0
currentBoard[blankPOS] = numberE
except:
return False
if cmd == 1: #go right
try:
exchangePOS = blankPOS + 1
numberE = currentBoard[exchangePOS]
# do the switch
currentBoard[exchangePOS] = 0
currentBoard[blankPOS] = numberE
except:
return False
if cmd == 2: #go left
try:
exchangePOS = blankPOS - 1
numberE = currentBoard[exchangePOS]
print "blanksPOS",blankPOS
print "exchangePOS",exchangePOS
print "currentBoard[blankPOS]",currentBoard[blankPOS]
print "currentBoard[exchangePOS]",currentBoard[exchangePOS]
# do the switch
currentBoard[exchangePOS] = 0
currentBoard[blankPOS] = numberE
except:
return False
if cmd == 3: #go down
try:
exchangePOS = blankPOS + 4
numberE = currentBoard[exchangePOS]
# do the switch
currentBoard[exchangePOS] = 0
currentBoard[blankPOS] = numberE
except:
return False
return currentBoard