Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os,re,telnetlib
- from collections import namedtuple
- Dir = namedtuple("Dir", ["char", "dy", "dx"])
- tn = telnetlib.Telnet()
- class Maze:
- START = "S"
- END = "E"
- WALL = "#"
- PATH = " "
- OPEN = {PATH, END} # map locations you can move to (not WALL or already explored)
- RIGHT = Dir("D", 0, 1)
- DOWN = Dir("X", 1, 0)
- LEFT = Dir("A", 0, -1)
- UP = Dir("W", -1, 0)
- DIRS = [RIGHT, DOWN, LEFT, UP]
- movelist = "";
- @classmethod
- def load_maze(cls, fname):
- with open(fname) as inf:
- lines = (line.rstrip("\r\n") for line in inf)
- maze = [list(line) for line in lines]
- return cls(maze)
- def __init__(self, maze):
- self.maze = maze
- def __str__(self):
- return "\n".join(''.join(line) for line in self.maze)
- def find_start(self):
- for y,line in enumerate(self.maze):
- try:
- x = line.index("S")
- return y, x
- except ValueError:
- pass
- # not found!
- raise ValueError("Start location not found")
- def solve(self, y, x):
- if self.maze[y][x] == Maze.END:
- # base case - endpoint has been found
- return True
- else:
- # search recursively in each direction from here
- for dir in Maze.DIRS:
- ny, nx = y + dir.dy, x + dir.dx
- if self.maze[ny][nx] in Maze.OPEN: # can I go this way?
- if self.maze[y][x] != Maze.START: # don't overwrite Maze.START
- self.maze[y][x] = dir.char # mark direction chosen
- if self.solve(ny, nx): # recurse...
- self.movelist += dir.char
- return True # solution found!
- # no solution found from this location
- if self.maze[y][x] != Maze.START: # don't overwrite Maze.START
- self.maze[y][x] = Maze.PATH # clear failed search from map
- return False
- def main():
- host = "bufferoverflow.disappointedmama.com"
- port = 9000
- tn.open(host, port)
- os.remove("test.txt")
- os.remove("checkback.txt");
- while True:
- line = tn.read_until("\n", 5)
- if ( "[]" ) not in line:
- break
- origLine = line;
- line = line.replace( " ", " " ).replace( "[]", "#" ).replace( "<>", "S" ).replace( "######################################### #", "#########################################E#" )
- with open("test.txt", "a") as myfile:
- myfile.write(line)
- with open("checkback.txt", "a") as myfile:
- myfile.write(origLine)
- maze = Maze.load_maze("test.txt")
- print("Maze loaded:")
- print(maze)
- try:
- sy, sx = maze.find_start()
- print("solving...")
- if maze.solve(sy, sx):
- print(maze)
- print(maze.movelist.replace("X", "S")[::-1])
- else:
- print("no solution found")
- except ValueError:
- print("No start point found.")
- if __name__=="__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement