Exemple #1
0
 def setUp(self):
     """
     The setUp function is called each time one of your tests is run.
     We create an instance of the maze here before each test.
     """
     self.m=Maze()
     self.m.reset()
Exemple #2
0
    def initialize(self):
        # Setup Background, game objects, and initial states
        win = GraphWin('App-Controlled Car', 800, 600)

        self.maze = Maze(win)
        self.maze.draw()

        self.car = Car(win)
        self.car.draw()

        self.isRunning = True

        # Setup Queues, Listeners, and off threads
        self.inputQueue = Queue(maxsize=0)

        #keyboardListener = KeyboardListener(self.inputQueue)
        #keyboardListener.start()

        joystickListener = JoystickListener("Web Joystick Listener",
                                            self.inputQueue)
        joystickListener.start()

        # Setup Game Loop
        self.run()

        # Pause and Close
        win.getMouse()
        win.close()
	def Initialize(self):
		self.mTutorialText = pygame.image.load(os.path.join("Data", "tutorialText4.bmp")).convert()
		self.mTutorialRect = self.mTutorialText.get_rect()

		# Build maze
		self.mMaze = Maze(self.mKernel)
		self.mMaze.SetOffset(self.mOffset)
		self.mMaze.Load(os.path.join("Data", "tutorial2.maze"))
		self.mMaze.BuildWalls()

		# Make Monster --- ahhh
		self.mMonster = Monster(self.mKernel)
		self.mMonster.SetOffset(self.mOffset)
		self.mMonster.SetPath(self.mMaze.Solve((0, 0)))
		self.mMonster.SetCage(self.mMaze.GetCage())

		self.mBackImage = pygame.image.load(os.path.join("Data", "back.bmp")).convert()
		self.mBackHover = pygame.image.load(os.path.join("Data", "back_hover.bmp")).convert()
		self.mBackButton = self.mBackImage
		self.mBackRect = self.mBackButton.get_rect()
		self.mBackRect.topleft = (20, 530)

		self.mNextImage = pygame.image.load(os.path.join("Data", "next.bmp")).convert()
		self.mNextHover = pygame.image.load(os.path.join("Data", "next_hover.bmp")).convert()
		self.mNextButton = self.mNextImage
		self.mNextRect = self.mNextButton.get_rect()
		self.mNextRect.topleft = (630, 530)

		return RoboPy.GameState.Initialize(self)
Exemple #4
0
 def mazerunner(self, alg_list = ["dfs", "bfs", "a*EU", "a*MH", "bdbfs"]):
     self.maze = Maze(self.occ_rate, self.dim)
     for i in alg_list:
         solution_param = self.get_solution_param(i)
         if solution_param.has_path:
             printGraph(self.maze, solution_param.path, i, (solution_param.max_fringe_size, solution_param.nodes_expanded))
         else:
             printGraph(self.maze, solution_param.has_path)
Exemple #5
0
class testMaze(unittest.TestCase):
    """
    This class inherits from a class called TestCase which is
    defined in the unittest module.

    When you inherit from a class, you get all the methods that are
    defined in that class for free.

    Since this is a TestCase class, calling unittest.main() will automatically
    run any of the functions that start with the word 'test'
    """
    
    def setUp(self):
        """
        The setUp function is called each time one of your tests is run.
        We create an instance of the maze here before each test.
        """
        self.m=Maze()
        self.m.reset()

    def testMazeExists(self):
        """
        this will check to see if we have a maze class but as soon
        as setUp is run, we will see a failure so we really don't need
        to do anything here
        """
        pass
    
    def testScreenExists(self):
        assert type(self.m.s) == turtle._Screen

    def testTurtleExists(self):
        assert type(self.m.t) == turtle.Turtle

    def testScreenBackgroundIsBlue(self):
        assert self.m.s.bgcolor()=='blue'

    def testForMatrix(self):
        assert len(self.m.matrix)==20

    def testTurtleIsWhite(self):
        assert self.m.t.color()[0]=='white' and self.m.t.color()[1]=='white'

    def testTurtleIsInUpperLeftHandCorner(self):
        assert self.m.t.pos()==(-190,190), "Turtle position is %d,%d" % \
               (self.m.t.pos()[0],self.m.t.pos()[1])

    def testTurtleMatrixIs0InUpperLeftHandCorner(self):
        assert self.m.matrix[0][0]==0

    def testScreenSize(self):
        assert self.m.s.screensize()==(400,400)

    def testMatrixValueAt(self):
        assert self.m.getMatrixValueAt(-190,190)==0
        
    def testForReset(self):
        assert self.m.reset()==True
Exemple #6
0
 def cal_runningtime_single(self, alg):
     while True:
         self.maze = Maze(self.occ_rate, self.dim)
         start = time.time()
         solution_param =  self.get_solution_param(alg)
         if solution_param.has_path:
             end = time.time()
             print(end - start)
             break
    def Initialize(self):
        # Build maze
        self.mMaze = Maze(self.mKernel)
        self.mMaze.SetOffset((10, 10))
        self.mMaze.Generate(self.mMazeSize)
        #maze.Load(os.path.join("Data", "tutorial1.maze"))
        self.mMaze.BuildWalls()

        # Make Monster --- ahhh
        self.mMonster = Monster(self.mKernel)
        self.mMonster.SetOffset((10, 10))
        self.mMonster.SetPath(self.mMaze.Solve((0, 0)))
        self.mMonster.SetCage(self.mMaze.GetCage())

        self.mScoreImage = pygame.image.load(
            os.path.join("Data", "scoreText.bmp")).convert()
        self.mScoreImage.set_colorkey((0, 144, 247))
        self.mScoreRect = self.mScoreImage.get_rect()
        self.mScoreRect.topleft = (150, 570)

        self.mLosses = 0

        self.mMovesImage = pygame.image.load(
            os.path.join("Data", "movesText.bmp")).convert()
        self.mMovesImage.set_colorkey((0, 144, 247))
        self.mMovesRect = self.mMovesImage.get_rect()
        self.mMovesRect.topleft = (350, 570)

        self.mLevelImage = pygame.image.load(
            os.path.join("Data", "levelText.bmp")).convert()
        self.mLevelImage.set_colorkey((0, 144, 247))
        self.mLevelRect = self.mLevelImage.get_rect()
        self.mLevelRect.topleft = (550, 570)

        self.mLevelCompleteImage = pygame.image.load(
            os.path.join("Data", "levelComplete.bmp")).convert()
        self.mLevelCompleteRect = self.mLevelCompleteImage.get_rect()
        self.mLevelCompleteRect.topleft = (220, 150)

        self.mGameOverImage = pygame.image.load(
            os.path.join("Data", "gameOver.bmp")).convert()
        self.mGameOverRect = self.mLevelCompleteImage.get_rect()
        self.mGameOverRect.topleft = (220, 150)

        self.mMutedImage = pygame.image.load(os.path.join(
            "Data", "mute.bmp")).convert()
        self.mUnmutedImage = pygame.image.load(
            os.path.join("Data", "unmute.bmp")).convert()
        self.mVolumeImage = self.mUnmutedImage
        self.mVolumeRect = self.mVolumeImage.get_rect()
        self.mVolumeRect.topleft = (10, 570)
        self.mVolumeState = 1

        self.mFont = pygame.font.SysFont('Arial', 18, True)

        return RoboPy.GameState.Initialize(self)
Exemple #8
0
class main():
    def __init__(self):
        self.initialize()

    def initialize(self):
        # Setup Background, game objects, and initial states
        win = GraphWin('App-Controlled Car', 800, 600)

        self.maze = Maze(win)
        self.maze.draw()

        self.car = Car(win)
        self.car.draw()

        self.isRunning = True

        # Setup Queues, Listeners, and off threads
        self.inputQueue = Queue(maxsize=0)

        #keyboardListener = KeyboardListener(self.inputQueue)
        #keyboardListener.start()

        joystickListener = JoystickListener("Web Joystick Listener",
                                            self.inputQueue)
        joystickListener.start()

        # Setup Game Loop
        self.run()

        # Pause and Close
        win.getMouse()
        win.close()

    def run(self):
        # Game Loop
        while self.isRunning:
            # Process Events - Process inputs and other things
            self.processEvents()

            # Update - Update all objects that needs updating, ex position changes, physics
            #self.car.update(joystickInput)

            # Draw - Render things on screen
            self.car.move(self.inputQueue.get()['x'] * carSpeed,
                          self.inputQueue.get()['y'] * carSpeed)

            # Pause thread for framerate
            time.sleep(0.017)

    def processEvents(self):
        # Check if game is complete or not
        if self.car.carBody.getCenter().getX(
        ) > 580 and self.car.carBody.getCenter().getY() > 380:
            self.isRunning = False
Exemple #9
0
 def __init__(self, maze,name="aMaze"):
     self._running = True
     self._display_surf = None
     self._surfs = {}
     self._name = name
     
     self.maze = Maze(maze)
     self.windowHeight = len(maze) * 40
     self.windowWidth = len(maze[0]) * 40
     
     self.on_execute()
Exemple #10
0
 def initialize(self):
     c.totalScore = 0
     self.startGame = StartGame(self.width, self.height)
     self.run1 = WalkingGobang(self.width, self.height, 15)
     self.run2 = WalkingMaze(self.width, self.height, 15)
     self.run3 = WalkingShoot(self.width, self.height, 20)
     self.gobang = GobangGame(self.width, self.height)
     self.maze = Maze(self.width, self.height, 25, 25, 20, 20, 15)
     self.shoot = Shooting(self.width, self.height, 20)
     self.endGame = EndGame(self.width, self.height, 2, 50)
     self.done = False
     self.gameover = False
Exemple #11
0
def generate_reachable_plot(iterations: int,
                            maze_size: int,
                            start: tuple = (),
                            goal: tuple = (),
                            p_start: float = 0,
                            p_stop: float = 1.0,
                            p_step: float = .05):
    """
    Generates a plot showing the probability that for a given p, there exists a path through the room.
    Each probability is calculated by using the basic definition of probability:
                      number of success
                    ---------------------
                      number of samples
    Plots and saves this graph as reachable.png

    iterations - the amomunt of iterations to perform at each p. The essential 'total sample size' for a given p.
    maze_size - the size of the mazes generated to test.
    start - the start square represented as an ordered pair. Default is (0, 0).
    goal - the goal square represented as an ordered pair. Default is (n - 1, n - 1) where n = maze_size.
    p_start - the smallest p value to test (inclusive). Default is 0.
    p_stop - the largest p value to test (inclusive). Default is 1.
    p_step - the 'step' between each p-value. Default is .05.
    """
    if (not start):  # If start is not provided
        start = (0, 0)
    if (not goal):  # If goal is not provided
        goal = (maze_size - 1, maze_size - 1)

    p_values = numpy.arange(p_start, p_stop + p_step,
                            p_step)  # Generate p values
    prob_success = []  # Create a list to store the success outcomes
    for p in p_values:  # Loop through p values
        number_successes = 0  # Keep track of how many succeed
        for i in range(iterations):  # Loop through iterations
            success = Maze.reachable(Maze.gen_maze(maze_size, p), start,
                                     goal)  # Either True or False here
            if (success):  # Increase total successes if it was successful
                number_successes += 1
        prob_success.append(number_successes /
                            iterations)  # Add this value to our list

    # Now that we have data, we plot and save the figure
    # Scatter plot
    plt.figure(figsize=figure_size)
    plt.scatter(p_values, prob_success, label="Reachable", color="indigo")
    plt.xlabel("p-values")
    plt.ylabel("Simulated Success Probability")
    plt.locator_params(nbins=20)
    plt.title("Probability of a Path as Obstacles Increase")
    plt.legend(loc="best")
    plt.grid()
    plt.savefig(f"{figure_save_path}reachable_scatter.png")
    plt.show()
Exemple #12
0
def main():
    '''Replay loop of the game, it will restart the game until n is pressed
    on the end screen'''
    while 1:
        '''Initialising the four main objects of the program'''
        map = m.Maze("data/maps/map-01.txt")
        hero = m.Hero(map.get_position_of(HERO_CHAR))
        view = v.ViewPyGame()
        controller = ControllerMacGyver(map, hero, view)
        '''launching the game loop'''
        controller.get_event()
        '''Before restarting, we del every objects'''
        del map,hero,view,controller
Exemple #13
0
 def cal_solvability(self):
     p = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]
     solvability = []
     for i in range(0, len(p)):
         self.occ_rate = p[i]
         has_path_times = 0
         for j in range(0, 500):
             self.maze = Maze(self.occ_rate, self.dim)
             solution_param =  self.get_solution_param("dfs")
             if solution_param.has_path:
                 has_path_times += 1
         solvability.append(has_path_times / 500)
     printSolvability(p , solvability)
Exemple #14
0
 def Maze_merge(self, m1, m2, d, strategy):
     """
     take in two maze and merge them into one solvable maze
     strategy: strategy we use to merge two maze,
         if set to 1, simply cut them into half and merge
         if set to 0, split each into 4 parts and merge them
     """
     m1_n = deepcopy(m1)
     m2_n = deepcopy(m2)
     if strategy == 1:
         m3 = Maze(1, d)
         m3.env = m1_n.env[0:int(d / 2)] + m2_n.env[int(d / 2):d]
     else:
         m3 = m1_n
         for i in range(0, d):
             for j in range(0, d):
                 if i < d / 2:
                     if j < d / 2:
                         m3.env[i][j] = m1_n.env[i][j]
                     else:
                         m3.env[i][j] = m2_n.env[i][j]
                 else:
                     if j < d / 2:
                         m3.env[i][j] = m2_n.env[i][j]
                     else:
                         m3.env[i][j] = m1_n.env[i][j]
     if random.uniform(0, 1) < self.mutant_rate:
         x = random.randint(1, self.cur_maze.dim - 2)
         y = random.randint(1, self.cur_maze.dim - 2)
         m3.env[x][y] = 1 - m3.env[x][y]
     return m3
Exemple #15
0
 def cal_aver_path_length(self):
     p = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]
     aver_path_len = []
     for i in range(0, len(p)):
         self.occ_rate = p[i]
         path_length = 0
         has_path_times = 0
         for j in range(0, 1000):
             self.maze = Maze(self.occ_rate, self.dim)
             solution_param = self.get_solution_param("a*MH")
             if solution_param.has_path:
                 path_length += len(solution_param.path)
                 has_path_times += 1
         aver_path_len.append(path_length / has_path_times)
     printAverPathLen(p, aver_path_len)
Exemple #16
0
class Test_Maze(unittest.TestCase):

    maze = Maze.Maze(binSize=1)

    def test_geometry(self):
        self.maze.sigma = .1
        self.maze.visualize_maze()

    def test_discretization(self):
        assert (np.mod(self.maze.Nstates,
                       10) == 0), "Number of states must be a multiple of 10"

    def test_get_state_from_position(self):
        original_y = self.maze.y_position
        original_x = self.maze.x_position

        for y, x in zip([0, 30, 59.9], [59.9, 30, 0]):
            self.maze.y_position = y
            self.maze.x_position = x

        self.maze.y_position = original_y
        self.maze.x_position = original_x

    def test_training(self):
        print("Testing Learning...")
        self.maze.run(N_trials=3000, N_runs=1, verbose=False)
        plt.figure()
        plt.plot((self.maze.get_learning_curve()))
        plt.title("Latencies")
        self.maze.plot_Q()
        plt.show()
        self.maze.navigation_map(alpha=0)
        plt.show()
def main():

    #using try/except block for no file error or any other related errors
    try:
        #creates a maze object from maze class
        maze1 = Maze.Maze("maze6.txt")
        start = maze1.getStart()
        #the first item on path is the start point
        path.append(start)
        end = maze1.getEnd()
        #recursion starts from here
        solve_maze(maze1)

        #checks to see if the path length is zero or 1 it means there was no solutuon
        #or the start and end point were the same
        if len(path) < 2:
            print("Sorry no solution found for this maze!")
        elif len(path) == 1 and end == start:
            print("The start and end point should not be the same.")
        else:
            print("Here is your path from:",
                  start,
                  "\tto:",
                  end,
                  "\n",
                  path,
                  sep="")

    except FileNotFoundError as error:
        print(error)

    except Exception as error:
        print("Sorry, something went wrong.", error)
Exemple #18
0
 def __init__(self):
     self.maze_file = "PacmanMaze"
     self.maze = Maze.Maze(19, 21, self.maze_file)
     self.pacman_speed = 5
     self.ghost_speed = 4
     self.ghost_sequences = [[20, 5]]
     self.number = 2
Exemple #19
0
    def enemies(self):
        em = m.Maze(self.parent, self.width, self.height, self.blank())
        em.spawnEnemy()
        for enemy in em.terrain.enemies:
            enemy.loc = em.terrain.land[3][5]
            enemy.X = enemy.loc.X
            enemy.Y = enemy.loc.Y

        em.player.loc = em.terrain.land[0][0]
        em.player.loc.start = True
        em.player.debt = self.moneyTracker
        em.terrain.land[4][9].target = True
        em.terrain.exit = em.terrain.land[4][9]

        # box around enemy
        #vertical lines
        for i in range(3):
            em.terrain.land[i + 1][5].borders[1] = True
            em.terrain.land[i + 1][4].borders[1] = True
        # horizontal lines
        em.terrain.land[4][5].borders[0] = True

        em.terrain.checkBarriers()

        info = pu.popUp(self.parent, self.width, self.height)
        info.popUpFrame.create_image(0, 0, image=self.eImage, anchor=NW)

        em.display(next=0)
        self.moneyTracker = c.deepcopy(em.player.debt)
        em.unpack()
Exemple #20
0
    def walls(self):
        w = m.Maze(self.parent, self.width, self.height, self.blank())
        w.terrain.land[4][9].target = True

        # horizontal line
        for i in range(10):
            w.terrain.land[2][i].borders[0] = True

        w.terrain.land[1][3].holding = "phase"

        # vertical lines
        for i in range(5):
            w.terrain.land[i][3].borders[1] = True

        w.terrain.land[0][4].holding = "phase"
        w.terrain.land[4][3].holding = "phase"
        w.terrain.land[2][5].holding = "phase"

        for i in range(5):
            w.terrain.land[i][7].borders[1] = True

        w.terrain.land[0][9].holding = "phase"

        w.terrain.checkBarriers()
        w.player.loc = w.terrain.land[0][0]
        w.player.loc.start = True
        w.player.debt = self.moneyTracker

        info = pu.popUp(self.parent, self.width, self.height)
        info.popUpFrame.create_image(0, 0, image=self.wImage, anchor=NW)

        w.display(next=0)
        self.moneyTracker = c.deepcopy(w.player.debt)
        w.unpack()
Exemple #21
0
def allWallsMaze(size):
    walls = []
    for i in range(size[0]):
        walls.append([])
        for j in range(size[1]):
            walls[i].append((True, True))
    return Maze.Maze(walls)
Exemple #22
0
 def setUp(self):
     """
     The setUp function is called each time one of your tests is run.
     We create an instance of the maze here before each test."
     """
     # this checks for a Maze class
     self.m = Maze()
Exemple #23
0
def defineProblem():
    print("Choose the maze you would want to solve: ")
    my_maze = Maze.Maze()
    try:
        file_maze = askopenfilename()
        my_maze.generateMazeJSON(JsonManager.read(file_maze))
    except:
        print("Incorrect format of the JSON file.")
        return 0
    initial = [-1, -1]
    while initial[0] < 0 or initial[0] > my_maze.rows - 1 or initial[
            1] < 0 or initial[1] > my_maze.columns - 1:
        print("Select the initial cell: ")
        initial[0] = int(input("  Initial cell row: "))
        initial[1] = int(input("  Initial cell column: "))
    objective = [-1, -1]
    while objective[0] < 0 or objective[0] > my_maze.rows - 1 or objective[
            1] < 0 or objective[1] > my_maze.columns - 1:
        print("Select the objective cell: ")
        objective[0] = int(input("  Objective cell row: "))
        objective[1] = int(input("  Obejctive cell column: "))
    file = file_maze.split("/")

    JsonManager.writeProblem(initial, objective, file[len(file) - 1],
                             [my_maze.rows, my_maze.columns])
    print("Problem storage on \\problems folder.")
Exemple #24
0
def get_astar_path(sx,sy,ex,ey,mazeX,mazeY,sparsity):
    

    obs,arr=Maze.creat_map([sx,sy],[ex,ey],mazeX,mazeY,sparsity)
    plt.plot(ex,ey,'xm')
    plt.plot(sx,sy,'xm')

    path_planner=A_star.A_Star(obs,[sx,sy],[ex, ey])

    # Plot Mesh
    plt.pcolormesh(arr)
    plt.axes().set_aspect('equal') #set the x and y axes to the same scale
    plt.xticks([]) # remove the tick marks by setting to an empty list
    plt.yticks([]) # remove the tick marks by setting to an empty list
    plt.axes().invert_yaxis() #invert the y-axis so the first row of data is at the top

    start_time=timeit.default_timer()
    path=path_planner.A_Star() 

    # If Path found plot the path
    if path!=None:
        nppath=np.asarray(path)
        end_time=timeit.default_timer()

        print("timing",end_time-start_time)

        plt.plot(nppath[:,0],nppath[:,1],'r-')
        plt.savefig('./frames/astar_final')
        plt.show()   
    else:
        print("path not found")
        plt.show()

    return path
Exemple #25
0
    def test_solve_no_output(self):
        # Based on code from user1200039 http://stackoverflow.com/questions/5136611/capture-stdout-from-a-script-in-python
        import sys
        from io import StringIO
        import LabB2, Maze
        msg = ("""
Most commonly your program fails this test if you use a print statement
in your append function. You must not print anything in class methods.
Instead, you should return the data so that the test code can access it.

Wrong:

def add(a, b):
    ""\" Add a and b.""\"
    print(a+b)

Right:

def add(a, b):
    ""\" Return the sum of a and b.""\"
    return a+b
""")
        enter()
        oldout = sys.stdout
        maze = Maze.Maze(("#@##", "#  #", "##!@"), 0)
        buf = StringIO()
        try:
            sys.stdout = buf
            LabB2.solve(None, maze)
        finally:
            sys.stdout = oldout
        self.assertEqual(len(buf.getvalue()), 0, msg=msg)
        exit()
def TraverseMaze(room,stack):
    """
    Use a simple recursion algo to reach room 1,
    and return all the intermediate transition information.
    Note that this is not an efficient algorithm. 
    Shortest Path cannot be found via this approach either.
    """
    global stack 
    
    if room==1:
       break
    else:
        for i in range(len(room_transition(room))-1)
            colors=Maze.get_exists()
            room_next=Maze.go_through_door(colors[i])
            stack.append(room_transition(room_next))
            TraverseMaze(room_next)
Exemple #27
0
    def setUp(self):
        """
        this will check to see if we have a maze class but as soon
        as setUp is run, we will see a failure so we really don't need
        to do anything here
        """

        self.m = Maze()
Exemple #28
0
def main():
    N = eval(input("Please enter the dimensions for your maze (Your maze will be N x N) "))
    myMaze = Maze(N)

    print("The Red Square is the start")
    print("The Yellow Square is the key")
    print("The Green Square is the end")
    print("The Blue Circles represent the path to the key")
    print("The Black Circles represent the path to the end")
    print("The top left Cell is (0,0), x increases as you move right and y increases as you move down")
    print("The top left Cell is (0,0), x increases as you move right and y increases as you move down")

    myMaze.generateMaze()
    myMaze.explore(myMaze.entrance[0],myMaze.entrance[1])
    #myMaze.printSolution()
    myMaze.Draw()

    myCharacter = Character(myMaze)
    print("You have " + str(len(myMaze.SolutionStack)-2) + " steps to reach the ending")
    print("You are the pink circle, you may use the arrow keys to move")
    gameLoop(myMaze,myCharacter)

    replay = input("Would you like to play again (Y/N)")
    if replay == "Y":
        myMaze.win.close()
        main()
    elif replay == "N":
        myMaze.win.close()
        quit()
    myMaze.win.close()
Exemple #29
0
 def test_nomaze(self):
     enter()
     import Maze, LabB2
     name = "nomaze.txt"
     f = open(name, "r")
     maze = Maze.Maze([line for line in f], 0)
     f.close()
     self.assertIsNone(LabB2.solve(None, maze), \
       msg="None was not returned for a maze with no solution.")
Exemple #30
0
 def items_initialize(self):
     '''Fonction that place the 3 items randomly in the map on the floor
     as a char from '1' to '3' '''
     nb_of_items = 3
     while nb_of_items > 0:
         p = m.Position(random.randint(0, 14), random.randint(0, 14))
         if self.map.get_char(p) == PATH_CHAR:
             self.map.set_char_to_indexes(str(nb_of_items), p)
             nb_of_items -= 1
Exemple #31
0
 def __init__(self):
     self.robot_clients = {}
     self.robot_states = {}
     self.maze = Maze('../data/maze2.pgm')
     # don't use: self.visualizer = GameVisualizerImage(self.maze)
     self.visualizer = GameVisualizer(self.maze)
Exemple #32
0
class GameMaster(object):
    def __init__(self):
        self.robot_clients = {}
        self.robot_states = {}
        self.maze = Maze('../data/maze2.pgm')
        # don't use: self.visualizer = GameVisualizerImage(self.maze)
        self.visualizer = GameVisualizer(self.maze)
        #self.visualizer = GameVisualizerRawTerminal(self.maze)

    def addClient(self, clientName):
        
        print clientName
        module = __import__(clientName)
        if clientName in self.robot_clients.keys():
            clientName = clientName + str(len(self.robot_clients))
        self.robot_clients[clientName] = module.TestClient()   # TODO get class name 
        self.robot_states[clientName] = RobotState()
        start_position = self.maze.getStartPosition()
        self.robot_states[clientName].id = start_position[0]        
        self.robot_states[clientName].position = start_position[1:3]
        self.robot_states[clientName].orientation = start_position[-1]

    def initGame(self):
        pass

    def gameFinished(self):
        goal = self.maze.getGoal()
        for state in self.robot_states.values():
            if goal == state.position:
                return True   
        return False
    
    def getCompass(self,robot_state):
        goal = self.maze.getGoal()
        position = robot_state.position
        angle = math.atan2( goal[1] - position[1] , goal[0] - position[0]) * 180.0 / math.pi + 90;
        compass = round(angle/45) - (robot_state.orientation * 2)
        if compass < 0:
            compass += 8
        return compass
        
        
        
    def startGame(self):
        i = 0 # just for testing
        self.maze.updateRobotStates(self.robot_states)
        while i < 100000 and not self.gameFinished(): #i < 10: #
            i += 1
            #sleep(0.05)
            self.visualizer.showState()
            #a = raw_input()
            print "round",i
            for name, robot in self.robot_clients.items():
                sensor_data = None
                if self.robot_states[name].sense == True:
                    sensor_data = self.maze.getSensorData(self.robot_states[name])
                    sensor_data["battery"] = self.robot_states[name].battery
                    sensor_data["stones"] = self.robot_states[name].stones
                    sensor_data["bombs"] = self.robot_states[name].bombs
                    self.robot_states[name].sense = False
                compass = self.getCompass(self.robot_states[name])
                #try:
                command = robot.getNextCommand(sensor_data, self.robot_states[name].bumper, compass,self.robot_states[name].teleported)
                #except:
                #    print "Error in robot",name,"continue" 
                print name, "command:", Command.names[command]
                print "battery: ", self.robot_states[name].battery

                self.robot_states[name].bumper = False
                self.robot_states[name].teleported = False
                if command == Command.RightTurn:
                    if self.robot_states[name].battery > 0:
                        self.robot_states[name].battery -= 1
                        self.robot_states[name].orientation = (self.robot_states[name].orientation + 1) % 4
                if command == Command.LeftTurn:
                    if self.robot_states[name].battery > 0:
                        self.robot_states[name].battery -= 1
                        self.robot_states[name].orientation = (self.robot_states[name].orientation - 1) % 4
                if command == Command.Sense:
                    self.robot_states[name].sense = True
                if command == Command.DropStone:
                    if self.robot_states[name].stones > 0:
                        position = self.robot_states[name].getIndicees()[2]
                        if self.maze.checkPositionFree(position) == True:
                            self.robot_states[name].stones -= 1
                            self.maze.setStone(position)
                if command == Command.DropBomb:  
                    if self.robot_states[name].bombs > 0:
                        position = self.robot_states[name].getIndicees()[2]
                        if self.maze.checkPositionFree(position) == True:
                            self.robot_states[name].bombs -= 1                            
                            self.maze.setBomb(position)                            
                if command == Command.MoveForward:
                    if self.robot_states[name].battery > 0:
                        self.robot_states[name].battery -= 1
                        position = self.robot_states[name].getIndicees()[0]
                        if self.maze.checkPositionFree(position) == True:
                            self.robot_states[name].position = position[:]
                            if self.maze.checkPortal(position) == True:                               
                                newPosition = self.maze.getFreePortal(self.robot_states)
                                if newPosition != None:
                                    self.robot_states[name].position = newPosition[:]
                                    self.robot_states[name].teleported = True
                        else:
                            self.robot_states[name].bumper = True
                
                if command == Command.Stay:
                    if self.robot_states[name].battery < 100:
                        if self.robot_states[name].position in self.maze.getLoadingStations():
                            self.robot_states[name].battery += 30
                        else:
                            self.robot_states[name].battery += 1
                        if self.robot_states[name].battery > 100:
                            self.robot_states[name].battery = 100
                self.maze.updateRobotStates(self.robot_states)
            self.maze.updateRound(self.robot_states)
Exemple #33
0
from Dead import *
import PyGameFuncs

from sys import argv ###################
#######################################################################

subject_num = ''
if len(sys.argv)>1: #ie if a subject number was input
	subject_num = str(sys.argv[1])
else:
	print("PLEASE ENTER THE PARTICIPANT NUMBER. (Open program by typing eg 'python Output.py 001'")

camera = Camera()
user = MazeMove(camera)

maze = Maze()
hallway_type = maze.current_type()
inventory = Inventory(maze)
output2d = Output2d(camera, inventory, maze)
writefile = WriteFile(maze, subject_num)
time = Time(maze)
dead = Dead(output2d, time, writefile)
glutInit()
was_focused = False

fps = 1000 #added this to try sotp flickering (frames per sec) -didn't work :(

##

def display():
	output2d.draw_images()
Exemple #34
0
def getMaze():
    # Ask user to input maze file name
    filename = input("Please enter the maze file name: ")
    
    # if user enters nothing during input, it will default to maze.txt and try to open it.
    if (filename == ""):
        filename = "maze.txt"
    
    # try to open the file
    try:
        inputFile = open(filename, 'r')
        
    except FileNotFoundError:
        # If it doesnt exist, prints error message and stops
        print ("Error, The file", filename, "does not exist.")
        return None
    
    # Read the map data into theMaze
    theMaze = inputFile.readlines()
    
    # close the file
    inputFile.close()
    
    # Set up the map size, start point, end point
           
    # Grab from first line of map data
    mapSize = theMaze[0].split()
           
    # Split the 2 numbers into rows, cols
    mapSize[0] = 2*int(mapSize[0])+1
    mapSize[1] = 2*int(mapSize[1])+1
    
    # Grab start and end point from line 2 and 3 of file       
    startPoint = theMaze[1].split()
    endPoint = theMaze[2].split()    
    
    # Set up a display window for graphics.py
    win = GraphWin ("Maze Path", 10 * (mapSize[1]), 10 * (mapSize[0]))      
    
    # Generate the board in a list of lists
    generatedMaze = Maze(mapSize[0],mapSize[1])
    
    # Map the maze into my list of lists
    generatedMaze.mappingMaze(theMaze, mapSize)
    
    # Place the start and end points onto the board
    generatedMaze.setPositions(startPoint, endPoint, mapSize)
            
    # Display translated Maze
    generatedMaze.display(generatedMaze, 10, win)   
    
    # Solve the maze
    generatedMaze.solveMaze()
    
    # Display the solution in graphics
    generatedMaze.displaysol(generatedMaze, 10, win)
Exemple #35
0
def makeMaze(rows, columns):
    # Create the display window
    win = GraphWin ("Maze Test", 10 * (columns + 1), 10 * (rows + 1))
    
    # Set up the full maze
    board = Maze (rows, columns)
    
    # Calculate the board center and put it in as the starting point
    r0 = rows // 2
    c0 = columns // 2
    board.set (r0, c0, START)
    queue = []
    queue.append(Point(r0, c0))
    
    while len(queue) > 0:  # As long as there are things to process in the queue
        element = queue.pop(0)  # Get the next location
        r = element.getX()
        c = element.getY()
        
        r1 = r + 2   # Move down two and see if we can cut a corridor
        if board.onMap (r1, c) and board.get(r1, c) == ROCK and random.random() < PROBABILITY:
            board.set(r+1, c, OPEN)
            board.set(r1, c, OPEN)
            queue.append(Point(r1, c))
        r1 = r - 2   # Move up two and see if we can cut a corridor
        if board.onMap (r1, c) and board.get(r1, c) == ROCK and random.random() < PROBABILITY:
            board.set(r-1, c, OPEN)
            board.set(r1, c, OPEN)
            queue.append(Point(r1, c))
        c1 = c + 2   # Move right two and see if we can cut a corridor
        if board.onMap (r, c1) and board.get(r, c1) == ROCK and random.random() < PROBABILITY:
            board.set(r, c+1, OPEN)
            board.set(r, c1, OPEN)
            queue.append(Point(r, c1))        
        c1 = c - 2   # Move left two and see if we can cut a corridor
        if board.onMap (r, c1) and board.get(r, c1) == ROCK and random.random() < PROBABILITY:
            board.set(r, c-1, OPEN)
            board.set(r, c1, OPEN)
            queue.append(Point(r, c1))
            
    # Starting at one of the four sides, place the exit
    side = random.randint(0,3)
    if side == 0:   # Top edge
        steps = columns // 2
        cStart = 1 + 2 * random.randint(0, (steps // 2))
        rStart = 0
        board.set (0, cStart, EXIT)
        dRow = 1
        dCol = 0
    elif side == 1:  # Bottom edge
        steps = columns // 2
        cStart = 1 + 2 * random.randint(0, (steps // 2))
        size = board.getSize()
        rStart, c1 = size
        rStart-=1
        board.set (rStart, cStart, EXIT)
        dRow = -1
        dCol = 0 
    elif side == 2:  # Left edge
        steps = rows // 2
        rStart = 1 + 2 * random.randint(0, (steps // 2))
        cStart = 0
        board.set (rStart, 0, EXIT)
        dRow = 0
        dCol = 1
    else:            # Right Edge
        steps = rows // 2
        rStart = 1 + 2 * random.randint(0, (steps // 2))
        size = board.getSize()
        r1, cStart = size
        cStart-=1
        board.set (rStart, cStart, EXIT)
        dRow = 0
        dCol = -1 
        
    # Cut a corridor inward from the exit until you contact the maze
    rStart += dRow
    cStart += dCol
    while board.get(rStart, cStart) == ROCK:
        board.set (rStart, cStart, OPEN)
        rStart += dRow
        cStart += dCol
        
    # Display the maze and wait for the person to click
    board.display (board, 10, win)
    
    win.getMouse()
    win.close()