114 lines
2.6 KiB
Text
114 lines
2.6 KiB
Text
isMiniMicro = version.hostName == "Mini Micro"
|
|
|
|
// These coordinates are [row,col] not [x,y]
|
|
Directions = {"up": [-1,0], "right": [0,1], "down": [1, 0], "left": [0,-1]}
|
|
TileNum = range(1, 15)
|
|
Puzzle15 = {"grid":[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],
|
|
"blankPos": [3,3]}
|
|
|
|
Puzzle15.__setTile = function(position, value)
|
|
row = position[0]; col = position[1]
|
|
self.grid[row][col] = value
|
|
end function
|
|
|
|
Puzzle15.__getTile = function(position)
|
|
row = position[0]; col = position[1]
|
|
return self.grid[row][col]
|
|
end function
|
|
|
|
Puzzle15.__getOppositeDirection = function(direction)
|
|
directions = Directions.indexes
|
|
oppix = (directions.indexOf(direction) + 2) % 4
|
|
return directions[oppix]
|
|
end function
|
|
|
|
Puzzle15.getState = function
|
|
return self.grid
|
|
end function
|
|
|
|
Puzzle15.getBlankPos = function
|
|
return self.blankPos
|
|
end function
|
|
|
|
Puzzle15.hasWon = function
|
|
count = 1
|
|
for r in range(0, 3)
|
|
for c in range(0, 3)
|
|
if self.grid[r][c] != count then return false
|
|
count += 1
|
|
end for
|
|
end for
|
|
return true
|
|
end function
|
|
|
|
Puzzle15.move = function(direction)
|
|
if not Directions.hasIndex(direction) then return false
|
|
move = Directions[direction]
|
|
curPos = self.blankPos[:]
|
|
newPos = [curPos[0] + move[0], curPos[1] + move[1]]
|
|
if (-1 < newPos[0] < 4) and (-1 < newPos[1] < 4) then
|
|
value = self.__getTile(newPos)
|
|
self.__setTile(curPos, value)
|
|
self.__setTile(newPos, 16) // 16 is the blank tile
|
|
self.blankPos = newPos
|
|
return true
|
|
else
|
|
return false
|
|
end if
|
|
end function
|
|
|
|
Puzzle15.shuffle = function(n)
|
|
lastMove = ""
|
|
directions = Directions.indexes
|
|
for i in range(1, 50)
|
|
while true
|
|
moveTo = directions[floor(rnd * 4)]
|
|
oppMove = self.__getOppositeDirection(moveTo)
|
|
|
|
if self.__getOppositeDirection(moveTo) != lastMove and self.move(moveTo) then
|
|
lastMove = moveTo
|
|
if isMiniMicro then
|
|
self.displayBoard
|
|
wait 1/33
|
|
end if
|
|
break
|
|
end if
|
|
end while
|
|
end for
|
|
end function
|
|
|
|
Puzzle15.displayBoard = function
|
|
if isMiniMicro then clear
|
|
for r in range(0, 3)
|
|
for c in range(0, 3)
|
|
grid = self.getState
|
|
if grid[r][c] == 16 then
|
|
s = " "
|
|
else
|
|
s = (" " + grid[r][c])[-3:]
|
|
end if
|
|
print s, ""
|
|
end for
|
|
print
|
|
end for
|
|
end function
|
|
|
|
Puzzle15.shuffle
|
|
|
|
while not Puzzle15.hasWon
|
|
if isMiniMicro then
|
|
clear
|
|
else
|
|
print
|
|
end if
|
|
|
|
Puzzle15.displayBoard
|
|
while true
|
|
print
|
|
move = input("Enter the direction to move the blank in (up, down, left, right): ")
|
|
move = move.lower
|
|
if Directions.hasIndex(move) and Puzzle15.move(move) then break
|
|
print "Please enter a valid move."
|
|
end while
|
|
end while
|
|
print "Congratulations! You solved the puzzle!"
|