Guest User

eightSolver.py

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