示例#1
0
 def __init__(self):
     self.g1 = grid.Grid()
     self.g2 = grid.Grid()
     self.ships = []
     self.hits = []
     self.misses = []
     self.damage = 0
示例#2
0
    def __init__(self, map=""):
        self.gridMap = [[None for x in range(0, self.MAP_WIDTH)]
                        for y in range(0, self.MAP_HEIGHT)]

        # Need to use IF since there cannot be > 1 constructor
        if len(map) > 0:
            # Map iterator
            i = 0
            for n in range(0, self.MAP_HEIGHT):
                for m in range(0, self.MAP_WIDTH):
                    if map[i] == '0':
                        self.gridMap[n][m] = Grid(n, m, GridState.UNEXPLORED)
                    elif map[i] == '1':
                        self.gridMap[n][m] = Grid(
                            n, m, GridState.EXPLORED_NO_OBSTACLE)
                    elif map[i] == '2':
                        self.gridMap[n][m] = Grid(
                            n, m, GridState.EXPLORED_WITH_OBSTACLE)

                    i += 1

        else:
            for n in range(0, self.MAP_HEIGHT):
                for m in range(0, self.MAP_WIDTH):
                    self.gridMap[n][m] = Grid(n, m)

        # Determine where the START and END zone are
        for i in range(0, 3):
            for j in range(0, 3):
                self.gridMap[i][j].setGridState(GridState.START_ZONE)
                self.gridMap[self.MAP_HEIGHT - i - 1][self.MAP_WIDTH - j -
                                                      1].setGridState(
                                                          GridState.END_ZONE)
示例#3
0
def main():
    # One of the 2 dimension of the window. (Window must be a square)
    square_size = int(input('Insert one dimension of the square: '))

    # Window settings
    win = GraphWin('Sorter', square_size, square_size)
    win.setBackground('black')

    # Text settings
    txt = Text(Point((square_size / 2) + (square_size / 4), 20), "swap=0")
    txt.setTextColor('white')
    txt.draw(win)
    txt_for_pause = Text(Point(square_size / 2, square_size / 2),
                         'Click on the screen to start')
    txt_for_pause.setTextColor('white')

    # Grid settings
    grid = Grid(square_size)
    grid.shuffle()

    # Draws all the point on the canvas
    draw_points(win, grid.pixel_grid)

    # Draws a text befor starting the sort
    txt_for_pause.draw(win)
    win.getMouse()
    txt_for_pause.undraw()

    # Starts the bubble sorting
    bubble_sort(win, grid, txt)

    # Wait for user input
    win.getMouse()
    win.close()
示例#4
0
    def reformGrid(self, arr):
        """
        Ants transmit the following data structure
        Integer specifying the length of foodLocSet
        Integer specifying the length of the unexploredLocSet
        
        A 1-dimensional array and the length of the rows
        and returns a 2-dimensional array.

        Assumes that there are an equal number of rows and cols
        """

        offset1, offset2, offset3, offset4 = arr[0], arr[1], arr[2], arr[3] 
       
        
        externalUnexploredLocSet = arr[offset1:offset2]
        externalFoodLocSet = arr[offset2:offset3]
        externalExhaustedFoodLoc = arr[offset3:offset4] 
        externalMap = arr[offset4:] 

        ## internal maps are square. the square root of the array
        ## gives us the length of the rows
        N = int(math.sqrt(len(externalMap)))
        
        output = Grid(N,N)

        for row in xrange(N):
            for col in xrange(N):
                output.setAt(row, col, externalMap[row*N + col])

        return (externalUnexploredLocSet, externalFoodLocSet, externalExhaustedFoodLoc, output) 
示例#5
0
    def setGrids(self, number):
        self.grids = []
        for i in range(number - 1):
            if i % 2 == 0:
                grid = Grid.Grid(self.screen,
                                 position=(50 + 100 * i,
                                           random.randint(280, 400)),
                                 scale=0.4)
            else:
                grid = Grid.Grid(self.screen,
                                 position=(50 + 100 * i,
                                           random.randint(80, 150)),
                                 scale=0.4)

            if random.uniform(0, 1) >= 0.3:
                grid.setTrap(True)

            self.grids.append(grid)

        grid = Grid.Grid(self.screen,
                         image="gridFlag.png",
                         image2="gridFlag2.png",
                         position=(50 + 100 * (i + 1), random.randint(80,
                                                                      150)),
                         scale=0.4)

        if random.uniform(0, 1) >= 0.7:
            grid.setTrap(True)

        self.grids.append(grid)
示例#6
0
 def __init__(self):
     self.grid = Grid(16, 30, 0.2)
     # self.grid.generateSpecificGrid()
     self.grid.generateGrid()
     self.grid.markMineNumber()
     self.totalNumOfMine = self.grid.numOfMine
     self.currentNumOfMine = self.totalNumOfMine
示例#7
0
    def __init__(self, window):
        '''
        This method is called when the scene is created
        Create and/or load any assets (images, buttons, sounds)
        that you need for this scene
        :param window:
        '''
        # Save window in instance variable
        self.window = window

        # 4 - Load assets: image(s), sounds,  etc.
        self.oGrid = Grid(window)
        self.oPlayer = Player(window)
        self.oBackground = pygwidgets.Image(window, (0, 0), 'images/background.jpg')
        self.oLevelDisplay = pygwidgets.DisplayText(window, (20, 15), '', fontSize=28)
        self.oLivesDisplay = pygwidgets.DisplayText(window, (120, 15), '', fontSize=28)
        self.oScoreDisplay = pygwidgets.DisplayText(window, (220, 15), '', fontSize=28)
        self.oBonusDisplay = pygwidgets.DisplayText(window, (350, 15), '', fontSize=28, textColor=(0, 153, 0))

        self.dingSound = pygame.mixer.Sound('sounds/ding.wav')
        self.winSound = pygame.mixer.Sound('sounds/win.wav')
        self.upSound = pygame.mixer.Sound('sounds/plus.wav')
        self.downSound = pygame.mixer.Sound('sounds/minus.wav')
        self.bonusSound = pygame.mixer.Sound('sounds/bonus.wav')
        self.splatSound = pygame.mixer.Sound('sounds/splat.wav')
        self.loseSound = pygame.mixer.Sound('sounds/lose.wav')
        self.state = ScenePlay.STATE_PLAYING
        self.oTimer = pyghelpers.Timer(.75, callBack=self.startNextRound) # wait 3/5 sec between rounds

        self.reset()
示例#8
0
    def reformGrid(self, arr):
        """
        Ants transmit the following data structure
        Integer specifying the length of foodLocSet
        Integer specifying the length of the unexploredLocSet
        
        A 1-dimensional array and the length of the rows
        and returns a 2-dimensional array.

        Assumes that there are an equal number of rows and cols
        """

        offset1, offset2, offset3, offset4 = arr[0], arr[1], arr[2], arr[3]

        externalUnexploredLocSet = arr[offset1:offset2]
        externalFoodLocSet = arr[offset2:offset3]
        externalExhaustedFoodLoc = arr[offset3:offset4]
        externalMap = arr[offset4:]

        ## internal maps are square. the square root of the array
        ## gives us the length of the rows
        N = int(math.sqrt(len(externalMap)))

        output = Grid(N, N)

        for row in xrange(N):
            for col in xrange(N):
                output.setAt(row, col, externalMap[row * N + col])

        return (externalUnexploredLocSet, externalFoodLocSet,
                externalExhaustedFoodLoc, output)
示例#9
0
    def test_generators(self):

        m = 5
        n = 8

        self.assertEqual(len(list(Grid.diagonal_generator(n))), n**2)
        self.assertEqual(len(list(Grid.matrix2d_generator(m, n))), m * n)
示例#10
0
 def test_addData_time(self):
     #检查addData后若time小于之前的更新时间,是否会抛出异常
     g=Grid()
     g._Grid__time_update=1000
     with self.assertRaisesRegex(ValueError,"time_update"):
         raw=HelperForTest.randomLegalRawData()
         g.addData(raw,500)
示例#11
0
def testSynthetic():
    '''Test against a synthetic set of pedestrians'''
    SIZE = 10.0
    # define the domain
    minCorner = Vector2( -SIZE / 2.0, -SIZE / 2.0 )
    domainSize = Vector2( SIZE, SIZE )
    RES = int( SIZE / CELL_SIZE )
    resolution = Vector2( RES, RES )
   
    # define the signal ( a single point, moving from the origin to the corner
    traj, STEP_COUNT = syntheticPedestrians( SIZE )

    print "Maximum kernel value:", kernel.data.max()
    print "Kernel sum:          ", kernel.data.sum()
    grids = []

    pedDomain = Grid.RectDomain( minCorner, domainSize )    
    sig = Signals.DiracSignal( pedDomain )
    
    for i in xrange( STEP_COUNT ):
        sig.setData( traj[:, :, i] )
        grid = Grid.DataGrid( minCorner, domainSize, resolution )
        kernel.convolve( sig, grid )
##        grid.cells /= ( CELL_SIZE * CELL_SIZE )
        grids.append( grid )
    
    visGrids( grids )
示例#12
0
 def test_walk(self):
     for grid in generate_test_grids():
         # iterate points
         for x in range(grid.xmax):
             for y in range(grid.ymax):
                 num = 0
                 for point in [
                         grid.above(Grid.Point(x, y)),
                         grid.below(Grid.Point(x, y)),
                         grid.right(Grid.Point(x, y)),
                         grid.left(Grid.Point(x, y))
                 ]:
                     if point is not None:
                         if point.status is not '0':
                             num += 1
                 if x == 0 and y == 0:
                     self.assertEqual(len(grid.walk(Grid.Point(x, y))), num,
                                      "FAIL on minimum corner")
                 elif x == grid.xmax - 1 and y == grid.ymax - 1:
                     self.assertEqual(len(grid.walk(Grid.Point(x, y))), num,
                                      "FAIL on maximum corner")
                 elif x == 0 or y == 0:
                     self.assertEqual(len(grid.walk(Grid.Point(x, y))), num,
                                      "FAIL on minimum edge")
                 elif x == grid.xmax - 1 or y == grid.ymax - 1:
                     self.assertEqual(len(grid.walk(Grid.Point(x, y))), num,
                                      "FAIL on maximum edge")
                 else:
                     self.assertEqual(len(grid.walk(Grid.Point(x, y))), num,
                                      "FAIL internal point")
         # try point outside range
         x = 2 * grid.xmax
         y = 2 * grid.ymax
         self.assertEqual(len(grid.walk(Grid.Point(x, y))), 0,
                          "FAIL external point")
示例#13
0
	def getGrids(self) :
		self.__grids = []
		nbRows_l = self.__worksheet.nrows - 1
		nbCols_l = self.__worksheet.ncols - 1
		currRow_l = -1 # start at first line
		while currRow_l < nbRows_l:
			grid_l = Grid()
			currRow_l += 1
			row_l = self.__worksheet.row(currRow_l)
#print 'Row:', currRow_l
			if self.__worksheet.cell_type(currRow_l, 0) != 0 : # not emty cell
				currCol_l = -1 # first col
				while currCol_l < nbCols_l:
					currCol_l += 1
					# Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank
					cellType_l = self.__worksheet.cell_type(currRow_l, currCol_l)
					cellValue_l = self.__worksheet.cell_value(currRow_l, currCol_l)
#print '	', cellType_l, ':', cellValue_l
					if currCol_l == 0 :
						grid_l.setBet(cellValue_l)
					else :
						grid_l.setNextCell(cellValue_l, cellType_l)

				self.__grids.append(copy.deepcopy(grid_l))

			else :
				nbRows_l = currRow_l
		
		return self.__grids
示例#14
0
def main():
    # CHANGE THE Constants.TO_RUN VARIABLE TO CHANGE THE ALGORITHM BEING RAN. OPTIONS:
    # BFS
    # DIJKSTRA
    # ASTAR
    algorithmToRun = Constants.TO_RUN

    pygame.init()

    SCREEN = pygame.display.set_mode(Constants.SCREEN)
    SCREEN.fill(Constants.WHITE)

    grid = Grid(Constants.SCREEN_WIDTH_AND_HEIGHT, 10)
    draw = Draw(SCREEN, grid.get_grid(), grid.get_room_per_node())
    draw.draw_grid()
    pygame.display.flip()

    run = Run(grid, draw)

    if algorithmToRun == Constants.BFS:
        run.run_bfs()
    elif algorithmToRun == Constants.DIJKSTRA:
        run.run_dijkstra()
    elif algorithmToRun == Constants.ASTAR:
        run.run_astar()
    else:
        run.run_bfs()
示例#15
0
 def __init__(self, width, height, *board):
     self.__board = Grid(width, height, ConwaysLogic.TRAITS)
     self.__width = width
     self.__height = height
     if board:
         for i in range(0, width):
             for j in range(0, height):
                 self.__board.setValue(i, j, "Value", board[i][j])
示例#16
0
 def __init__(self, name, species="human", score=0):
     self.remaining_shots = {}
     self.species = species
     self.name = name
     self.score = score
     self.grid = Grid(self.species, self.name)
     self.eliminated = False
     self.occupied_spaces = {}
示例#17
0
 def set_grid(self):
     if(len(self.args_grid)!=0):
         if(self.args_grid[2]==1):
             temp=Grid.get_simple_grid(self.args_grid[0],self.args_grid[1])
             self.grid=temp
         if (self.args_grid[2] == 2):
             temp = Grid.get_powerlaw_grid(self.args_grid[0], self.args_grid[1],self.args_grid[3],)
             self.grid = temp
示例#18
0
 def test_addData_timeUpdate(self):
     g = Grid()
     t=1
     rawData=HelperForTest.randomLegalRawData()
     for i in range(1,50):
         t+=random.randint(1,500)
         g.addData(rawData,t)
         self.assertEqual(g._Grid__time_update,t)
 def __init__(self, width, height, numMines):
     self.__width = width
     self.__height = height
     if numMines > width * height - MineSweeperLogic.NUM_EMPTY:
         self.__numMines = width * height - MineSweeperLogic.NUM_EMPTY
     else:
         self.__numMines = numMines
     self.__board = Grid(width, height, MineSweeperLogic.TRAITS)
示例#20
0
 def test_size(self):
     #case1:返回正确的size
     cluster=Cluster(1)
     self.assertEqual(len(cluster._Cluster__grid_dic),cluster.size())
     for i in range(1,10):
         grid=Grid()
         grid._Grid__key=i
         cluster.addGrid(grid)
     self.assertEqual(len(cluster._Cluster__grid_dic), cluster.size())
示例#21
0
 def test_isGridExistWithKey(self):
     # case1:存在返回True
     cluster=Cluster(1)
     self.assertFalse(cluster.isGridExistWithKey(1))
     # case2:不存在返回false
     grid=Grid()
     grid._Grid__key=1
     cluster.addGrid(grid)
     self.assertTrue(cluster.isGridExistWithKey(1))
示例#22
0
 def test_key(self):
     # TODO:制造100个随机的合法rawData,测key()函数能否正确返回该key值
     for i in range(1, 100 + 1):
         rawData = HelperForTest.randomLegalRawData()
         right_key = Helper().getKeyFromRawData(rawData)
         g = Grid()
         g.addData(rawData, random.randint(1,10000))
         totest_key =g.key()
         self.assertEqual(right_key,totest_key)
示例#23
0
    def test_densityThreshold(self):
        last_time = random.randint(1, 10000)
        cur_time=last_time+random.randint(1,10000)

        value=Helper().Cl*(1-Helper().lamb**(cur_time-last_time+1))/(Helper().N*(1-Helper().lamb))
        g=Grid()
        g._Grid__time_update=last_time

        self.assertEqual(value,g.densityThreshold(cur_time))
示例#24
0
    def test_addData_key(self):

        #TODO:add之后检查key是否正确,检查错误的rawData抛出异常,检查当前更新时间是否正确、想办法测试change,测试TODELETE
        g=Grid()
        rawData=HelperForTest.randomLegalRawData()
        correct_key=Helper.getKeyFromRawData(rawData)
        g.addData(rawData,1)
        self.assertEqual(correct_key,g.key())
        self.assertEqual(1,g._Grid__time_update)
示例#25
0
文件: Bug.py 项目: Unilat/bugs
 def _move(self):
     debug("MOVE");
     pos = self._one_ahead();
     
     if Grid.get_pos(pos) == Grid.states.EMPTY:
         # Set where we were to empty
         Grid.set_pos(self._pos, Grid.states.EMPTY)
         # Set new position to filled
         self._pos = pos
         Grid.set_pos(pos, self)
示例#26
0
文件: Bug.py 项目: Calpoog/bugs
    def _move(self):
        debug("MOVE")
        pos = self._one_ahead()

        if Grid.get_pos(pos) == Grid.states.EMPTY:
            # Set where we were to empty
            Grid.set_pos(self._pos, Grid.states.EMPTY)
            # Set new position to filled
            self._pos = pos
            Grid.set_pos(pos, self)
示例#27
0
 def addNewData(self, rawData, time):
     logging.debug("Pw:" + str(rawData.PW) + " RF:" + str(rawData.RF) +
                   " DOA:" + str(rawData.DOA) + " time:" + str(time))
     key = Helper().getKeyFromRawData(rawData)
     if not key in self.__grid_list:
         grid_object = Grid()
         grid_object.addData(rawData, time)
         self.__grid_list[key] = grid_object
     else:
         self.__grid_list[key].addData(rawData, time)
示例#28
0
    def visualize(self, states):
        clock = pygame.time.Clock()
        for i in range(len(states)):
            #print (states[i][1].topLeftXBlock, states[i][1].topLeftYBlock)
            grid = Grid.Grid(self.gridWidth, self.gridHeight)
            grid = Grid.states_to_grid(states[i], grid)
            self.drawGrid(self.screen, grid, 100, 100, 20, 1, states[i][1])
            pygame.display.update()

            clock.tick(120)
示例#29
0
 def __init__(self, *args, **kwargs):
     super(MyWindow, self).__init__(*args, **kwargs)
     #this clear thing affect the background color
     #comment it out to get a black background
     glClearColor(1, 1.0, 1.0, 1)
     self.fps_display = FPSDisplay(self)
     self.car = CarSprite()
     self.key_handler = key.KeyStateHandler()
     self.testTrack = Track([40, 60, 1200, 600], [240, 260, 800, 200])
     self.testGrid = Grid(40, 60, 1200, 600, 50)
示例#30
0
    def test_isGridExist(self):

        #case1:存在返回False
        cluster=Cluster(1)
        grid=Grid()
        grid._Grid__key=342
        self.assertFalse(cluster.isGridExist(grid))
        #case2:不存在返回True
        cluster.addGrid(grid)
        self.assertTrue(cluster.isGridExist(grid))
示例#31
0
def main(size, colors, max_iteration):
    grid = Grid(size)
    X = []
    Y = []
    iteration = 0
    while iteration < max_iteration :
        
        grid.perform_next_step(colors)
        mapped_states = np.array(grid.get_states_colors())
        plt.figure(figsize=(10, 10))
        start = time.time()
        for color in colors:            
            if iteration is not 0:
                grid.reload_grid()
            for i in range(grid.get_grid_size()):
                for j in range(grid.get_grid_size()):
                    if mapped_states[i][j] == color:
                        X = np.insert(X, len(X),i)
                        Y = np.insert(Y, len(Y),j)                        
            plt.scatter(X, Y, s=1, marker = 's', c = color)
            X = []
            Y = []

        end = time.time()
        print('Time of performing next iteration: ' + str(end - start))
        plt.axis([-1, size, -1, size])
        plt.title('Iteration: ' + str(iteration))
        plt.xlabel('X') 
        plt.ylabel('Y')
        plt.show()
        iteration += 1
示例#32
0
    def test_getGrid(self):

        #case1:key不存在,抛出异常
        cluster=Cluster(1)
        with self.assertRaises(KeyError):
            cluster.getGrid(1)
        #case2:grid存在得到对应的Grid
        grid=Grid()
        cluster.addGrid(grid)
        g=cluster.getGrid(grid.key())
        self.assertEqual(grid.key(),g.key())
示例#33
0
 def test_getAllGrids(self):
     #case1:返回本Cluster的所有Grids
     cluster=Cluster(1)
     grid_dic=cluster.getAllGrids()
     self.assertEqual(len(grid_dic),len(cluster._Cluster__grid_dic))
     for i in range(1,10):
         grid=Grid()
         grid._Grid__key=i
         cluster.addGrid(grid)
     grid_dic = cluster.getAllGrids()
     self.assertEqual(len(grid_dic), len(cluster._Cluster__grid_dic))
示例#34
0
文件: Bug.py 项目: Unilat/bugs
 def __init__(self, pos, facing, team):
     '''
     Constructor takes a starting pc and a reference to code array.
     '''
     self.team = team
     self._pc = team.bugCode[0]
     self._code = team.bugCode
     self._stack = []
     self._pos = pos
     self._direction = facing
     
     # Indicate where we've placed the bug is taken
     Grid.set_pos(pos, self)
示例#35
0
文件: Bug.py 项目: Unilat/bugs
    def _check_cond(self, test):

        what_is_next =  Grid.get_pos(self._one_ahead())
        next_bug = self._next_is_bug()

        if test == Constants.codes.JUMP_IF_NOT_NEXT_IS_EMPTY and \
            what_is_next != Grid.states.EMPTY:
            return True
        elif test == Constants.codes.JUMP_IF_NOT_NEXT_IS_NOT_EMPTY and \
            what_is_next == Grid.states.EMPTY:
            return True
        elif test == Constants.codes.JUMP_IF_NOT_NEXT_IS_ENEMY and \
            (not next_bug or next_bug.team.id == self.team.id):
            return True
        elif test == Constants.codes.JUMP_IF_NOT_NEXT_IS_NOT_ENEMY and \
            (next_bug and next_bug.team.id != self.team.id):
            return True
        elif test == Constants.codes.JUMP_IF_NOT_NEXT_IS_FRIEND and \
            (not next_bug or next_bug.team.id != self.team.id):
            return True
        elif test == Constants.codes.JUMP_IF_NOT_NEXT_IS_NOT_FRIEND and \
            (next_bug and next_bug.team.id == self.team.id):
            return True
        elif test == Constants.codes.JUMP_IF_NOT_NEXT_IS_WALL and \
            what_is_next != Grid.states.WALL:
            return True
        elif test == Constants.codes.JUMP_IF_NOT_NEXT_IS_NOT_WALL and \
            what_is_next == Grid.states.WALL:
            return True
        elif test == Constants.codes.JUMP_IF_NOT_RANDOM and \
            randint(0, 1):
            return True
        else: # JUMP IF NOT TRUE
            return False
示例#36
0
文件: display.py 项目: Unilat/bugs
 def populate(self):
     '''
     Creates the bug objects and corresponding canvas graphics.
     '''
     
     for team in range(len(teams)):
         for i in range(teams[team].numBugs):
             x = randint(0,19)
             y = randint(0,19)
             while Grid.get_pos([x,y]) != Grid.states.EMPTY:
                 x = randint(0,19)
                 y = randint(0,19)
                 
             bug = Bug([x,y], randint(0,3), teams[team])
             self.buglist.append(bug)
             self.bugimages.append(self.canvas.create_image(bug._pos[0]*20+14,bug._pos[1]*20+14, \
                                                        image=self.bugdict["bug"+str(team+1)+str(bug._direction)]))
             
         # Set up graphics for bug statistics in the right panel
         self.canvas.create_rectangle(415, team * 70 + 2, 595, team * 70 + 64, \
                                      fill="#fafafa", outline="#ddd")
         self.teamLabels.append(self.canvas.create_text(420, team * 70 + 6, text="Team " + str(team+1), anchor=NW, font=("Helvetica", "13"), fill="#444"))
         self.teamCurrentLabels.append(self.canvas.create_text(420, team * 70 + 44, text="Current: " + str(teams[team].numBugs), anchor=NW, fill="#444"))
         self.teamMinLabels.append(self.canvas.create_text(495, team * 70 + 44, text="Min: " + str(teams[team].minBugs), anchor=NW, fill="#444"))
         self.teamMaxLabels.append(self.canvas.create_text(550, team * 70 + 44, text="Max: " + str(teams[team].maxBugs), anchor=NW, fill="#444"))
         self.teamGraphs.append(self.canvas.create_rectangle(415, \
                                         team * 70 + 27, 420 + 167 * teams[team].percent(), \
                                         team * 70 + 42, fill=colors[team], outline=borders[team]))
示例#37
0
def testAlgo(model, init=0):
    i = 0
    if init == 0:
        state = Grid.initGrid()
    elif init == 1:
        state = Grid.initGridPlayer()
    elif init == 2:
        state = Grid.initGridRand()

    print("Initial State:")
    print(Grid.dispGrid(state))
    status = 1
    # while game still in progress
    while (status == 1):
        qval = model.predict(state.reshape(1, 64), batch_size=1)
        action = (np.argmax(qval))  # take action with highest Q-value
        print('Move #: %s; Taking action: %s' % (i, action))
        state = Grid.makeMove(state, action)
        print(Grid.dispGrid(state))
        reward = Grid.getReward(state)
        if reward != -1:
            status = 0
            print("Reward: %s" % (reward,))
        i += 1  # If we're taking more than 10 actions, just stop, we probably can't win this game
        if i > 10:
            print("Game lost; too many moves.")
            break
示例#38
0
文件: Bug.py 项目: Unilat/bugs
 def _next_is_bug(self):
     nxt =  Grid.get_pos(self._one_ahead())
     
     if nxt != Grid.states.EMPTY and \
         nxt != Grid.states.WALL:
         return nxt
     else:
         # the next position is either a wall or empty
         return 0
示例#39
0
 def __init__(self):
   self.grid = Grid(gridWidth, gridHeight)
   for i in range(numBots):
     self.age = 0.0
     bot = Bot()
     x = random.randint(0, gridWidth-1)
     y = random.randint(0, gridWidth-1)
     self.grid.getNode(x, y).add(bot)
     self.createCode()
     self.stepCount = 0
示例#40
0
def rotated2geo(lon, lat, pole_latitude, pole_longitude):
    '''
    Use function from PyRemo to convert from rotated to geographical coordinates.

    pole_latitude  - latitude of rotated north pole
    pole_longitude - longitude of rotated north pole

    '''
    grid_lon, grid_lat = gr.rotated_grid_transform(lon, lat, pole_latitude,pole_longitude)
    return grid_lon, grid_lat
示例#41
0
def main():
   """
   The main core of the program.
   """

   global time
   global MAX_ITER
   global output_dt

   # ==========================================================================
   # Initialize
   # - Returns a dictionary of dictionaries, which are the parameters from the
   #   configuration file (by section) and from the command line (listed as
   #   section 'CommandLine')
   params = init()

   # ==========================================================================
   # Evolution loop

   prev_write = -1

   for n_iter in xrange(MAX_ITER):

      # Exceeded maximum time
      if time >= tmax:
         break

      # Unexpected exit? (e.g. like "touch .dump_restart")
      # TODO

      # Write output
      do_write = False
      if output_dt > 0:
         curr_write = int(math.floor(time / output_dt))
         if curr_write > prev_write:
            do_write = True
         prev_write = curr_write
      if do_write:   # to allow for a condition based on step number
         Grid.write_data(n_iter)

      # Boundary condition fill
      Grid.fill_boundary_conditions()

      # Compute step size
      dt = compute_time_step()

      # Evolve a single step
      Hydro.one_step(dt)

      # Update time
      time = time + dt

   # End evolution loop

   # ==========================================================================
   # Finalize

   # Write final output
   Grid.write_data(n_iter+1)
   finalize()
示例#42
0
文件: Main.py 项目: flomonster/Hanjie
def lancer_niveau():
    """Launch a level"""

    global ig
    global grid
    global Secret_grid
   
    Nom = my_listbox.get(my_listbox.curselection())
    
    for widget in fenetre.winfo_children():
        widget.destroy()
           
    Secret_grid = Grid()
    Secret_grid.Load(Nom)
    grid = Grid(Secret_grid.getLargeur(),Secret_grid.getHauteur())
    
    ig = Game(Secret_grid, fenetre)
    ig.Zone_dessin.bind("<Button-1>",pointerB1)
    ig.Zone_dessin.bind("<Button-3>",pointerB3)
    ig.Zone_dessin.bind("<B1-Motion>",slideB1)
    ig.Zone_dessin.bind("<B3-Motion>",slideB3)
    ig.Bouton_Effacer.config(command=effacer)
    ig.Bouton_Retour.config(command=retour)
示例#43
0
 def parseInitialConditions(self, msg):
     '''
     The first thing the Server will do when the game is signaled to begin is to send 
     the initial conditions so that each client can set up, getting info about which player
     ID its been assigned, how large the grid is, and where the bases are for each player on 
     the grid.
     '''
     
     m = re.match("([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)", msg)
     if m and int(m.group(1)) == GAME_START_CODE:
         # So the client knows which player it's displaying information for
         playerID = int(m.group(2))
         self.playerID = playerID
         
         numRows = int(m.group(3))
         numCols = int(m.group(4))
         aBaseRow = int(m.group(5))
         aBaseCol = int(m.group(6))
         bBaseRow = int(m.group(7))
         bBaseCol = int(m.group(8))
         
         # The player always starts off in the middle of his base
         myPlayer = False
         enemyPlayer = False
         i = 1
         while i < 3:
             playerRow = 0
             playerCol = 0
             if i == 1:
                 playerRow = aBaseRow + int(math.ceil(BASE_SIZE / 2))
                 playerCol = aBaseCol + int(math.ceil(BASE_SIZE / 2))
             else:
                 playerRow = bBaseRow + int(math.ceil(BASE_SIZE / 2))
                 playerCol = bBaseCol + int(math.ceil(BASE_SIZE / 2))
             
             self.players.append(PlayerSprite(i, playerRow, playerCol))
             if i == self.playerID: 
                 myPlayer = self.players[i-1]
             else:
                 enemyPlayer = self.players[i-1]
             i+= 1
         
         self.grid = Grid(numRows, numCols)
         self.grid.addBase(aBaseRow, aBaseCol, A_BASE_UNIT)
         self.grid.addBase(bBaseRow, bBaseCol, B_BASE_UNIT)
         self.gameStarted = True
         
         self.viewport = Viewport(self.grid, myPlayer, enemyPlayer)
     else:
         print "invalid initial conditions"
示例#44
0
    def __init__(self,inputPrintActions):
        """
        Ants are initialized with a 20x20 internal map. All tiles (except the
        starting tile) on the internal map are initially set to -100 which
        represents unexplored tiles. 

        The starting position of the ant is assumed to be (row, col)
        (9,9), the center of the internal map.

        Ants are initialized with zero food.

        Ants are intialzied with no route plan.

        The internal representation for ants is as follows:
        -100: unknown tile
        -101: travelable tile
        -102: untravelable tile
        -103: home tile
        0-127: food
        """

        self._foodKnown = False
        self._hasFood = False
        self._newFoodFound = False
        self._gridLen = 20
        self._receiveMap = False
        self._routePlan = []
        self._routePlanType = "UNKNOWN" 
        self._memo = {}
        self._row = 9
        self._col = 9
        self._homeRow = 9
        self._homeCol = 9
        self._foodLoc = (0,0)
        self._unexploredLoc = (0,0)
        self._foodLocSet = set()
        self._unexploredLocSet = set()
        self._exhaustedFoodLocSet = set()
        self._dirs = dict([("NORTH",(-1,0)),("EAST",(0,1)),("SOUTH",(1,0)),("WEST",(0,-1))])
        self._nReceives = 0
        self._printActions = inputPrintActions
        
        ## create a 2-dimensional grid to represent the world
        ## for the ant
        self._internalMap = Grid(self._gridLen, self._gridLen, -100) 

        self._internalMap.setAt(self._homeRow, self._homeCol, -103)    ##103 represents the home tile
示例#45
0
def test_1():
	allcells=[]


	x = 10
	y = 10

	g = Grid.grid(10,10)
	print g

	for i in range(0,y):
		column = []
		for j in range(0,x):
			column.append(Cell.cell((i,j)))
		allcells.append(column)

	c = Cell.cell((0,0))
	c.getNeighbours()
示例#46
0
文件: Game.py 项目: hinsert/tunneler
 def __init__(self, playerHandlers, numRows, numCols, server):
     self.timestep = 0 
     self.changes = ""
     self.handlersReady = []
     self.commands = []
     self.bullets = []
     self.nextBulletID = 3
     self.server = server
     self.gameAlreadyOver = False
     
     self.grid = Grid(numRows, numCols)
     aBaseRow, aBaseCol = self.grid.createRandomBasePosition()
     bBaseRow, bBaseCol = self.grid.createRandomBasePosition()
     self.grid.addBase(aBaseRow, aBaseCol, A_BASE_UNIT)
     self.grid.addBase(bBaseRow, bBaseCol, B_BASE_UNIT)
     
     self.playerHandlers = playerHandlers
     self.createPlayers(aBaseRow, aBaseCol, bBaseRow, bBaseCol)
     self.sendInitialGameConditions()
示例#47
0
    def __init__(self, **kwargs):
        super(Knot_Display, self).__init__(**kwargs)
        self.t = 0.0
        self.orientation = Quat(1, Vec3(0,0,0))
        self.zoom = 1.0

        self.grid = Grid(100, 100)


        self.program = ShaderProgram(
            FragmentShader('''#version 130
                              uniform float pi = 3.14159;
                              varying vec2 uv;
                              //vec4 torus_normal(float v15, float v16) { return vec4((-6.28318520000000 * pow(pow((-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))), 2), (-1/2)) * pow(((39.4784162574990 * pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + (39.4784162574990 * pow(cos((6.28318520000000 * v15)), 2)) + (39.4784162574990 * pow(cos((6.28318520000000 * v16)), 2)) + (-39.4784162574990 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2))), (-1/2)) * (-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v15)) * cos((6.28318520000000 * v16))), (-6.28318520000000 * pow(pow((-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))), 2), (-1/2)) * pow(((39.4784162574990 * pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + (39.4784162574990 * pow(cos((6.28318520000000 * v15)), 2)) + (39.4784162574990 * pow(cos((6.28318520000000 * v16)), 2)) + (-39.4784162574990 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2))), (-1/2)) * (-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v16)) * sin((6.28318520000000 * v15))), (pow((197.392081287495 + (-39.4784162574990 * pow(sin((6.28318520000000 * v16)), 2)) + (-157.913665029996 * cos((6.28318520000000 * v16)))), (-1/2)) * pow(((-1 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2)) + (pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + pow(cos((6.28318520000000 * v16)), 2) + pow(cos((6.28318520000000 * v15)), 2)), (-1/2)) * (-12.5663704000000 + (6.28318520000000 * cos((6.28318520000000 * v16)))) * sin((6.28318520000000 * v16))), 1.0); }
                              //vec4 torus_normal(float v15, float v16) { return vec4((pow((197.392081287495 + (-39.4784162574990 * pow(sin((6.28318520000000 * v16)), 2)) + (-157.913665029996 * cos((6.28318520000000 * v16)))), (-1/2)) * pow(((-1 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2)) + (pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + pow(cos((6.28318520000000 * v16)), 2) + pow(cos((6.28318520000000 * v15)), 2)), (-1/2)) * (12.5663704000000 + (-6.28318520000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v15)) * cos((6.28318520000000 * v16))), (pow((197.392081287495 + (-39.4784162574990 * pow(sin((6.28318520000000 * v16)), 2)) + (-157.913665029996 * cos((6.28318520000000 * v16)))), (-1/2)) * pow(((-1 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2)) + (pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + pow(cos((6.28318520000000 * v16)), 2) + pow(cos((6.28318520000000 * v15)), 2)), (-1/2)) * (12.5663704000000 + (-6.28318520000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v16)) * sin((6.28318520000000 * v15))), (pow((197.392081287495 + (-39.4784162574990 * pow(sin((6.28318520000000 * v16)), 2)) + (-157.913665029996 * cos((6.28318520000000 * v16)))), (-1/2)) * pow(((-1 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2)) + (pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + pow(cos((6.28318520000000 * v16)), 2) + pow(cos((6.28318520000000 * v15)), 2)), (-1/2)) * (-12.5663704000000 + (6.28318520000000 * cos((6.28318520000000 * v16)))) * sin((6.28318520000000 * v16))), 1.0); }
                              vec4 torus_normal(float v15, float v16) { return vec4((-1.00000000000000 * pow(pow((-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))), 2), (-1/2)) * (-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v15)) * cos((6.28318520000000 * v16))), (-1.00000000000000 * pow(pow((-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))), 2), (-1/2)) * (-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v16)) * sin((6.28318520000000 * v15))), (1.00000000000000 * pow(pow((-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))), 2), (-1/2)) * (-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))) * sin((6.28318520000000 * v16))), 1.0); }
                              float tf(float f) { return 0.5*sin(4*pi*f) + 0.5; }
                              out vec4 outputColor; void main() {
/*
                                outputColor = gl_FrontFacing ?
                                  vec4(tf(uv.x), tf(uv.y), 0, 1) :
                                  vec4(1, 1 - tf(uv.x), 1 - tf(uv.y), 1);
*/
                                outputColor = vec4(0.8, 0.8, 0.8, 1);
                                vec4 n = normalize( torus_normal(uv.x, uv.y) );
                                float lambert = max( dot(vec4(0.7, 0, 0.7, 0), n), 0);
                                outputColor *= (lambert + 0.2);
                              }'''),
            VertexShader('''#version 130
                            uniform float pi = 3.14159;
                            /* layout(location = 0) */ in vec2 param;
                            varying vec2 uv;
                            vec4 torus(float v25, float v26) { return vec4(((2.00000000000000 * cos((6.28318520000000 * v25))) + (-1.00000000000000 * cos((6.28318520000000 * v25)) * cos((6.28318520000000 * v26)))), ((2.00000000000000 * sin((6.28318520000000 * v25))) + (-1.00000000000000 * cos((6.28318520000000 * v26)) * sin((6.28318520000000 * v25)))), (1.00000000000000 * sin((6.28318520000000 * v26))), 1.0); }
                            //vec4 knot(float v15, float v16) { return vec4(((-1.00000000000000 * cos((18.8495556000000 * v15)) * cos((12.5663704000000 * v15))) + (2.00000000000000 * cos((12.5663704000000 * v15)))), ((2.00000000000000 * sin((12.5663704000000 * v15))) + (-1.00000000000000 * cos((18.8495556000000 * v15)) * sin((12.5663704000000 * v15)))), (1.00000000000000 * sin((18.8495556000000 * v15))), 1.0); }
                            void main() {
                                vec4 p = torus(param.x, param.y);
                                //vec4 p = knot(param.x, param.y);
                                //vec4 p = vec4(param.x, param.y, 0, 1);
                                uv = param.xy;
                                gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * p;
                            }''')
        )
示例#48
0
# This is for VS code only.
import vsEnvironSetup
vsEnvironSetup.setVariables()

import Grid

# The number of passes to go through the grid
passCount = 1
Grid.runGrid(passCount, filename='lists/binaries3.dat')
示例#49
0
def finalize():

   Grid.finalize()
   Hydro.finalize()
示例#50
0
class Knot_Display(pyglet.window.Window):

    def __init__(self, **kwargs):
        super(Knot_Display, self).__init__(**kwargs)
        self.t = 0.0
        self.orientation = Quat(1, Vec3(0,0,0))
        self.zoom = 1.0

        self.grid = Grid(100, 100)


        self.program = ShaderProgram(
            FragmentShader('''#version 130
                              uniform float pi = 3.14159;
                              varying vec2 uv;
                              //vec4 torus_normal(float v15, float v16) { return vec4((-6.28318520000000 * pow(pow((-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))), 2), (-1/2)) * pow(((39.4784162574990 * pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + (39.4784162574990 * pow(cos((6.28318520000000 * v15)), 2)) + (39.4784162574990 * pow(cos((6.28318520000000 * v16)), 2)) + (-39.4784162574990 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2))), (-1/2)) * (-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v15)) * cos((6.28318520000000 * v16))), (-6.28318520000000 * pow(pow((-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))), 2), (-1/2)) * pow(((39.4784162574990 * pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + (39.4784162574990 * pow(cos((6.28318520000000 * v15)), 2)) + (39.4784162574990 * pow(cos((6.28318520000000 * v16)), 2)) + (-39.4784162574990 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2))), (-1/2)) * (-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v16)) * sin((6.28318520000000 * v15))), (pow((197.392081287495 + (-39.4784162574990 * pow(sin((6.28318520000000 * v16)), 2)) + (-157.913665029996 * cos((6.28318520000000 * v16)))), (-1/2)) * pow(((-1 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2)) + (pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + pow(cos((6.28318520000000 * v16)), 2) + pow(cos((6.28318520000000 * v15)), 2)), (-1/2)) * (-12.5663704000000 + (6.28318520000000 * cos((6.28318520000000 * v16)))) * sin((6.28318520000000 * v16))), 1.0); }
                              //vec4 torus_normal(float v15, float v16) { return vec4((pow((197.392081287495 + (-39.4784162574990 * pow(sin((6.28318520000000 * v16)), 2)) + (-157.913665029996 * cos((6.28318520000000 * v16)))), (-1/2)) * pow(((-1 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2)) + (pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + pow(cos((6.28318520000000 * v16)), 2) + pow(cos((6.28318520000000 * v15)), 2)), (-1/2)) * (12.5663704000000 + (-6.28318520000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v15)) * cos((6.28318520000000 * v16))), (pow((197.392081287495 + (-39.4784162574990 * pow(sin((6.28318520000000 * v16)), 2)) + (-157.913665029996 * cos((6.28318520000000 * v16)))), (-1/2)) * pow(((-1 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2)) + (pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + pow(cos((6.28318520000000 * v16)), 2) + pow(cos((6.28318520000000 * v15)), 2)), (-1/2)) * (12.5663704000000 + (-6.28318520000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v16)) * sin((6.28318520000000 * v15))), (pow((197.392081287495 + (-39.4784162574990 * pow(sin((6.28318520000000 * v16)), 2)) + (-157.913665029996 * cos((6.28318520000000 * v16)))), (-1/2)) * pow(((-1 * pow(cos((6.28318520000000 * v15)), 2) * pow(cos((6.28318520000000 * v16)), 2)) + (pow(sin((6.28318520000000 * v15)), 2) * pow(sin((6.28318520000000 * v16)), 2)) + pow(cos((6.28318520000000 * v16)), 2) + pow(cos((6.28318520000000 * v15)), 2)), (-1/2)) * (-12.5663704000000 + (6.28318520000000 * cos((6.28318520000000 * v16)))) * sin((6.28318520000000 * v16))), 1.0); }
                              vec4 torus_normal(float v15, float v16) { return vec4((-1.00000000000000 * pow(pow((-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))), 2), (-1/2)) * (-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v15)) * cos((6.28318520000000 * v16))), (-1.00000000000000 * pow(pow((-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))), 2), (-1/2)) * (-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))) * cos((6.28318520000000 * v16)) * sin((6.28318520000000 * v15))), (1.00000000000000 * pow(pow((-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))), 2), (-1/2)) * (-2.00000000000000 + (1.00000000000000 * cos((6.28318520000000 * v16)))) * sin((6.28318520000000 * v16))), 1.0); }
                              float tf(float f) { return 0.5*sin(4*pi*f) + 0.5; }
                              out vec4 outputColor; void main() {
/*
                                outputColor = gl_FrontFacing ?
                                  vec4(tf(uv.x), tf(uv.y), 0, 1) :
                                  vec4(1, 1 - tf(uv.x), 1 - tf(uv.y), 1);
*/
                                outputColor = vec4(0.8, 0.8, 0.8, 1);
                                vec4 n = normalize( torus_normal(uv.x, uv.y) );
                                float lambert = max( dot(vec4(0.7, 0, 0.7, 0), n), 0);
                                outputColor *= (lambert + 0.2);
                              }'''),
            VertexShader('''#version 130
                            uniform float pi = 3.14159;
                            /* layout(location = 0) */ in vec2 param;
                            varying vec2 uv;
                            vec4 torus(float v25, float v26) { return vec4(((2.00000000000000 * cos((6.28318520000000 * v25))) + (-1.00000000000000 * cos((6.28318520000000 * v25)) * cos((6.28318520000000 * v26)))), ((2.00000000000000 * sin((6.28318520000000 * v25))) + (-1.00000000000000 * cos((6.28318520000000 * v26)) * sin((6.28318520000000 * v25)))), (1.00000000000000 * sin((6.28318520000000 * v26))), 1.0); }
                            //vec4 knot(float v15, float v16) { return vec4(((-1.00000000000000 * cos((18.8495556000000 * v15)) * cos((12.5663704000000 * v15))) + (2.00000000000000 * cos((12.5663704000000 * v15)))), ((2.00000000000000 * sin((12.5663704000000 * v15))) + (-1.00000000000000 * cos((18.8495556000000 * v15)) * sin((12.5663704000000 * v15)))), (1.00000000000000 * sin((18.8495556000000 * v15))), 1.0); }
                            void main() {
                                vec4 p = torus(param.x, param.y);
                                //vec4 p = knot(param.x, param.y);
                                //vec4 p = vec4(param.x, param.y, 0, 1);
                                uv = param.xy;
                                gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * p;
                            }''')
        )

    def update(self, dt):
        self.t += dt

    def on_resize(self, width, height):
        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(50, width / float(height), .01, 100)
        glMatrixMode(GL_MODELVIEW)

        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
        return pyglet.event.EVENT_HANDLED

    def on_mouse_press(self, x, y, button, modifiers):
        # self.set_exclusive_mouse()
        return

    def on_mouse_release(self, x, y, button, modifiers):
        # self.set_exclusive_mouse(exclusive=False)
        return

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        # rotate on left-drag
        if buttons & 1:
            # the rotation vector is the displacement vector rotated by 90 degrees
            v = Vec3(dy, -dx, 0).scale(0.002)
            # update the current orientation
            self.orientation = self.orientation * v.rotation()
        # zoom on right-drag
        if buttons & 4:
            self.zoom += self.zoom * dy*0.01

    def on_draw(self):
        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
        self.clear()
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glTranslatef(0, 0, -7.0)
        glScalef(self.zoom, self.zoom, self.zoom)

        r = self.orientation.conj().matrix()
        # column-major order
        m = [r.X.x, r.X.y, r.X.z, 0,
             r.Y.x, r.Y.y, r.Y.z, 0,
             r.Z.x, r.Z.y, r.Z.z, 0,
                 0,     0,     0, 1,]
        array = (GLfloat * len(m))()
        for index, value in enumerate(m):
            array[index] = value
        glMultMatrixf(array);

        glPointSize(1.8)
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
        with self.program:
            self.grid.draw_triangles()
        glPopMatrix()
示例#51
0
文件: Tetris.py 项目: qdot/bartris
class Tetris():

    NORMAL_MODE = 0
    BOOZE_MODE = 1
    DESIGNATED_DRIVER_MODE = 2
    SINGLE_DRINK_MODE = 3

    def __init__(self):
        self._event_handlers = []
        self._setup_states()
        self._state["game_over"] = True
        self._setup_display()
        self._joystick = None
        if pygame.joystick.get_count() > 0:
            print "FOUND A JOYSTICK!"
            self._joystick = pygame.joystick.Joystick(0)
            self._joystick.init()
            
    def _setup_states(self, mode = 0):
        self._params = {
            "fullscreen"             : False,
            "fullscreen_width"       : 1024,
            "fullscreen_height"      : 768,
            "num_cells_wide"         : 10,
            "num_cells_high"         : 20,
            "cell_width"             : 25,
            "cell_height"            : 25,
            "drink_pouring_time"     : 10.0,
            "starting_cell_x"        : 4,
            "starting_cell_y"        : 1,
            "grid_top_x"             : 0,
            "grid_top_y"             : 0,
            "modes"                  : ["(N)ormal Mode", "(B)ooze Mode", "(S)ingle Drink Mode", "(D)esignated Driver Mode", "(Q)uit"]
            }

        self._level_params = {
            "moving_rate"            : [0.00005,.00004,0.00003,0.00002,0.00001],
            "rotating_rate"          : [0.00009,0.00008,0.00007,0.00006,0.00005],
            "falling_rate"           : [0.00050,0.00035,0.00020,0.00010,0.00005]
            }

        self._state = {
            "last_falling_time"      : 0,
            "falling_rate"           : self._level_params["falling_rate"][0],
            "last_moving_time"       : 0,
            "last_rotating_time"     : 0,
            "level_up_line_count"    : 5,
            "last_num_lines_cleared" : 0,
            "top_y"                  : 0,
            "times_found"            : 0,
            "current_level"          : 1,
            "game_over"              : False,
            "all_finished"           : False,
            "current_y"              : 0,
            "holding_down"           : False
            }


        if mode in [self.NORMAL_MODE, self.SINGLE_DRINK_MODE]:
            self._color_dict     = {1: COLORS["blue"], 6 : COLORS["brown"], 10: COLORS["darkGrey"]}        
        elif mode == self.BOOZE_MODE:
            self._color_dict     = {3 : COLORS["brown"], 10: COLORS["darkGrey"]}
        elif mode == self.DESIGNATED_DRIVER_MODE:
            self._color_dict     = {10: COLORS["blue"]}

        if mode == self.SINGLE_DRINK_MODE or mode == self.BOOZE_MODE:
            self._level_params = {
                "moving_rate"            : [0.00005],
                "rotating_rate"          : [0.00009],
                "falling_rate"           : [0.00040]
                }
            self._params["drink_pouring_time"] = 20.0

        self._color_range    = 10

        self._textBuff       = 2
        self._grid           = Grid( 1, 1, self._params["cell_width"], self._params["cell_height"], self._params["num_cells_wide"], self._params["num_cells_high"], COLORS["black"], self._params["fullscreen"], self._params["fullscreen_width"], self._params["fullscreen_height"])
        if self._params["fullscreen"]:
            self._params["grid_top_x"] = (self._params["fullscreen_width"] / 2) - (self._grid.width / 2)
            self._params["grid_top_y"] = (self._params["fullscreen_height"] / 2) - (self._grid.height / 2)

        self._tetrominoList  = ['T','I','O','S','Z','L','J']
        self._sound          = Sound()

        self._new_tetromino()

    def _setup_display(self):
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        pygame.init()
        if self._params["fullscreen"]:
            self._screen = pygame.display.set_mode((1024, 768), pygame.FULLSCREEN, 24)
        else:
            self._screen = pygame.display.set_mode((self._grid.width+self._textBuff,self._grid.height+self._textBuff),0,32)
        if pygame.font:
            self._font = pygame.font.Font(None, 18)

    def init_game(self):
        pygame.display.set_caption("Python Tetris")

    def run_game(self):
        time.sleep(0.01)
        if self._state["game_over"]:
            self._menu_state()
        else:
            self._game_loop()
        self._render()
        return

    def _menu_state(self):
        current_key = ''
        for event in pygame.event.get():
            if event.type == QUIT:
                raise QuitException()
            if event.type == pygame.KEYDOWN:
                current_key = event.key
        if current_key == K_q:
            raise QuitException()
        elif current_key == K_n:
            self._setup_states(self.NORMAL_MODE)
        elif current_key == K_b:
            self._setup_states(self.BOOZE_MODE)
        elif current_key == K_d:
            self._setup_states(self.DESIGNATED_DRIVER_MODE)
        elif current_key == K_s:
            self._setup_states(self.SINGLE_DRINK_MODE)

    def _game_loop(self):

        # Grab vars
        if self._tetromino.active:
            self._move_tetromino()
        else: #New Tetromino
            osc.sendMsg("/tetris/piece_down", [0], "localhost", 9001)
            self._new_tetromino()
        #Levels and Speedup
        if self._grid.num_lines_cleared >= (self._state["level_up_line_count"] * self._state["current_level"]) and self._state["last_num_lines_cleared"] != self._grid.num_lines_cleared:
            self._level_up()

    def _move_tetromino(self):

        current_key = ''
        up_key = ''
        for event in pygame.event.get():
            legal_moves   = {
                "down"  : self._tetromino.max_y < self._grid.height,
                "left"  : self._tetromino.min_x > 0 and self._grid.accept(self._tetromino.id,self._tetromino.positions[self._tetromino.currentPosition],-1,0),
                "right" : self._tetromino.max_x < self._grid.width and self._grid.accept(self._tetromino.id,self._tetromino.positions[self._tetromino.currentPosition],1,0),
                }



            if event.type == QUIT:
                break

            if event.type == pygame.JOYAXISMOTION:
                a = event.axis
                p = event.value
                #turn joystick into key simulations
                if a == 0:
                    if p < -0.01:
                        current_key = K_LEFT
                    elif p > 0.01:
                        current_key = K_RIGHT
                else:
                    if p > 0.01:
                        current_key = K_DOWN
                    elif p < 0.01 and p > -0.01:
                        up_key = K_DOWN
            if event.type == pygame.JOYBUTTONDOWN:
                if event.button == 1:
                    current_key = K_z
                else:
                    current_key = K_x
            if event.type == pygame.KEYDOWN:
                current_key = event.key
            elif event.type == pygame.KEYUP:
                up_key = event.key

            if current_key == K_RIGHT and legal_moves["right"]:
                self._tetromino.move(self._grid,1,0)
            if current_key == K_LEFT and legal_moves["left"]:
                self._tetromino.move(self._grid,-1,0)
            if current_key == K_DOWN:
                self._state["holding_down"] = True
                osc.sendMsg("/mario/speed", [40], "localhost", 9001)
            elif up_key == K_DOWN:
                osc.sendMsg("/mario/speed", [0], "localhost", 9001)
                self._state["holding_down"] = False
            #TODO: Fix rotation states
            if current_key == K_z and False not in legal_moves.values():
                self._tetromino.rotate(self._grid, -1)
            if current_key == K_x and False not in legal_moves.values():
                self._tetromino.rotate(self._grid, 1)
            #ADDED: quit current_key
            if current_key == K_q:
                raise QuitException()

        legal_moves   = {
            "down"  : self._tetromino.max_y < self._grid.height,
            "left"  : self._tetromino.min_x > 0 and self._grid.accept(self._tetromino.id,self._tetromino.positions[self._tetromino.currentPosition],-1,0),
            "right" : self._tetromino.max_x < self._grid.width and self._grid.accept(self._tetromino.id,self._tetromino.positions[self._tetromino.currentPosition],1,0),
            }

        current_time  = time.time()/1000.0
        falling_time  = current_time - self._state["last_falling_time"]

        #Downward fall
        if self._state["holding_down"] is True and legal_moves["down"]:
            self._tetromino.move(self._grid,0,1)
            self._state["current_y"] += 1
        elif falling_time >= self._state["falling_rate"] and legal_moves["down"]:
            self._state["last_falling_time"] = current_time
            self._tetromino.move(self._grid,0,1)
            self._state["current_y"] += 1
        elif not legal_moves["down"] and falling_time >= self._state["falling_rate"]:
            self._tetromino.cluck.play()
            self._tetromino.active = False

    def _new_tetromino(self):
        #ADDED: Set tetromino color to one of our three allowed colors
        color_index = random.randint(0,self._color_range)
        color = ()
        for color_probability in sorted(self._color_dict.keys()):
            if color_index <= color_probability:
                color = self._color_dict[color_probability]
                break

        rand          = random.randint(0,len(self._tetrominoList)-1)
        self._tetromino = Tetromino(self._params["starting_cell_x"], self._params["starting_cell_y"], COLORS["black"],color,self._tetrominoList[rand])
        self._state["holding_down"] = False
        if self._grid.checkForLines():
            for e in self._event_handlers:
                e.on_line_created(self)

        #Test for GAME OVER
        top_y = self._grid.topY()
        if top_y <= 2:
            self._state["times_found"] += 1
        if self._state["times_found"] > 3:
            self._state["game_over"] = True

    def _level_up(self):
        self._state["last_num_lines_cleared"] = self._grid.num_lines_cleared
        self._state["current_level"] += 1
        if self._state["current_level"] < len(self._level_params["falling_rate"]):
            self._state["falling_rate"] = self._level_params["falling_rate"][self._state["current_level"]]
        else:
            self._state["all_finished"] = True
            self._state["game_over"] = True
        self._sound.play("../sound/levelup.wav")
        for e in self._event_handlers:
            e.on_level_up(self)

    def _render(self):
        #render Background
        pygame.draw.rect(self._screen,(255,255,255),Rect(self._params["grid_top_x"], self._params["grid_top_y"],self._grid.width+2,self._grid.height+2))
        #Render Grid
        self._grid.render(self._screen)
        self._render_status()
        pygame.display.update()

    def _render_status(self):
        if not self._state["game_over"]:
            lineText       = "Lines: " + str(self._grid.num_lines_cleared) + "  Level: " + str(self._state["current_level"])
            lines_text     = self._font.render(lineText, 1, COLORS["white"])
            lines_text_pos = Rect((self._params["grid_top_x"]+1, self._params["grid_top_y"]+1),(self._params["grid_top_x"] + 300, self._params["grid_top_y"] + 20))
            self._screen.blit(lines_text, lines_text_pos)
        else:
            game_over_text     = self._font.render("GAME OVER... LEVEL: "+str( self._state["current_level"])+" LINES: " + str(self._grid.num_lines_cleared),1, COLORS["red"])
            if self._state["all_finished"]:
                game_over_text     = self._font.render("ALL LEVELS FINISHED! LEVEL: "+str( self._state["current_level"])+" LINES: " + str(self._grid.num_lines_cleared),1, COLORS["red"])
            game_over_text_pos = Rect((self._params["grid_top_x"]+1, self._params["grid_top_y"]+1),(self._params["grid_top_x"] + 300, self._params["grid_top_y"] + 20))
            self._screen.blit(game_over_text,game_over_text_pos)
            for i in range(0, len(self._params["modes"])):
                pLineText       = self._params["modes"][i]
                p_lines_text     = self._font.render(pLineText, 1, COLORS["white"])
                p_lines_text_pos = Rect((1+self._params["grid_top_x"],100+(i*25)+self._params["grid_top_y"]),(300,250))
                self._screen.blit(p_lines_text, p_lines_text_pos)


    def add_event_handler(self, eh):
        self._event_handlers.append(eh)
示例#52
0
文件: Tetris.py 项目: qdot/bartris
    def _setup_states(self, mode = 0):
        self._params = {
            "fullscreen"             : False,
            "fullscreen_width"       : 1024,
            "fullscreen_height"      : 768,
            "num_cells_wide"         : 10,
            "num_cells_high"         : 20,
            "cell_width"             : 25,
            "cell_height"            : 25,
            "drink_pouring_time"     : 10.0,
            "starting_cell_x"        : 4,
            "starting_cell_y"        : 1,
            "grid_top_x"             : 0,
            "grid_top_y"             : 0,
            "modes"                  : ["(N)ormal Mode", "(B)ooze Mode", "(S)ingle Drink Mode", "(D)esignated Driver Mode", "(Q)uit"]
            }

        self._level_params = {
            "moving_rate"            : [0.00005,.00004,0.00003,0.00002,0.00001],
            "rotating_rate"          : [0.00009,0.00008,0.00007,0.00006,0.00005],
            "falling_rate"           : [0.00050,0.00035,0.00020,0.00010,0.00005]
            }

        self._state = {
            "last_falling_time"      : 0,
            "falling_rate"           : self._level_params["falling_rate"][0],
            "last_moving_time"       : 0,
            "last_rotating_time"     : 0,
            "level_up_line_count"    : 5,
            "last_num_lines_cleared" : 0,
            "top_y"                  : 0,
            "times_found"            : 0,
            "current_level"          : 1,
            "game_over"              : False,
            "all_finished"           : False,
            "current_y"              : 0,
            "holding_down"           : False
            }


        if mode in [self.NORMAL_MODE, self.SINGLE_DRINK_MODE]:
            self._color_dict     = {1: COLORS["blue"], 6 : COLORS["brown"], 10: COLORS["darkGrey"]}        
        elif mode == self.BOOZE_MODE:
            self._color_dict     = {3 : COLORS["brown"], 10: COLORS["darkGrey"]}
        elif mode == self.DESIGNATED_DRIVER_MODE:
            self._color_dict     = {10: COLORS["blue"]}

        if mode == self.SINGLE_DRINK_MODE or mode == self.BOOZE_MODE:
            self._level_params = {
                "moving_rate"            : [0.00005],
                "rotating_rate"          : [0.00009],
                "falling_rate"           : [0.00040]
                }
            self._params["drink_pouring_time"] = 20.0

        self._color_range    = 10

        self._textBuff       = 2
        self._grid           = Grid( 1, 1, self._params["cell_width"], self._params["cell_height"], self._params["num_cells_wide"], self._params["num_cells_high"], COLORS["black"], self._params["fullscreen"], self._params["fullscreen_width"], self._params["fullscreen_height"])
        if self._params["fullscreen"]:
            self._params["grid_top_x"] = (self._params["fullscreen_width"] / 2) - (self._grid.width / 2)
            self._params["grid_top_y"] = (self._params["fullscreen_height"] / 2) - (self._grid.height / 2)

        self._tetrominoList  = ['T','I','O','S','Z','L','J']
        self._sound          = Sound()

        self._new_tetromino()
示例#53
0
class GridSimulation(object):
  
  "inititialize the world"
  def __init__(self):
    self.grid = Grid(gridWidth, gridHeight)
    for i in range(numBots):
      self.age = 0.0
      bot = Bot()
      x = random.randint(0, gridWidth-1)
      y = random.randint(0, gridWidth-1)
      self.grid.getNode(x, y).add(bot)
      self.createCode()
      self.stepCount = 0
  
  def createCode(self):
    #self.code = nprandom.random_integers(0, 1, codeSize)
    self.code = zeros(codeSize)
    for i in range(codeSize):
      self.code[i] = random.randint(0, 1)
    self.refreshAge = self.age + random.expovariate(codeRefreshRate)
    
  "run the simulation"
  def elapseTime(self, time):
    goalAge = self.age + time
    while (self.age < goalAge):
      
      "report"
      if (self.stepCount <= 0):
        self.stepCount += stepsPerReport
        numBots = self.grid.numBots()
        numCorrect = self.grid.numCorrect()
        print 'Time:', self.age, 'Number of Bots:', numBots, 'Code:', self.code, \
        'Percent correct:', float(numCorrect)/numBots
      self.stepCount -= 1
      
      self.age += timeStepSize
      if (self.age > self.refreshAge):
        self.createCode()
      
      "run the bots"
      for x in range(self.grid.width):
        for y in range(self.grid.height):
          node = self.grid.getNode(x, y)
          for bot in node.bots:
            "push their outputs to the node"
            node.data += bot.outputs.dataOut
          for bot in node.bots.copy():
            "listen to accumulated outputs"
            bot.inputs.dataIn = node.data
            node.clearData()
            
            "determine move"
            left = bot.outputs.left > random.random()
            right = bot.outputs.right > random.random()
            up = bot.outputs.up > random.random()
            down = bot.outputs.down > random.random()
            if (left and right):
              left = False
              right = False
            if (up and down):
              up = False
              down = False
            
            "determine new coordinates"
            newx = x
            newy = y
            if (left):
              newx -= 1
            if (right):
              newx += 1
            if (up):
              newy += 1
            if (down):
              newy -= 1
            
            node2 = node
            "make move"
            if ((x, y) != (newx, newy)):
              node.remove(bot)
              node2 = self.grid.getNode(newx, newy)
              node2.add(bot)
            
            "reproduce"
            if (bot.spawnTime <= 0.0):
              node2.add(bot.spawn())
            
            "elapse bot time and remove dead bots"
            guess = bot.outputs.code
            guess = maximum(guess, 0)
            guess = minimum(guess, 1)
            correct = reduce(lambda x, y : x * y, abs(guess - self.code)) < random.random()
            #bot.inputs.correct = 1 if correct else 0
            #debug
            bot.inputs.correct = self.code[0]
            print correct
            
            alive = bot.elapseTime(timeStepSize)
            if (not alive):
              node2.remove(bot)
      
      "kill extra bots"
      bots = []
      for x in range(self.grid.width):
        for y in range(self.grid.height):
          node = self.grid.getNode(x, y)
          bots.extend(node.bots)
      random.shuffle(bots)
      for i in range(maxBots, len(bots)):
        bots[i].node.remove(bots[i])
示例#54
0
    def __init__(self, width, height, blocked, food):
        """
        Initializes a worldMap with the specified
        width and height

        The percentage of tiles specified by blocked are set at
        random to be non-traversable

        The percentage of tiles specified by food are
        seeded at random with food in an amount between 1-5 units

        The anthill location is set at random

        width: an integer > 0
        height: an integer > 0
        blocked: a float 0.8 > float > 0.0
        food: a float 0.8 > float > 0.0

        Mapping of hash table values
        Open (i.e. traversable): 100
        Blocked: 101
        Home: 102
        Food: 1-5
         
        """
               
        self._width = width
        self._height = height

        self._dirs = dict([("NORTH",(-1,0)),("EAST",(0,1)),("SOUTH",(1,0)),("WEST",(0,-1))])


        ## create the map of the world             
        ## create an empty 2-dimensional array
        self._grid = Grid(height, width)

        ## populate the 2-dimensional array with open tiles
        for row in range(height):
            for col in range(width):
                self._grid.setAt(row, col, tile())
                
        ## set randomly selected tiles to be blocked
        assert blocked >= 0.0
        assert blocked <= 0.8
        for i in range(int(width*height*blocked)):
            val = random.choice(range(width*height))
            self._grid.getAt(val/width, val%width).setIsTravelable(False)

        ## set randomly selected tiles to be seeded with food
        assert food >= 0.0
        assert blocked <= 0.8
        for i in range(int(width*height*food)):
            val = random.choice(range(width*height))
            ## check that tile isn't blocked before seeding with food
            if self._grid.getAt(val/width, val%width).isTravelable():
                self._grid.getAt(val/width, val%width).setNumFood(random.choice(range(1,6)))

        ## set the anthill location
        while(True): 
            home = random.choice(range(width*height))
            ## check that tile isn't blocked before setting to be home
            currTile = self._grid.getAt(home/width, home%width)
            if currTile.isTravelable() and currTile.getAmountOfFood() == 0:
                self._grid.getAt(home/width, home%width).setIsHome(True)
                break;

        ## create a map of the ants in the world
        ## create an empty 2-dimensional array populated with empty lists
        self._antGrid = [[[] for col in xrange(width)] for row in xrange(height)]
示例#55
0
class worldMap:
    """
    A worldMap represents a world

    A worldMap has a width and a height and contains (width*height) tiles
    """

    def __init__(self, width, height, blocked, food):
        """
        Initializes a worldMap with the specified
        width and height

        The percentage of tiles specified by blocked are set at
        random to be non-traversable

        The percentage of tiles specified by food are
        seeded at random with food in an amount between 1-5 units

        The anthill location is set at random

        width: an integer > 0
        height: an integer > 0
        blocked: a float 0.8 > float > 0.0
        food: a float 0.8 > float > 0.0

        Mapping of hash table values
        Open (i.e. traversable): 100
        Blocked: 101
        Home: 102
        Food: 1-5
         
        """
               
        self._width = width
        self._height = height

        self._dirs = dict([("NORTH",(-1,0)),("EAST",(0,1)),("SOUTH",(1,0)),("WEST",(0,-1))])


        ## create the map of the world             
        ## create an empty 2-dimensional array
        self._grid = Grid(height, width)

        ## populate the 2-dimensional array with open tiles
        for row in range(height):
            for col in range(width):
                self._grid.setAt(row, col, tile())
                
        ## set randomly selected tiles to be blocked
        assert blocked >= 0.0
        assert blocked <= 0.8
        for i in range(int(width*height*blocked)):
            val = random.choice(range(width*height))
            self._grid.getAt(val/width, val%width).setIsTravelable(False)

        ## set randomly selected tiles to be seeded with food
        assert food >= 0.0
        assert blocked <= 0.8
        for i in range(int(width*height*food)):
            val = random.choice(range(width*height))
            ## check that tile isn't blocked before seeding with food
            if self._grid.getAt(val/width, val%width).isTravelable():
                self._grid.getAt(val/width, val%width).setNumFood(random.choice(range(1,6)))

        ## set the anthill location
        while(True): 
            home = random.choice(range(width*height))
            ## check that tile isn't blocked before setting to be home
            currTile = self._grid.getAt(home/width, home%width)
            if currTile.isTravelable() and currTile.getAmountOfFood() == 0:
                self._grid.getAt(home/width, home%width).setIsHome(True)
                break;

        ## create a map of the ants in the world
        ## create an empty 2-dimensional array populated with empty lists
        self._antGrid = [[[] for col in xrange(width)] for row in xrange(height)]
      
    def getWorldWidth(self):
        return self._width

    def getWorldHeight(self):
        return self._height

    def getTile(self, row, col):
        """
        return the tile at the specified position
        """
        return self._grid.getAt(row, col)

    def getSurroundings(self, row, col):
        """
        return a hash table of the Surroundings of the position
        specified by the (row, col) position
        """

        output = {}
        output["Current"] = self._grid.getAt(row, col)

        ## iterate through each possible direction (NORTH, EAST, SOUTH, WEST)
        for direction, move in self._dirs.items():
            newRow = row + move[0]
            newCol = col + move[1]
            ## validate that the new position is in the world
            if newRow >= 0 and newRow < self._height and newCol >= 0 and newCol < self._width:     
                output[direction] = self._grid.getAt(newRow, newCol)
            ## dragons be here: off the map, set to blocked tile with 0 food, 0 ant
            else:                           
                output[direction] = tile(0,0,False)

        return output
示例#56
0
#!/bin/python

from Grid import *
from Thing import *
import time, sys

g = Grid(6, 9)
g.addWall180([2,3], EAST)
g.addWall180([4,3], EAST)
g.addWall180([4,2], EAST)
g.addWall180([3,1], SOUTH)
g.addWall180([0,3], SOUTH)
g.addWall180([1,2], SOUTH)
g.addWall180([1,2], WEST) 

a = Alice()
m = Mirror()
c = Chess()
f = Feather()

a.spawn(g, (5,0))
m.spawn(g, (1,4))
# m.spawn(g, (2,5))
#c.spawn(g, (0,5))
f.spawn(g, (0,8))

print g.positionOf(a)

try:
  tick = float(sys.argv[1])
except:
示例#57
0
class Ant:
    """
    Represents an ant.

    The ant has an internal map and maps its position relative to
    the starting point
    """

    def __init__(self,inputPrintActions):
        """
        Ants are initialized with a 20x20 internal map. All tiles (except the
        starting tile) on the internal map are initially set to -100 which
        represents unexplored tiles. 

        The starting position of the ant is assumed to be (row, col)
        (9,9), the center of the internal map.

        Ants are initialized with zero food.

        Ants are intialzied with no route plan.

        The internal representation for ants is as follows:
        -100: unknown tile
        -101: travelable tile
        -102: untravelable tile
        -103: home tile
        0-127: food
        """

        self._foodKnown = False
        self._hasFood = False
        self._newFoodFound = False
        self._gridLen = 20
        self._receiveMap = False
        self._routePlan = []
        self._routePlanType = "UNKNOWN" 
        self._memo = {}
        self._row = 9
        self._col = 9
        self._homeRow = 9
        self._homeCol = 9
        self._foodLoc = (0,0)
        self._unexploredLoc = (0,0)
        self._foodLocSet = set()
        self._unexploredLocSet = set()
        self._exhaustedFoodLocSet = set()
        self._dirs = dict([("NORTH",(-1,0)),("EAST",(0,1)),("SOUTH",(1,0)),("WEST",(0,-1))])
        self._nReceives = 0
        self._printActions = inputPrintActions
        
        ## create a 2-dimensional grid to represent the world
        ## for the ant
        self._internalMap = Grid(self._gridLen, self._gridLen, -100) 

        self._internalMap.setAt(self._homeRow, self._homeCol, -103)    ##103 represents the home tile

    def getAntHasFood(self):
        return self._hasFood    

    def setAntHasFood(self, hasFood):
        """
        set the boolean value for whether the ant has food
        """
        self._hasFood = hasFood

    def antGather(self):
        """
        represents and ant collecting food
        """
        ## validate that the ant has no food
        assert self._hasFood == False
        self._hasFood = True

    def antDropoff(self):
        """
        represents and ant dropping off food
        """
        ## validate that the ant has food
        assert self._hasFood == True
        self._hasFood = False

    def setAntReceiveMap(self, mapFromOtherAnt):
        self._receiveMap = mapFromOtherAnt

    def getAntReceiveMap(self):
        return self._receiveMap

    def getPrintActions(self):
        return self._printActions

    def checkMap(self):
        """
        iterates through known food locations and know unexplored locations 
        to find the nearest tile of the respective type(food/unexplored).
        Stores the nearest location for use with A*.
        """
        self._foodLoc = (float("inf"),0)
        self._unexploredLoc = (float("inf"),0)
        for (row, col) in self._foodLocSet:
            ## A* hueristic: for each food location, calculate the distance form
            ## the current location 
            foodDistance = math.sqrt((self._row - row)**2 + (self._col - col)**2)
            if foodDistance < self._foodLoc[0]:
                self._foodLoc = (foodDistance,(row,col))

        for (row, col) in self._unexploredLocSet: 
            assert self._internalMap.getAt(row, col) == -100
            ## A* hueristic: for each unexplored location, calculate the distance form
            ## the current location
            unexploredDistance = math.sqrt((self._row - row)**2 + (self._col - col)**2)
            if unexploredDistance < self._unexploredLoc[0]:
                 self._unexploredLoc = (unexploredDistance,(row,col))

    def finalCheckMap(self):
        """
        iterates through the internal map to determine if there
        are any unexplored locations
        """
        for row in xrange(self._gridLen):
            for col in xrange(self._gridLen):
                if self._internalMap.getAt(row, col) == -101:
                    self.addUnexploredLocs(row,col)
                

    def updateMapPos(self, action):
        """
        updateMapPos takes a string value representing a movement.
        updateMapOs updates the relative location of the ant on the
        internal map
        """
        self._row = self._row + (self._dirs[action])[0]
        self._col = self._col + (self._dirs[action])[1]
        ## if the new position is within 5 tiles of the boundry of the ant's internal map
        ## then we increase the size of the internal map
        if self._row <= 5 or self._row > self._gridLen - 5 or self._col <= 5 or self._col > self._gridLen - 5:
            self.resize()

    def resizeInstanceVariables(self, rowDelta, colDelta):
        """
        resizeInstanceVaribles adjusts the instance variables
        so the instance variables stay consistent with the resized map
        """
        self._row += rowDelta
        self._col += colDelta
        self._homeRow += rowDelta
        self._homeCol += colDelta
        
        ## update the lists of food, unexplored, and exhausted
        self._foodLocSet = set(map(lambda x: (x[0] + rowDelta, x[1] + colDelta), self._foodLocSet))
        self._unexploredLocSet = set(map(lambda x: (x[0] + rowDelta, x[1] + colDelta), self._unexploredLocSet))
        self._exhaustedFoodLocSet = set(map(lambda x: (x[0] + rowDelta, x[1] + colDelta), self._exhaustedFoodLocSet))

    def resize(self):
        """
        resizes the ants internal map by adding 10 rows / 10 cols.
        """

        oldLength = self._gridLen
        self._gridLen += 20
        ## increase the ant's internal map. New tiles are set to -100 to represent unexplored
        self._internalMap.resize(10,10,-100)

        ## update the ant's position in the internal map
        self.resizeInstanceVariables(10,10)

            
    def shortest_path_search(self, startPos, fSuccessors, fIsGoal, goalObjective):
        """returns a list of the shortest path to a goal state.
        startPosition is a (row position,col position) tuple (i.e. coordinates) that
        specifies the starting location. SPS takes the staring state, the
        function successors, the function is_goal, and the variable goalType"""

        if fIsGoal([startPos], goalObjective):
            return [startPos]

        fail = []

        ## memoize paths to home and to food
        ## don't memoize paths to unexplored tiles as the unexplored tiles change 
        ## check to see if we've memoized the shortest path
        if (startPos, goalObjective) in self._memo:
            ## if the goal is to get home, we can use the memoized path   
            if goalObjective == "HOME": 
                return self._memo[(startPos, goalObjective)]
            ## if the goal is to find food, we need to confirm that
            ## we still believe there is food at the location
            elif goalObjective == "FOOD":
                ## pull the end position off the path and unpack the tuple
                endRow, endCol = (self._memo[(startPos, goalObjective)])[-1]
                ## if we believe there is still food at the end point
                ## we can take the memoized path
                if (endRow,endCol) in self._foodLocSet:
                    return self._memo[(startPos, goalObjective)]
                ## if there's no food left, delete the path
                else:
                    del self._memo[(startPos, goalObjective)]
                    
        
        ## algorithm for shortest_path_search
        explored = set([])
        frontier = Queue.PriorityQueue()
        frontier.put([1, [startPos]])

        while(frontier):
            ## path with lowest cost gValue is expanded first
            path = frontier.get()
            ## calculate the number of steps in the path to this point len(path[1])/2.
            numSteps, state = len(path[1])/2., (path[1])[-1]
            for (action,state) in fSuccessors(state).items():
                ## if our path intersects a known path for returning to the
                ## home tile, stop SPS and take the known path
                if goalObjective == "HOME" and (state, "HOME") in self._memo:
                    path2 = path[1] + [action] + self._memo[(state, "HOME")]
                    return path2 
                
                ## state is a tuple of row,col offsets
                if state not in explored:
                    explored.add(state)
                    ## path is in the form [(0,0),"NORTH",(-1,0),"WEST",(-1,-1),"NORTH",(-2,-1)]   
                    path2 = path[1] + [action, state]

                    ## calculations for A*: Calculate the euclidean distance from the
                    ## expansion location to the goal location. The distance will be used
                    ## to guide which location is expanded in subsequent steps 
                    rowOffset, colOffset = state
                    newRow = self._homeRow + rowOffset
                    newCol = self._homeCol + colOffset
                    if goalObjective == "HOME":
                        aStarDist = math.sqrt((rowOffset)**2 + (colOffset)**2)
                    elif goalObjective == "FOOD":
                        foodRow, foodCol = self._foodLoc[1]
                        aStarDist = math.sqrt((foodRow - newRow)**2 + (foodCol - newCol)**2)
                    else:
                        assert goalObjective == "UNKNOWN"
                        unexploredRow, unexploredCol = self._unexploredLoc[1]
                        aStarDist = math.sqrt((unexploredRow - newRow)**2 + (unexploredCol - newCol)**2)
                    ## the gValue is the number of steps  in the path so far plus the euclidean
                    ## distance to the goal 
                    gValPath = [numSteps + aStarDist, path2] 
                    if fIsGoal(path2, goalObjective):
                        ## only memoize food paths starting at the home tile. Note 1
                        if goalObjective == "HOME" or (goalObjective == "FOOD" and startPos == (self._homeRow, self._homeCol)): 
                            self._memo[(startPos, goalObjective)] = path2
                        return path2
                    else:
                        frontier.put(gValPath)
        return fail

    def fSuccessors(self, state):
        """returns a hash table of all possible sucessor states to the starting state
        key:value pairs consist of the action:new state. State is a row offset,col offset
        tuple (i.e. coordinates).""" 

        ## unpack the state tuple (row, col)
        ## this is the end state of the path we are checking
        rowOffset, colOffset = state 
        
        output = {}

        ## iterate through each direction:state pair in the hash table 
        for (direction,move) in self._dirs.items():
            ## update the row,col position by the move that corresponds to the direction
            newRowOffset = rowOffset + move[0]
            newColOffset = colOffset + move[1]
            newRow = self._homeRow + newRowOffset
            newCol = self._homeCol + newColOffset
            ## if the new row,col position isn't blocked
            ## and the new row,col position isn't unexplored
            ## add position to the hash table of possible successor states
            if (self._internalMap.getAt(newRow, newCol) != -100 and self._internalMap.getAt(newRow, newCol) != -102):
                output[direction] = (newRowOffset,newColOffset)
        return output

    ## helper function for shortest_path_search
    def fIsGoal(self, path, goalType):
        """returns a boolean whether the state represents a goal state
        there are 3 potential goals: home , food , and unknown
        """
    
        ## unpack the coordinate tuple
        rowOffset, colOffset = path[-1]
        row = self._homeRow + rowOffset
        col = self._homeCol + colOffset
        ## check if the path ends at the home tile
        if goalType == "HOME":
            return self._internalMap.getAt(row, col) == -103
        ## check if the path ends at food
        elif goalType == "FOOD":
            return (row, col) == self._foodLoc[1] 
        ## check if we're on a tile that can sense() an unexplored tile
        else:
            ## if not 1 or 2, goalType must be 0
            assert goalType == "UNKNOWN"
            output = False
            for move in self._dirs.values():
                newRow = row + move[0]
                newCol = col + move[1]
                if self._internalMap.getAt(newRow, newCol) == -100:
                    output = True
            return output


    def getAction(self,Surroundings):
        """
        returns a string value representing the ant's next action.
        Possible actions: GATHER, DROPOFF, HALT, NORTH, SOUTH, EAST, WEST
        """
        ## extract the current tile from Surroundings
        currTile = Surroundings.getCurrentTile()

        ## if there are other ants on the current tile, receive data from the other ants
        if len(currTile.getAnts()) > 0:
            for ant in currTile.getAnts():
                ## ants only communicate with other ants every 5th turn to reduce computational expense
                if ant != self and self._nReceives%2 == 0: 
                    self.receive(ant.send())

        ## sense the Surroundings
        self.sense(Surroundings)

        ## ant waits at home until it receives a map from a mature ant
        if not self.getAntReceiveMap():
            return "HALT"

        ## if the ant has a route plan, follow the plan
        if len(self._routePlan) > 0:
            action = self._routePlan.pop(0)
            self.updateMapPos(action)
            if self.getPrintActions():
                print action  
            return action
        
        ## if the ant has food and the ant is on the
        ## ant mound, drop off the food, DROPOFF
        ## the program decrements the ants food
        if self.getAntHasFood() and self._internalMap.getAt(self._row, self._col) == -103:
            if self.getPrintActions():
                print 'DROPOFF'  
            return "DROPOFF"
    
        ## if the ant doesn't have food and the current tile does have food
        ## set a path for home, then GATHER
        if currTile.getAmountOfFood() > 0 and not self.getAntHasFood() and self._internalMap.getAt(self._row, self._col) != -103:
            rowOffset = self._row - self._homeRow
            colOffset = self._col - self._homeCol
            path = self.shortest_path_search((rowOffset, colOffset), self.fSuccessors, self.fIsGoal, "HOME")
            self._routePlan = path[1::2]
            self._routePlanType = "HOME" 
            ## If there is only one unit of food delete the location as a food location
            if currTile.getAmountOfFood() == 1:
                self._foodLocSet.remove((self._row,self._col))                     
                self._exhaustedFoodLocSet.add((self._row, self._col))
                ## there's no longer food at the location so we no longer need the path
                if self._memo.has_key(((self._homeRow,self._homeCol), "FOOD")): 
                    del self._memo[((self._homeRow, self._homeCol), "FOOD")] 
            if self.getPrintActions():
                print "GATHER"  
            return "GATHER"

        ## if the ant is aware of a food location plot the shortest path to food
        if len(self._foodLocSet) > 0:
            assert not self.getAntHasFood()
            rowOffset = self._row - self._homeRow
            colOffset = self._col - self._homeCol
            path = self.shortest_path_search((rowOffset,colOffset),self.fSuccessors, self.fIsGoal, "FOOD")
            self._routePlan = path[1::2]
            self._routePlanType = "FOOD"
            ## update internal location and
            ## return the next action in the route plan
            action = self._routePlan.pop(0)
            self.updateMapPos(action)
            if self.getPrintActions():
                print action 
            return action
                    

        ## otherwise, the location of food is not known and the
        ## ant does not have a route, so plot a path to the
        ## nearest unexplored tile
        if len(self._foodLocSet) == 0 and len(self._unexploredLocSet) > 0:
            rowOffset = self._row - self._homeRow
            colOffset = self._col - self._homeCol
            path = self.shortest_path_search((rowOffset, colOffset),self.fSuccessors, self.fIsGoal, "UNKNOWN")
            self._routePlan = path[1::2]
            self._routePlanType = "UNKNOWN" 
            action = self._routePlan.pop(0)
            self.updateMapPos(action)
            if self.getPrintActions():
                print action  
            return action
        
        ## Otherwise we're done. No unexplored tiles
        else:
            if self.getPrintActions():
                print "HALT"
            self.finalCheckMap(); 
            return "HALT"
            
    def receive(self, externalData):
        """
        accepts an antMap from another ant and updates the ants
        internal map with the new information
        """
        self._nReceives += 1
        
        ## set the self.receiveMap field to true
        self.setAntReceiveMap(True)

        ## convert the 1-dimensional array to a 2-dimensional map
        extUnexploredLocSet, extFoodLocSet, extExhaustedFoodLocSet, extMap = self.reformGrid(externalData)
               
        ## maps are square. Extract the length of the sides   
        N = extMap.getRows()
        ## calculate the difference between the side of the internal map
        ## and the received map
        difference = N - self._gridLen
        halfDif = abs(difference/2)

        ## Size of internal map == size of external map
        ## update the internal map for the case where the size of the
        ## external map is the same as the size of the internal map
        ## Unexplored tiles on the internal map are updated where the
        ## tiles are known on the external map
    
        if difference == 0:
            for row in range(self._gridLen):
                for col in range(self._gridLen):
                    if self._internalMap.getAt(row, col) == -100 and extMap.getAt(row, col) != -100:
                        self._internalMap.setAt(row, col, extMap.getAt(row, col))
                        ## if the position was in the unexplored set, remove as it is no longer unexplored
                        self._unexploredLocSet.discard((row,col))

            self.sychronizeData(extUnexploredLocSet, extFoodLocSet, extExhaustedFoodLocSet)
                         
        ## Size of external map > size of internal map
        ## update for the case where the size of the
        ## external map greater than the size of the internal map
        ## Unexplored tiles on the internal map are updated where the
        ## tiles are known on the external map. After the update,
        ## the external map replaces the internal map

        elif difference > 0:
                      
            ## Copy information from internal map into external Grid
            for row in range(halfDif, halfDif + self._gridLen):
                for col in range(halfDif, halfDif + self._gridLen):
                    ## for explored tiles on the internal map, overwrite the external map
                    if not self._internalMap.getAt(row - halfDif, col - halfDif) == -100:
                        extMap.setAt(row, col, self._internalMap.getAt(row - halfDif, col - halfDif))
                                                
            ## overwite internal map with external map
            self._internalMap = extMap
            self._gridLen = N
            self.resizeInstanceVariables(halfDif, halfDif)
            self.sychronizeData(extUnexploredLocSet, extFoodLocSet, extExhaustedFoodLocSet)
            
        ## Size of internal map > size of external map
        ## update for the case where the size of the
        ## internal map is greater than the size of the external map
        ## Unexplored tiles on the internal map are updated where the
        ## tiles are known on the external map. 

        else:
            for row in range(halfDif, halfDif + N):
                for col in range(halfDif, halfDif + N):
                    if self._internalMap.getAt(row, col) == -100 and extMap.getAt(row - halfDif, col - halfDif) != -100:
                        self._internalMap.setAt(row, col, extMap.getAt(row - halfDif, col - halfDif))    
                     
            extUnexploredLocSet = set(map(lambda x: (x[0] + halfDif, x[1] + halfDif), extUnexploredLocSet))
            extFoodLocSet = set(map(lambda x: (x[0] + halfDif, x[1] + halfDif), extFoodLocSet))
            extExhaustedFoodLocSet = set(map(lambda x: (x[0] + halfDif, x[1] + halfDif), extExhaustedFoodLocSet))
            self.sychronizeData(extUnexploredLocSet, extFoodLocSet, extExhaustedFoodLocSet)
            

    def checkRoute(self, location):
        """
            checkRoute is needed to check and clear the current route plan.
            checkRoute is called when data is received from other ant
            that indicates that the closest food location is exhausted
        """
        if location == self._foodLoc[1]:
            rowOffset, colOffset = self._routePlan[-1]
            endRow = self._homeRow + rowOffset
            endCol = self._homeCol + colOffset
            if (endRow, endCol) == location:
                self._routePlan = []

    def sychronizeData(self,extUnexploredLocSet, extFoodLocSet, extExhaustedFoodLocSet):
        """
            sychronize data integrates the date from an external ant
        """
        
        self._exhaustedFoodLocSet.union(extExhaustedFoodLocSet)
        self._foodLocSet.union(extFoodLocSet)
        self._unexploredLocSet.union(extUnexploredLocSet)
        ## filter out locations that have already been explored 
        self._unexploredLocSet = set(filter(lambda x: self._internalMap.getAt(x[0], x[1]) == -100,self._unexploredLocSet))
        ## filter out food locations that are known to be exhausted
        self._foodLocSet = set(filter(lambda x: x not in self._exhaustedFoodLocSet, self._foodLocSet))
        ## delete the current routePlan if the new data shows food has been exhausted at the current route plan destination
        if self._foodLoc[1] in extExhaustedFoodLocSet and self._routePlanType == "FOOD":
            self._routePlan = [] 

                            
    def reformGrid(self, arr):
        """
        Ants transmit the following data structure
        Integer specifying the length of foodLocSet
        Integer specifying the length of the unexploredLocSet
        
        A 1-dimensional array and the length of the rows
        and returns a 2-dimensional array.

        Assumes that there are an equal number of rows and cols
        """

        offset1, offset2, offset3, offset4 = arr[0], arr[1], arr[2], arr[3] 
       
        
        externalUnexploredLocSet = arr[offset1:offset2]
        externalFoodLocSet = arr[offset2:offset3]
        externalExhaustedFoodLoc = arr[offset3:offset4] 
        externalMap = arr[offset4:] 

        ## internal maps are square. the square root of the array
        ## gives us the length of the rows
        N = int(math.sqrt(len(externalMap)))
        
        output = Grid(N,N)

        for row in xrange(N):
            for col in xrange(N):
                output.setAt(row, col, externalMap[row*N + col])

        return (externalUnexploredLocSet, externalFoodLocSet, externalExhaustedFoodLoc, output) 

    def send(self):
        """
        pack the key data into a 1-dimensional array for transmital to another ant. 
		The key data is the unexplored locations, food locations, and exhausted food 
		locations. We use the first found elements of the array to indicate the size 
		of the unexplored, food, and exhausted so the receiving ant can unpack the data
        """

        unexploredLen = len(self._unexploredLocSet)
        foodLen = len(self._foodLocSet)
        exhaustedFoodLen = len(self._exhaustedFoodLocSet)
        offset1 = 4
        offset2 = offset1 + unexploredLen
        offset3 = offset2 + foodLen
        offset4 = offset3 + exhaustedFoodLen

        output = [offset1, offset2, offset3, offset4]
        
        return output + \
               list(self._unexploredLocSet) +  \
               list(self._foodLocSet) + \
               list(self._exhaustedFoodLocSet) + \
               [self._internalMap.getAt(row,col) for row in xrange(self._gridLen) for col in xrange(self._gridLen)]

    def addUnexploredLocs(self, row, col):
        for move in self._dirs.values():
            newRow = row + move[0]
            newCol = col + move[1]
            if self._internalMap.getAt(newRow, newCol) == -100:
                self._unexploredLocSet.add((newRow, newCol))
            
            
       
    def sense(self, Surroundings):
        """
        sense takes a Surroundings object as input, examines the Surroundings,
        and updates the internal map
        """
        ## handle the corner case where the food on the current tile was taken since the last turn
        if self._internalMap.getAt(self._row, self._col) != -103 and Surroundings.getCurrentTile().getAmountOfFood() == 0 and \
        (self._row, self._col) in self._foodLocSet:
            self._exhaustedFoodLocSet.add((self._row, self._col))
            self._foodLocSet.remove((self._row, self._col))

        ## iterate through each possible direction
        for direction, move in self._dirs.items():
            sensedTile = Surroundings.getTile(direction)
            ## calculate the relative position for the sensed tile
            newRow = self._row + move[0]
            newCol = self._col + move[1]

            ## check for food, home tile always ignored 
            if self._internalMap.getAt(newRow, newCol) != -103 and sensedTile.getAmountOfFood() > 0:
                self._foodLocSet.add((newRow,newCol))
                ## note 2
                if self._routePlanType == "UNKNOWN":
                    self._routePlan = [] 

            ## unpdate map for travelable/untravelable, home tile always ignored 
            if self._internalMap.getAt(newRow, newCol) == -103:
                pass
            elif sensedTile.isTravelable():
                self._internalMap.setAt(newRow, newCol, -101)
                self._unexploredLocSet.discard((newRow,newCol))
            else:
                self._internalMap.setAt(newRow, newCol, -102)
                self._unexploredLocSet.discard((newRow,newCol))


        ##
        for move1 in self._dirs.values():
            newRow1 = self._row + move1[0]
            newCol1 = self._col + move1[1]
            if self._internalMap.getAt(newRow1, newCol1) == -101:
                self.addUnexploredLocs(newRow1, newCol1)

        ## after the ant finishes sensing, update whether food is known
        self.checkMap()
示例#58
0

count=1
speed=0
steer=0
timer=0
deltaL=0
deltaR=0
encoder=Encoder()
navigation=Navigation()
scanner=Scanner()
karte=Karte(encoder)
plan=Plan()
kreis=0
motor=Motor()
grid=Grid(50,50)
logic=Logic()
manuell=Manuell()
json=Json()
weggeber=Weggeber()

grid.setZielInGrid(35,20)
grid.setStartInGrid(1,1)
karte.setRoboPosZero(0,0)
plan.setGlobalZiel(150,0)

def cleaning():
    """Do cleanup at end, command are visVersa"""
    motor.setCommand(0,0)
atexit.register(cleaning)
示例#59
0
def train(model):
    epochs = 3000
    gamma = 0.975
    epsilon = 1
    batch_size = 50
    buffer = 100
    replay = []
    # stores tuples of (S, A, R, S')
    h = 0
    for i in range(epochs):
        state = Grid.initGridPlayer() # using the harder state initialization function
        status = 1
        # while game still in progress
        while status == 1:
            # We are in state S
            # Let's run our Q function on S to get Q values for all possible actions
            qval = model.predict(state.reshape(1, 64), batch_size=1)
            if random.random() < epsilon:  # choose random action
                action = np.random.randint(0, 4)
            else:  # choose best action from Q(s,a) values
                action = (np.argmax(qval))
            # Take action, observe new state S'
            new_state = Grid.makeMove(state, action)
            # Observe reward
            reward = Grid.getReward(new_state)

            # Experience replay storage
            if len(replay) < buffer:  # if buffer not filled, add to it
                replay.append((state, action, reward, new_state))
            else:  # if buffer full, overwrite old values
                if h < (buffer - 1):
                    h += 1
                else:
                    h = 0
                replay[h] = (state, action, reward, new_state)
                # randomly sample our experience replay memory
                minibatch = random.sample(replay, batch_size)
                x_train = []
                y_train = []
                for memory in minibatch:
                    # Get max_Q(S',a)
                    old_state, action, reward, new_state = memory
                    old_qval = model.predict(old_state.reshape(1, 64), batch_size=1)
                    newQ = model.predict(new_state.reshape(1, 64), batch_size=1)
                    maxQ = np.max(newQ)
                    y = np.zeros((1, 4))
                    y[:] = old_qval[:]
                    if reward == -1:  # non-terminal state
                        update = (reward + (gamma * maxQ))
                    else:  # terminal state
                        update = reward
                    y[0][action] = update
                    x_train.append(old_state.reshape(64, ))
                    y_train.append(y.reshape(4, ))

                x_train = np.array(x_train)
                y_train = np.array(y_train)
                print("Game #: %s" % (i,))
                model.fit(x_train, y_train, batch_size=batch_size, nb_epoch=1)
                state = new_state
            if reward != -1:  # if reached terminal state, update game status
                status = 0
            clear_output(wait=True)
        if epsilon > 0.1:  # decrement epsilon over time
            epsilon -= (1 / epochs)
示例#60
0
def init():
   """
   Handle the initialization for the Driver component.
   """

   global MAX_ITER
   global output_dt
   global time
   global tmax

   # ==========================================================================
   # Arguments and parameters

   # Read the command-line arguments
   cline_args = parse_command_line()

   # Read the parameter file
   cfile_args = parse_config_file(cline_args.config_file)

   # Add the command-line arguments as section 'CommandLine'
   # TODO --- test this
   cfile_args['CommandLine'] = vars(cline_args)

   # ==========================================================================
   # Initialize the Driver component

   if 'Driver' not in cfile_args:
      cfile_args['Driver'] = {}

   # Maximum number of iterations
   if 'max_iter' in cfile_args['Driver']:
      MAX_ITER = int(cfile_args['Driver']['max_iter'])
   else:
      MAX_ITER = 10
   # Store either the default value or the value from the config file converted
   # from string to integer
   cfile_args['Driver']['max_iter'] = MAX_ITER

   # Time step between outputs
   if 'output_dt' in cfile_args['Driver']:
      output_dt = float(cfile_args['Driver']['output_dt'])
   else:
      output_dt = 0.0
   cfile_args['Driver']['output_dt'] = output_dt

   # Current time
   time = 0.0

   # Final time
   if 'tmax' in cfile_args['Driver']:
      tmax = float(cfile_args['Driver']['tmax'])
   else:
      raise Exception("tmax required") #TODO

   # ==========================================================================
   # Initialize the other components
   # - Each initialization updates its own parameters dictionary (adding
   #   default values for anything not specified on the command line or in the
   #   configuration file) and returns the updated dictionary for logging.

   # Initialize the grid
   if "Grid" not in cfile_args:
      cfile_args['Grid'] = {}
   cfile_args['Grid'] = Grid.init(cfile_args['Grid'])

   # Initialize the hydro
   if "Hydro" not in cfile_args:
      cfile_args['Hydro'] = {}
   cfile_args['Hydro'] = Hydro.init(cfile_args['Hydro'])

   # ==========================================================================
   # Write parameters to log file

   if not os.path.exists("output"):
      os.makedirs("output")

   f = open("output/parameters.txt",'w')
   for section in cfile_args:
      f.write("[ " + section + " ]\n")
      for item in cfile_args[section]:
         f.write("   " + item + " : " + str(cfile_args[section][item]) + "\n")
   f.close()

   # ==========================================================================
   # Set up initial conditions
   IC.set_initial_conditions()

   return cfile_args