def generate(self): os.system("clear") print( "Enter size of maze and type of generation(0 - dfs, 1 - Kruskal)") n, m, type = map(int, input().split()) self.cur = maze.maze(n, m, type) print("Generation was successful")
def loadmaze(self): os.system("clear") print("Enter name of file") name = input() try: in_file = open(name, 'r') first = True i = 0 for line in in_file: if line[-1] == '\n': line = line[:-1] if line[-1] == ' ': line = line[:-1] if first: n, m = map(int, line.split(" ")) first = False self.cur = maze.maze(n, m, type) continue self.cur.maze[i] = list(map(int, line.split(" "))) i += 1 print("loading was successful") in_file.close() except: print("file is not found") exit(0)
def thread(): self.running = True for m in maze(self.maze_width, self.maze_height): if not self.running: break wx.CallAfter(self.plot_data, magnify(m, magnification=self.magnification)) time.sleep(0.05)
def test_example1(): g = {1: [5, 2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1], 5: [1]} m = maze.maze(g) # assert not m.equivalent(4, 5) # assert not m.equivalent(5, 4) for a, b in it.product(g, repeat=2): assert m.equivalent(a, b) == m.equivalent(b, a), (a, b)
def getFitnesses(population): fitnesses = [] game = maze.maze() for indi in population: # For each individual, keep playing the game until it is finished and returns a score. usedGame = copy.deepcopy(game) usedGame.runGame(indi) fitnesses.append(usedGame.getScore()) return fitnesses
def getkey(snake, food, shape=(16, 16)): m = maze(shape[0], shape[1], value=-1) m.setAbsorb(food) m.refreshDead(snake) m.refreshPi() # exclude -inf bConverge = False count = 0 while not bConverge: bConverge = m.refreshValue() m.refreshPi() count += 1 if count >= MAX_ITER: break return m.getMove(snake[0]), count
class Game: pos = MyPair(1, 1) size = MyPair(30, 30) obstacles = maze.maze(size) win = False drawChar = " " def moveLeft(self): nextPos = MyPair(self.pos.x - 1, self.pos.y) if self.posType(nextPos) == 3 or self.posType(nextPos) == 4: self.pos.x -= 1 return True else: return False def moveRight(self): nextPos = MyPair(self.pos.x + 1, self.pos.y) if self.posType(nextPos) == 3 or self.posType(nextPos) == 4: self.pos.x += 1 return True else: return False def moveUp(self): nextPos = MyPair(self.pos.x, self.pos.y - 1) if self.posType(nextPos) == 3 or self.posType(nextPos) == 4: self.pos.y -= 1 return True else: return False def moveDown(self): nextPos = MyPair(self.pos.x, self.pos.y + 1) if self.posType(nextPos) == 3 or self.posType(nextPos) == 4: self.pos.y += 1 return True else: return False def posType(self, pos): if self.pos == pos: return 1 elif self.obstacles[pos.y][pos.x]: return 2 elif pos.x == (self.size.x) - 1 and pos.y == (self.size.y) - 1: return 4 else: return 3
def main(): # initial Point init = [28, 28] # Final point goal = [53, 4] # Move Cost cost = 1 # Connection Speed speed = 115200 # Barriers ratio to path width = robot_diameter / (2 * maze cell long) ratio = 1 # save.p is the maze pickle file, and generates the maze grid = cPickle.load(open('save.p', 'rb')) # Serial Port port = "/dev/ttyACM1" # Taking an object from maze class maze_obj = maze(grid, init, goal,cost,ratio) ''''''''''''''''''''''''''''''''''''''''' ' Building the final maze with Barriers ' ''''''''''''''''''''''''''''''''''''''''' grid_row_no, grid_col_no = len(grid), len(grid[0]) total_barrier = set() for row in range(grid_row_no) : for col in range(grid_col_no): cur_node = grid[row][col] if cur_node == 1 : node_barrier = maze_obj.update_b(row, col) total_barrier.update(node_barrier) maze_obj.set_grid(total_barrier) # Performing search path = maze_obj.search() # Taking an object from arduino_connection class ard_obj = arduino_connection(path, port, speed) # Sending Data to arduino ard_obj.connect()
from maze import maze from solver import solver import time m = maze('21x21.png') m.parse() # Zoek de oplossing s = solver(m) s.solve(0.02) # Animeer de oplossing s.reset() s.solve(0) solution = [] for pos in s.getPath(): solution.append(pos) m.output(solution) time.sleep(0.03)
#init pygame #from pygame.button import Button os.chdir("./resources") # 资源路径 Unique = False Gate = False if easygui.ynbox("是否开启传送门模式?"): Gate = True if easygui.ynbox("迷宫路径是否唯一?"): Unique = True easygui.msgbox(msg="按方向键移动\n按空格键进入传送门\n长按A键开启提示\n长按B键自动寻路\n终点一定在右下角\n吃到一定数量的铜锣烧才能过关",title="游玩说明",ok_button="开始游戏") pygame.init() #pygame模块的初始化 m = why.maze(10,20,Unique,Gate) while len(m.path)==0: m = why.maze(10,20,False,True) # 万一木有路,重新生成(概率很小) count = 0 win = False print(m.grid) #init clock clock = pygame.time.Clock() #创建一个对象用来跟踪时间 # screen screen:pygame.Surface = pygame.display.set_mode([1280,640]) #先搭建窗口,640*480是很久很久以前的显示器尺寸 pygame.display.set_caption("迷宫") icon = pygame.image.load("people.png") pygame.display.set_icon(icon) #加载图标
import Qagent import numpy as np import maze m = maze.maze() def test_q_algorithm_normal(): """ Testing to see if the q algorithm operates correctly """ q = Qagent.agent(m) result = q.qAlgorithm(0.54, 1, 0.67) assert result == 0.835 def test_q_algorithm_negative(): """ Testing to see if it breaks on negative """ q = Qagent.agent(m) result = q.qAlgorithm(-50000, 60, 0.9999999) assert result > 1 def test_q_algorithm_big(): """ Testing to see if it breaks on large numbers """ q = Qagent.agent(m) result = q.qAlgorithm(500000000000000000000000000000000000000000000000000, 500000000000000000000000000000000000000000000000000,
# within 1 tile in the direction def perform(self, model): choice = random.randint(0, len(self.directions) - 1) if self.directions[choice] == "North": if model.checkMonster("North", 1): return "attack" else: return "moveN" elif self.directions[choice] == "East": if model.checkMonster("East", 1): return "attack" else: return "moveE" elif self.directions[choice] == "South": if model.checkMonster("South", 1): return "attack" else: return "moveS" else: if model.checkMonster("West", 1): return "attack" else: return "moveW" if __name__ == "__main__": randomPlayer = randomPlayer() maze = maze.maze() maze.runGame(randomPlayer) print(maze.getScore())
try: cost = [int(right), int(up), int(left), int(down)] except: print("invalid cost values, reverting to uniform cost") cost = [1,1,1,1] else: cost = [1,1,1,1] return Solver, cost #Read the puzzle information from the text file. gridSize, initialState, goalState, obstacles = readProblem() #Create a problem object problem = maze.maze(gridSize, obstacles) #populate the maze array with the obstacles problem.populateMaze() Solver, cost = getInput() while (Solver == None): Solver, cost = getInput() #Create the start and end state giving them directions of start and end startState = mazestate.PuzzleState(initialState, direction=3, dirCost=cost) endState = mazestate.PuzzleState(goalState, direction=4) display = draw.guiDisplay(problem)
#!/bin/env python2 import player import maze import cardinals print("Commands: walk <number>, face <direction>, turn <left|right>") print("directions can be: north, south, east, west.") print("commands can be abbreviated as their first letter (w 3 = walk 3)") print("Size ([SIZExSIZE] or just SIZE, eg.: 2x3 or just 3 for a 3x3 maze)") maze_size = raw_input("Size of the maze: ").split("x") size_x = int(maze_size[0]) size_y = int(maze_size[-1]) m1 = maze.maze(size_x, size_y) p1 = player.player(m1.start_position, m1.start_heading) commands_count = 0 print(m1.view(p1.position, p1.heading)) print("commands: %s" % commands_count) while 1: # execute player commands: commands = raw_input("%s: " % p1.name).strip().strip(';').split(';') commands_count += len(commands) if "cheater" in commands: for i in m1.blueprint: print(" ".join(map(str, i))) print("current player position: %s" % p1.position) if "exit" in commands or "quit" in commands: if "y" in raw_input("givin' up already? (y/n): "): print("loser :)")
def __init__(self, size): self.size = size self.maze = maze(size, size, 0.75, 0.03)
def run(self, filepath, mode, save): self.maze = maze(filepath) self.window = tuple(x * self.scale for x in self.maze.size) if self.human: self.agent = agent(self.maze.start, self.maze) path = [] states_explored = 0 else: #time in seconds time_start = time.time() path = getattr(search, mode)(self.maze) states_explored = self.maze.states_explored time_total = time.time() - time_start pygame.init() self.surface = pygame.display.set_mode(self.window, pygame.HWSURFACE) self.surface.fill((255, 255, 255)) pygame.display.flip() pygame.display.set_caption('MP1 ({0})'.format(filepath)) if self.human: self.draw_player() else: print(""" Results {{ path length : {0} states explored : {1} total execution time: {2:.2f} seconds }} """.format(len(path), states_explored, time_total)) self.draw_path(path) self.draw_maze() self.draw_start() self.draw_waypoints() pygame.display.flip() if type(save) is str: pygame.image.save(self.surface, save) self.running = False clock = pygame.time.Clock() while self.running: pygame.event.pump() clock.tick(self.fps) for event in pygame.event.get(): if event.type == pygame.QUIT: raise SystemExit elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: raise SystemExit elif event.type == pygame.KEYDOWN and self.human: try: move = { pygame.K_RIGHT: (0, 1), pygame.K_LEFT: (0, -1), pygame.K_UP: (-1, 0), pygame.K_DOWN: (1, 0), }[event.key] path.extend(self.agent.move(move)) except KeyError: pass self.loop(path + [self.agent.position])
def test_symmetric(g): m = maze.maze(g) for a, b in it.product(g, repeat=2): assert m.equivalent(a, b) == m.equivalent(b, a)
self.image = player_image self.rect = self.image.get_rect().move(tile_width * pos_x, tile_height * pos_y) def check(self): if pygame.sprite.spritecollideany(self, wall_group): return True return False # основной цикл sound = pygame.mixer.Sound('data/step_1.wav') pygame.display.set_caption('Maze') taken = 0 END = 10 maze(1, 1, 2) size = WIDTH, HEIGHT screen = pygame.display.set_mode(size) clock = pygame.time.Clock() start_screen() player, level_x, level_y, amount, ball_dict = \ generate_level(load_level('map.txt')) total = amount tiles_group.draw(screen) player_group.draw(screen) balls_group.draw(screen) pygame.display.flip() level = 1 flag = False time = datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S").split()[1]
def loadMaze(self,mname): self.maz = maze.maze(maze.mfname(mname))
def test_reflexive(g): m = maze.maze(g) for a in g: assert m.equivalent(a, a)
def test_transitive(g): m = maze.maze(g) for a, b, c in it.product(g, repeat=3): if m.equivalent(a, b) and m.equivalent(b, c): assert m.equivalent(a, c)
# driver_reinforcement_maze.py import maze import matplotlib.pyplot as plt import numpy as np # Things to try: # Change random seed to get different random numbers: seed (integer) # Change width and height of maze: width, height (between 3 and 8 for each) # Change number of episodes: nepisode seed = 11 width = 5 height = 5 nepisode = 50 # (1) create model np.random.seed(seed) epsilon = 0.0 model = maze.maze(width, height, epsilon) # (2) simulate alpha = 1 model.qlearning(nepisode, alpha) # (3) plot results # number of steps for each episode model.plot_steps() # animation of strategy model.plot_strategy_animation() plt.show()
from maze import maze from mazePic import mazePic from mazeSolver import mazeSolver size=20 #create random maze a=maze(size,size) #draw the walls of the maze aPic=mazePic(a) #solve the maze solver=mazeSolver(a) solver.breadthFirstSearch((0,0),(size-1,size-1)) #color visited spots and solution #aPic.listFill(solver.visited,(0,0,255)) aPic.solution(solver.solution,(255,0,0)) aPic.savePic('test')
def engine(stdscr): '''Engine takes in a curses window and is called by curses.Wrapper() Engine intitalizes screen and contains the loop that takes the user input, sends it to an instance of the maze class and refreshes all the displays.''' curses.curs_set(0) # turn curser off stdscr.refresh() #initial screen refresh gMaze = maze('simpleMiniMaze.txt') #initialize Maze curses.halfdelay(1) #removes wait for user input on getch() #dict to convert keys to direction "vectors" [y,x] in the form of lists direction_vectors_dic = {curses.KEY_DOWN:[1,0],\ curses.KEY_UP:[-1,0],\ curses.KEY_LEFT:[0,-1],\ curses.KEY_RIGHT:[0,1],\ -1:[0,0]} #Dimensions and location of main game curses pad (window) p = {'y_loc':2,'x_loc':6,'height':16,'width':49, \ 'y_cent':min(max(gMaze.walkers[0][0].location[0],0),gMaze.height), \ 'x_cent':min(max(gMaze.walkers[0][0].location[1],0),gMaze.height)} #Frame around gameplay Pad game_frame = curses.newwin( p['y_loc'] + p['height'] + 1, p['x_loc'] + p['width'] - 1, p['y_loc'] - 1, p['x_loc'] - 2, ) game_frame.border() game_frame.refresh() #lower info frame end_game_frame = [ v[0] + v[1] for v in zip(game_frame.getmaxyx(), game_frame.getbegyx()) ] info_frame = curses.newwin(5, game_frame.getmaxyx()[1], end_game_frame[0], game_frame.getbegyx()[1]) info_frame.border() info_frame.refresh() #this loop runs the game err = 'none' start_time = time.time() while True: curses.napms(10) #to help slow things down and smooth things out inp = stdscr.getch() #will be -1 if no input is used if inp == 27: #27 is the Ascii code for esc key break #convert user input to a direction vector #if no user input (or unrecognized user input), use direcion [0,0] direction = direction_vectors_dic.get(inp, [0, 0]) try: #main call to maze object that moves all objects gMaze.update(direction) #set screen center based on hero location hero = gMaze.walkers[0][0] p['y_cent'] = min(max(gMaze.walkers[0][0].location[0], 0), gMaze.height) p['x_cent'] = min(max(gMaze.walkers[0][0].location[1], 0), gMaze.width) #set parameters for pad refresh y_top_left = int(p['y_cent'] - p['height'] / 2) y_bottom_right = int(p['y_cent'] + p['height'] / 2) x_top_left = int(p['x_cent'] - p['width'] / 2) x_bottom_right = int(p['x_cent'] + p['width'] / 2) #Main pad refresh gMaze.pad.refresh(y_top_left, x_top_left, p['y_loc'], p['x_loc'], p['y_loc'] + p['height'], p['x_loc'] + p['width']) #info frame refresh elapsed_time = divmod(int(time.time() - start_time), 60) formatted_time = '{}:{:0>2d}'.format(elapsed_time[0], elapsed_time[1]) info_frame.addstr(1, 1, 'Time: ' + formatted_time) info_frame.addstr(3, 1, 'Score: ' + '{:0>8d}'.format(gMaze.score)) info_frame.addstr(1, 20, 'Use the arrow keys to control') info_frame.addstr(2, 20, 'your Hero.') info_frame.addstr(3, 20, 'Hit \'esc\' to exit the game.') info_frame.refresh() except Exception as e: if 'GameOver' in str(e): #If the game over error is raise leave the screen on until #the user hits the escape key. err = e gMaze.pad.refresh(y_top_left, x_top_left, p['y_loc'], p['x_loc'], p['y_loc'] + p['height'], p['x_loc'] + p['width']) while True: #leave screen on until user hits escape key. inp = stdscr.getch() if inp == 27: break else: file = open('test_output.txt', 'w') file.write('testing: ' + str(e) + '\n') file.write(str(gMaze)) file.close() raise e exit() break