Guest User

eightSolver.py

a guest
Jun 23rd, 2024
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. from copy import deepcopy
  2.  
  3. class Game:
  4.     def __init__(self,arr):
  5.         self.arr=arr
  6.         self.history=[]
  7.     def isGameOver(self):
  8.         i=0
  9.         for line in self.arr:
  10.             for number in line:
  11.                 i+=1
  12.                 if number!=i:
  13.                     return False
  14.         return True
  15.     def getXY(self,i):
  16.         for y,line in enumerate(self.arr):
  17.             for x,c in enumerate(line):
  18.                 if c==i:
  19.                     return (x,y)
  20.         return None
  21.     def getAllPossibilities(self):
  22.         ret=[]
  23.         x,y=self.getXY(9)
  24.         allTuples=((x+1,y),(x-1,y),(x,y+1),(x,y-1))
  25.         for t in allTuples:
  26.             if (3 > t[0] > -1) and (3 > t[1] > -1):
  27.                 ret.append(self.arr[t[1]][t[0]])
  28.         return ret
  29.     def play(self,i):
  30.         x,y=self.getXY(9)
  31.         allTuples=((x+1,y),(x-1,y),(x,y+1),(x,y-1))
  32.         for t in allTuples:
  33.             if (t[0]<0) or (t[0]>2) or (t[1]<0) or (t[1]>2):
  34.                 continue
  35.             if self.arr[t[1]][t[0]]==i:
  36.                 self.arr[t[1]][t[0]]=9
  37.                 self.arr[y][x]=i
  38.                 self.history.append(i)
  39.                 return
  40.  
  41. def solve (game, steps):
  42.     #print("solve("+str(id(game))+','+str(steps)+')')
  43.     if game.isGameOver():
  44.         return game
  45.     if steps==0:
  46.         return None
  47.     for p in game.getAllPossibilities():
  48.         g2=deepcopy(game)
  49.         g2.play(p)
  50.         g2=solve(g2,steps-1)
  51.         if g2:
  52.             return g2
  53.     return None
  54.        
  55. def main():
  56.     arr=[]
  57.     for _ in range(3):
  58.         s=input()
  59.         l=[]
  60.         arr.append(l)
  61.         for c in s:
  62.             if c==" ":
  63.                 l.append(9)
  64.             else:
  65.                 l.append(int(c))
  66.     game=Game(arr)
  67.     game=solve(game,81)
  68.     if game:
  69.         print(game.history)
  70.     else:
  71.         print("Impossible")
  72.  
  73. main()
  74.  
Advertisement
Add Comment
Please, Sign In to add comment