Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #usr/bin/env python
- from sys import argv
- class DimensionMismatchException(BaseException):
- pass
- class Blank(object):
- def __repr__(self):
- return 'B'
- class Puzzle:
- rows = 0
- cols = 0
- array = None
- blank = None
- def __init__(self, rows, cols, *data):
- if len(data) != rows*cols - 1:
- raise DimensionMismatchException('not enough data')
- self.rows = rows
- self.cols = cols
- self.array = list(data)
- self.blank = Blank()
- self.array.append(self.blank)
- def __repr__(self):
- puzzle = ''
- for i in range(self.rows):
- if i > 0:
- puzzle = puzzle + '\n'
- puzzle = puzzle + str(self.array[i*self.rows:i*self.rows + self.cols])
- return puzzle
- def up(self):
- pos = self.array.index(self.blank)
- if pos < self.cols:
- return
- else:
- upper = pos - self.cols
- d = self.array[upper]
- self.array[pos] = d
- self.array[upper] = self.blank
- def down(self):
- pos = self.array.index(self.blank)
- if pos >= (self.rows - 1) * self.cols:
- return
- else:
- downer = pos + self.cols
- d = self.array[downer]
- self.array[pos] = d
- self.array[downer] = self.blank
- def right(self):
- pos = self.array.index(self.blank)
- if (pos + 1) % self.cols == 0:
- return
- else:
- righty = pos + 1
- d = self.array[righty]
- self.array[pos] = d
- self.array[righty] = self.blank
- def left(self):
- pos = self.array.index(self.blank)
- if pos % self.cols == 0:
- return
- else:
- lefty = pos - 1
- d = self.array[lefty]
- self.array[pos] = d
- self.array[lefty] = self.blank
- if __name__ == '__main__':
- rows = int(argv[1])
- cols = int(argv[2])
- data = [int(i) for i in argv[3:]]
- puzzle = Puzzle(rows, cols, *data)
- print('tablero en posicion 0:')
- print(puzzle)
- puzzle.up()
- print('un movimiento hacia arriba:')
- print(puzzle)
- puzzle.left()
- print('y ahora hacia la izquierda')
- print(puzzle)
Advertisement
Add Comment
Please, Sign In to add comment