### stage 2 - puzzle completness

parent b809444a
 from microbit import * size = 3 grid = [[4, 1, 3], [7, 2, 6], [0, 5, 8]] solvedGrid = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] def copy(grid): return [[y for y in x] for x in grid] def isSolved(grid): return grid == solvedGrid def showGrid(grid): for x in range(1, size + 1): for y in range(1, size + 1): display.set_pixel(y, x, grid[x-1][y-1]) def lightUp(): display.set_pixel(0, 0, 9) display.set_pixel(0, 4, 9) display.set_pixel(4, 0, 9) display.set_pixel(4, 4, 9) def getMoves(grid): # find the zero for x in range(size): for y in range(size): if grid[x][y] == 0: zerox = x zeroy = y # where can we move? xswaps = [((zerox, zeroy), (x, zeroy)) for x in [zerox - 1, zerox + 1] if x >= 0 and x < size] yswaps = [((zerox, zeroy), (zerox, y)) for y in [zeroy - 1, zeroy + 1] if y >= 0 and y < size] return xswaps + yswaps def swap(grid, move): pos0, pos1 = move x0, y0 = pos0 x1, y1 = pos1 tmp = grid[x0][y0] grid[x0][y0] = grid[x1][y1] grid[x1][y1] = tmp def search(): while not isSolved(grid): showGrid(grid) sleep(500) moves = getMoves(grid) swap(grid, moves) showGrid(grid) search() lightUp()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!