Beispiel #1
0
def MakeSuccessor(x, y, gX, gY):
    if (x < 0 or x >= MAX_X() or y < 0 or y >= MAX_Y()):
        return None
    ele = elevations[x][y]
    ter = Terrain.GetTerrainVal(pix[x, y])
    if ter == Terrain.OutOfBounds():
        return None
    s = State.State(ele, ter, x, y, gX, gY)
    return s
Beispiel #2
0
def make_neighbor(x, y):
    # validates out of bound indices
    if (x < 0 or x >= MAX_X() or y < 0 or y >= MAX_Y()):
        return None
    ter = Terrain.GetTerrainVal(pix[x, y])
    # filters out of bound neighbors
    if ter == Terrain.OutOfBounds():
        return None
    # must be a valid neighbor at this point
    return (x, y)
Beispiel #3
0
def winter_DLT(x, y, d=7):
    t_val = Terrain.GetTerrainVal(pix[x, y])
    if (t_val != Terrain.Water()):
        return
    if (d == 0):
        return
    pix[x, y] = (113, 237, 255, 255)
    for tup in pixel_neighbors((x, y)):
        i, j = tup
        winter_DLT(i, j, d - 1)
Beispiel #4
0
    def move(self):
        lastPos = [self.pos[0], self.pos[1]]
        self.attackCooldown -= (self.attackCooldown > 0)
        self.frame += self.frameRate

        if len(self.hitFrames
               ) > 0 and self.frame >= self.hitFrames[0] and not self.attacked:
            self.abilList[0].useCallback(self)
            del self.hitFrames[0]
            if len(self.hitFrames) <= 0:
                self.attacked = True

        if (self.frame >= len(self.animationFrames) - 1):
            self.setState(self.animationFrames[len(self.animationFrames) - 1])

        self.stunResidue = max(0, self.stunResidue - 0.001)

        speed = [self.knockback[0], self.knockback[1]]
        #if math.fabs(self.knockback[0]) == 0 and math.fabs(self.knockback[1]) == 0:
        if (self.currState is not "stunned"):
            speed[0] += self.speed[0]
            speed[1] += self.speed[1]

        if Terrain.canMoveThrough(PTRS["TERRAIN"].getAtPos(
            [self.pos[0] + speed[0], self.pos[1]])):
            self.pos[0] += speed[0]
        else:
            if speed[0] > 0:
                self.pos[0] = int(self.pos[0] / 20 + 1) * 20 - 0.001
            else:
                self.pos[0] = int(self.pos[0] / 20) * 20 + 0.001
        if Terrain.canMoveThrough(PTRS["TERRAIN"].getAtPos(
            [self.pos[0], self.pos[1] + speed[1]])):
            self.pos[1] += speed[1]
        else:
            if speed[1] > 0:
                self.pos[1] = int(self.pos[1] / 20 + 1) * 20 - 0.001
            else:
                self.pos[1] = int(self.pos[1] / 20) * 20 + 0.001

        for i in [0, 1]:
            self.knockback[i] *= 0.96
            if math.fabs(self.knockback[i]) <= 0.1:
                self.knockback[i] = 0
            if math.fabs(
                    self.knockback[i]) <= 1 and self.currState == "attack":
                self.knockback[i] = 0

        if self.currState == "walk" and lastPos[0] == self.pos[0] and lastPos[
                1] == self.pos[1]:
            self.setState("idle")
        elif self.currState == "idle" and (lastPos[0] != self.pos[0]
                                           or lastPos[1] != self.pos[1]):
            self.setState("walk")
Beispiel #5
0
 def __init__(self, start, end):
     global allControlPoints
     self.controls = assets.getAsset(
         'Road from {} to {}'.format(start, end), generateControls,
         (start, end), args.args.remake_roads)
     allControlPoints += self.controls
     setRoadUniforms()
     self.center = sum(self.controls) / len(self.controls)
     self.radius = max(
         [np.linalg.norm(i - self.center) for i in self.controls]) + 1000
     Terrain.registerCallback(self.renderHeightmap)
Beispiel #6
0
def plot_terrain(SynthPlot,**kwargs):

    terrain=kwargs['terrain']
    slope=kwargs['slope']
    terrain_file=kwargs['terrain_file']

    if terrain:
         Terrain.plot_altitude_map(SynthPlot,terrain_file)

    if slope:
         Terrain.plot_slope_map(SynthPlot)
Beispiel #7
0
 def drawMe(self, camera, atStart):
     pos = intOf([self.pos[0] - camera.Left(), self.pos[1] - camera.Top()])
     size = int(self.size)
     if self.selected == 1:
         pygame.draw.circle(camera.getSurface(), [255, 0, 0], pos, size, 3)
     elif self.selected == 2:
         pygame.draw.circle(camera.getSurface(), [0, 0, 255], pos, size, 3)
     drawCharPic(camera.getSurface(), self.picture, pos,
                 int(self.animationFrames[int(self.frame)]),
                 int(self.angleFacing * 180 / math.pi), self.team)
     if self.itemHeld != None:
         Terrain.drawItem(camera, [self.pos[0], self.pos[1] - self.size],
                          self.itemHeld)
Beispiel #8
0
def spring_DLT(x, y, base, d=15):
    t_val = Terrain.GetTerrainVal(pix[x, y])
    e_val = float(elevations[y][x])
    diff = e_val - base
    if (diff > 1):
        return
    if (d == 0):
        return
    pix[x, y] = (113, 237, 255, 255)
    for tup in pixel_neighbors((x, y)):
        i, j = tup
        t_val = Terrain.GetTerrainVal(pix[i, j])
        if (t_val != Terrain.Water() and t_val != Terrain.Ice()):
            spring_DLT(i, j, base, d - 1)
Beispiel #9
0
def BiomeGeneration(size, variance):
    terrain_array = Terrain.terrain_generation(size)
    precip_array = Terrain.terrain_generation(size)
    simulation_board = [[0 for x in range(size)] for y in range(size)]
    n = [[0 for x in range(size)] for y in range(size)]
    for lat in range(size):
        for lon in range(size):
            simulation_board[lat][lon] = Square(terrain_array[lat][lon],
                                                variance, lat, lon, size,
                                                precip_array[lat][lon])
            ex = simulation_board[lat][lon]
            n[lat][lon] = ex.precipitation

    return simulation_board
Beispiel #10
0
    def plot_vertical_momentum_flux(self,data,xdata,terrain):

        met=data[['wdir','wspd','wvert','lats','lons']]
        # topo=np.asarray(Terrain.get_topo(lats=met['lats'], lons=met['lons']))
        topo2=np.asarray(Terrain.get_topo2(lats=met['lats'], lons=met['lons'],terrain=terrain))

        u_comp,v_comp = get_wind_components(met.wspd,met.wdir)
        w_comp=met.wvert

        u_moflux = pd.rolling_cov(u_comp, w_comp, 60, center=True)
        v_moflux = pd.rolling_cov(v_comp, w_comp, 60, center=True)

        fig, ax = plt.subplots(2,1, sharex=True)
        l1=ax[0].plot(xdata,u_moflux,label='U-moment')
        l2=ax[0].plot(xdata,v_moflux,label='V-moment')
        ax[0].set_ylim([-1.0,1.0])
        ax[0].set_ylabel('Vertical momentum flux [ m2 s-2]',color='b',fontsize=15)
        # plt.legend(handles=[l1,l2])
        ax[0].legend()

        spl=UnivariateSpline(xdata[::5],topo2[::5],k=5)
        xsmooth=np.linspace(0.,xdata[-1],int(len(xdata)))
        ysmooth=spl(xsmooth)
        ysmooth[ysmooth<0]=0
        ax[1].plot(xsmooth, ysmooth,color='black')
        ax[1].set_xlabel('Distance from flight start [km]',fontsize=15)

        plt.draw()
    def load(self, level):
        """Loads in level based on ASCII values"""
        count_x = 0
        count_y = 0
        if level == 1:
            ascii_map = self.level_one_key
        elif level == 2:
            ascii_map = self.level_two_key
        elif level == 3:
            ascii_map = self.level_three_key

        for i in ascii_map:
            if i == '/':
                self.terrain_objects.append(Terrain(count_x, count_y))
            elif i == 'S':
                pass
            elif i == 'X':
                self.enemy_manager.spawn(count_x, count_y)
            elif i == 'G':
                # self.objects.append(Gun(count_x, count_y, self.surface)
                pass
            count_x += SIZE_BLOCK
            if count_x == SIZE_SCREEN_X:
                count_x = 0
                count_y += SIZE_BLOCK
            if count_y == SIZE_SCREEN_Y:
                break
Beispiel #12
0
def read(input_file):
    input_data = InputData()
    with open(input_file, "r") as in_file:
        header = in_file.readline().strip().split()
        input_data.map_m = int(header[1])
        input_data.map_n = int(header[0])
        input_data.num_customers = int(header[2])
        input_data.num_max_offices = int(header[3])

        input_data.customers_list = list()
        for i in range(0, input_data.num_customers):
            line = in_file.readline().strip().split()
            customer = Node(i, int(line[0]), int(line[1]), int(line[2]))
            input_data.customers_list.append(customer)

        input_data.map = [[0 for x in range(input_data.map_n)] for y in range(input_data.map_m)]
        for i in range(input_data.map_m):
            line = in_file.readline().strip()
            j = 0
            for char in line:
                input_data.map[i][j] = Terrain.get_cost(char)
                j += 1

        for node in input_data.customers_list:
            input_data.map[node.y][node.x] = -1

    return input_data
 def new(self):
     # initialize all variables and do all the setup for a new game
     self.all_sprites = pg.sprite.Group()
     self.walls = pg.sprite.Group()
     self.terrain = pg.sprite.Group()
     self.logicMaze = np.zeros((20, 20), int)
     for row, tiles in enumerate(self.map_data):
         for col, tile in enumerate(tiles):
             if tile == '.':
                 self.setTerrain(col, row)
             if tile == '1':
                 if (col < 20 and row < 20):
                     self.logicMaze[row][col] = 1
                 Wall(self, col, row)
             if tile == 'P':
                 Terrain(self, col, row, 1)
                 for i in range(self.genSize):
                     newPlayer = Player(self, col, row, i)
                     self.generation.append(newPlayer)
                     if i == 1:
                         self.best = newPlayer
             if tile == 'F':
                 print('Finish Line')
     for i in range(self.genSize):
         self.generation[i].configure(self.logicMaze)
Beispiel #14
0
 def generate_grid(self, surf):
     """
     Generates a new grid with randomized terrain covering the map.
     :param surf: surface images are displayed to
     :return: stored data
     """
     row_len = 0
     for row in range(self.width // self.block_size):
         col_len = 0
         self.grid.append([])
         for col in range(self.height // self.block_size):
             grass_or_clover = random.randint(0, 5)
             spot = [
                 [row_len, col_len, self.block_size, self.block_size],
                 Creature.Creature(""),
                 Terrain.Terrain(""),
             ]
             spot[1] = Empty.Empty()
             if grass_or_clover > 1:
                 spot[2] = Grass.Grass()
             else:
                 spot[2] = Clover.Clover()
             spot[2].set_color("alive")
             spot.append(
                 pygame.draw.rect(surf, spot[2].get_color(), spot[0]))
             self.grid[row].append(spot)
             col_len += self.block_size
         row_len += self.block_size
     return self.grid
Beispiel #15
0
def main():
	size = (70, 70)
	food = (3,3)
	colony = (size[0]-4, 3)
	initPatrol = 5
	step = 1


	terrain = Terrain.Terrain(size, colony, food)
	root = tk.Tk()
	board = Board.Board(root, terrain)
	board.pack(side="top", fill="both", expand="true", padx=4, pady=4)
	terrain.setNewPatrolCount(initPatrol)

	for i in range(50):
		terrain.makeObstacle((35, 0+i))

	while 1:
		for i in range(1, step + 1):
			time.sleep(0.01)

			if i == step:
				terrain.iterate()

			board.update()
			root.update_idletasks()
			root.update()
Beispiel #16
0
 def update(self):
     while np.linalg.norm(self.destination - self.position) < 4:
         self.destination = random.choice(
             [i.position for i in self.destination_town.buildings])
     self.position += (self.destination -
                       self.position) / np.linalg.norm(self.destination -
                                                       self.position) * 0.1
     self.position[1] = Terrain.getAt(self.position[0], self.position[2])
Beispiel #17
0
    def __init__(self):
        super().__init__(width=960, height=640, fovx=80, downSample=1)

        self.changeTitle("AXI OpenCL 3D Visualizer")

        self.α = 3.1
        self.β = -0.1

        self.pos = numpy.array([600.8, 20.4, 600.3])
        self.camSpeed = 0.04

        self.mouseSensitivity = 20

        self.ambLight = 0.08

        self.st = 0
        self.tt = 200
        self.drawAxes = False
        self.b = None

        self.chunksize = 50
        self.chunkscale = 0.8
        self.renderDist = 2
        self.rdextra = 0
        self.numWorkers = 4

        S = self.chunksize
        L = self.chunkscale

        self.cchunk = [
            int(self.pos[0] / (S * L) + 0.5),
            int(self.pos[2] / (S * L) + 0.5)
        ]

        terr = Terrain.RandTerrain(1)

        self.rmax = 50000

        self.terr = terr

        self.tp = [mp.Queue(16) for i in range(self.numWorkers)]
        self.rp = [mp.Queue(16) for i in range(self.numWorkers)]
        self.workLen = [0 for i in range(self.numWorkers)]

        self.vischunks = [None for i in range((self.renderDist * 2)**2)]
        self.reqChunks = []
        self.procChunks = []

        for u in range(self.cchunk[0] - self.renderDist,
                       self.cchunk[0] + self.renderDist):
            for v in range(self.cchunk[1] - self.renderDist,
                           self.cchunk[1] + self.renderDist):
                self.reqChunks.append((u, v))

        for i in range(len(self.reqChunks)):
            a = self.reqChunks[0]
            del self.reqChunks[0]
            self.requestChunk(a, i)
Beispiel #18
0
 def behavior(self):
     self.parent.destroy()
     maze = m.Maze(window,
                   self.width,
                   self.height,
                   t.Terrain(10, 20, p.Player(), [], barriers=True),
                   path="random")
     maze.terrain.spawnEnemy()
     maze.display(next="expand")
     self.startScreen.rebuild()
Beispiel #19
0
def do_fall():
    print("do fall was called")
    newColor = (128, 128, 128, 255)
    oldColor = (255, 255, 255, 255)
    print(Terrain.GetTerrainVal((255, 255, 255, 255)))
    s = time.time()
    for x in range(MAX_X()):
        for y in range(MAX_Y()):
            if (pix[x, y] == oldColor):
                for tup in pixel_neighbors((x, y)):
                    i, j = tup
                    t_val = Terrain.GetTerrainVal(pix[i, j])
                    if pix[i, j] != pix[x, y] and t_val != Terrain.Water(
                    ) and t_val != Terrain.ImpassibleVeg(
                    ) and t_val != Terrain.RoughMeadow():
                        pix[i, j] = newColor
                pix[x, y] = newColor
    e = time.time()
    print(e - s)
Beispiel #20
0
    def drawHUD(self, camera, atStart):
        if self.controlled or self.selected == 1:
            for i in range(self.maxHealth):
                xWiggle = 1
                yWiggle = 2
                pos = [xWiggle + 2 + 10 * i, yWiggle + 2]
                icon = 7
                if self.health <= i:
                    icon = 8
                    xWiggle = 0
                    yWiggle = 0

                pos[0] += int(
                    math.cos((PTRS["FRAME"] + i * 11 % 23) * math.pi / 10.0) *
                    xWiggle)
                pos[1] += int(
                    math.sin((PTRS["FRAME"] + i * 11 % 23) * math.pi / 40.0) *
                    yWiggle)
                Terrain.drawItem(camera, pos, icon, True)
Beispiel #21
0
def main():
    global pix
    global elevations
    img = Image.open('elevations_pixels.PNG')
    pix = img.load()
    with open('elevations.txt') as f:
        elevations = [line.split() for line in f]
    img.show()
    #do_fall()
    #do_winter()
    #do_spring()
    #img.show()
    #return

    print("done")
    print(len(elevations))
    points = []
    if (len(sys.argv) > 2):
        print("argument was passed!")
        with open(sys.argv[1]) as f:
            points = [tuple([int(i) for i in line.split()]) for line in f]
        season = int(sys.argv[2])
        change_season(season)
        paths = []
        stime = time.time()
        for i in range(len(points) - 1):
            start = points[i]
            end = points[i + 1]
            init = State.State(elevations[start[0]][start[1]],
                               Terrain.GetTerrainVal(pix[start[0], start[1]]),
                               start[0], start[1], end[0], end[1])
            paths.append(A_star(init))
        etime = time.time()
        counter = 1
        for path in paths:
            path.reverse()
            hr_output(path, counter)
            counter += 1
            for s in path:
                pix[s.x, s.y] = (255, 0, 0, 255)
        print(etime - stime)
        img.show()
        img.close()
        #print(points)
    # no file parameter passed, defaults to using points for brown path
    else:
        print("Usage: python3 orienteering.py file [season mode bit]")
        print("\tSEASON MODE BITS")
        print("\t0 -> summmer")
        print("\t1 -> fall")
        print("\t2 -> winter")
        print("\t3 -> spring")
        points = [(230, 327), (276, 279), (303, 240), (306, 286), (290, 310),
                  (304, 331), (306, 341), (253, 372), (246, 355), (288, 338),
                  (282, 321), (243, 327), (230, 327)]
Beispiel #22
0
    def update(self, camera_position, camera_direction):
        lo = 0
        hi = 1e2
        for _ in xrange(8):
            mi = (lo + hi) / 2.
            test = camera_position + camera_direction * mi
            if Terrain.getAt(test[0], test[2]) > test[1]:
                hi = mi
            else:
                lo = mi

        self.position = camera_position + camera_direction * lo
def main():
    global pix
    global elevations
    print('hello')
    img = Image.open('elevations_pixels.PNG')
    pix = img.load()
    print(pix)
    print(pix[0, 0])
    print(pix[228, 308])
    print(pix[230, 327])
    #pix[168,236] = (255,0,0,255)
    #pix[178,222] = (255,0,0,255)
    #pix[0,0] = (0,0,0,255)
    #img.show()
    x = img.size[0]
    y = img.size[1]
    print(x)
    print(y)
    with open('elevations.txt') as f:
        elevations = [line.split() for line in f]
    print("done")
    print(len(elevations))
    if (len(sys.argv) > 1):
        print("argument was passed!")
        return
    points = [(230, 327), (276, 279), (303, 240), (306, 286), (290, 310),
              (304, 331), (306, 341), (253, 372), (246, 355), (288, 338),
              (282, 321), (243, 327), (230, 327)]
    paths = []
    """
	#init = State.State(elevations[168][236], Terrain.GetTerrainVal(pix[168,236]), 168, 236, 178, 222)
	init = State.State(elevations[230][327], Terrain.GetTerrainVal(pix[230,327]), 230, 327, 276, 279)
	start = time.time()
	paths.append(A_star(init))
	end = time.time()
	print(end-start)
	"""
    stime = time.time()
    for i in range(len(points) - 1):
        start = points[i]
        end = points[i + 1]
        init = State.State(elevations[start[0]][start[1]],
                           Terrain.GetTerrainVal(pix[start[0], start[1]]),
                           start[0], start[1], end[0], end[1])
        paths.append(A_star(init))
    etime = time.time()
    for path in paths:
        for s in path:
            pix[s.x, s.y] = (255, 0, 0, 255)
    print(etime - stime)
    img.show()
    img.close()
Beispiel #24
0
def getTerrain(rp, tp):
    doQuit = False
    terr = Terrain.RandTerrain(1)
    while not doQuit:
        try:
            a = rp.get(True, 0.2)
        except:
            continue
        if a is None:
            doQuit = True
            break
        else:
            ga = terr.getArea(*a[3:])
            tp.put((*a[:3], ga))
Beispiel #25
0
def update(t):
    character.update(t)
    character.last_unanimated_position[1] = Terrain.getAt(
        character.position[0], character.position[2])
    character.update(t)
    for i in xrange(numberNPCs):
        npcs[i].update()

    for i in xrange(numberNPCs):
        npcs_object.instances['model'][i] = np.eye(4)
        npcs_object.instances['model'][i][:3][:3] *= npcs_object.scale
        transforms.translate(npcs_object.instances["model"][i],
                             *npcs[i].position)
    npcs_object.refreeze()
Beispiel #26
0
 def __init__(self, main, size, gravity=Vector2.Vector2()):
     size = (main.screen.get_width(), main.screen.get_height())
     self.terrain = Terrain.Terrain(main.resources, size, self)
     self.phyEng = PhysEng.PhysEng()
     self.objects = []
     self.toRemove = []
     self.gravity = gravity
     self.main = main
     self.reset = False
     self.load = False
     self.objs = []
     self.map_file = []
     self.name = "world"
     self.music = []
     self.size = size
Beispiel #27
0
    def plot_vertical_heat_flux(self,data,xdata):

        met=data[['theta','wvert','lats','lons']]
        topo=np.asarray(Terrain.get_topo(lats=met['lats'], lons=met['lons']))
        
        v_heatflux = pd.rolling_cov(met.wvert, met.theta, 60, center=True)

        plt.figure()
        plt.plot(xdata,v_heatflux)
        ax=plt.gca()
        ax.set_ylim([-0.5,0.5])
        ax.set_ylabel('Vertical heat flux [K m s-1]',color='b',fontsize=15)
        ax.set_xlabel('Distance from flight start [km]',fontsize=15)
        add_second_y_in(ax,topo,xaxis=xdata, color='r',label='Topography [m]')
        plt.draw()
Beispiel #28
0
 def canSeeUnit(self, unit):
     if dist(unit.getPos(), self.getPos()) <= self.getListenRange() or \
      (dist(unit.getPos(), self.getPos()) <= self.getSightRange() and self.unitInSightArc(unit)):
         for square in raytrace([
                 int(self.getPos()[0] / TILESIZE[0]),
                 int(self.getPos()[1] / TILESIZE[1])
         ], [
                 int(unit.getPos()[0] / TILESIZE[0]),
                 int(unit.getPos()[1] / TILESIZE[1])
         ]):
             if not Terrain.canSeeThrough(PTRS["TERRAIN"].getAtCoord(
                     intOf(square))):
                 return False
         return True
     return False
Beispiel #29
0
    def plot_tke(self,data,xaxis):

        met=data[['wdir','wspd','wvert','lats','lons']]
        topo=np.asarray(Terrain.get_topo(lats=met['lats'], lons=met['lons']))

        u_comp,v_comp = get_wind_components(met.wspd,met.wdir)
        w_comp=met.wvert
        u_var = pd.rolling_var(u_comp,60,center=True)
        v_var = pd.rolling_var(v_comp,60,center=True)
        w_var = pd.rolling_var(w_comp,60,center=True)

        tke = 0.5*(u_var+v_var+w_var)
        plt.figure()
        plt.plot(xaxis,tke)
        ax=plt.gca()
        ax.set_ylim([0,10])
        plt.xlabel('distance')
        plt.ylabel('TKE [m2 s-2]')
        add_second_y_in(ax,topo,xaxis=xaxis,color='g',label='Topography [m]')
        plt.draw()
def GetSuccessors(state):
    succ = []
    # successors above
    succ.append(
        State.State(elevations[state.x + 1][state.y - 1],
                    Terrain.GetTerrainVal(pix[state.x + 1, state.y - 1]),
                    state.x + 1, state.y - 1, state.goalX, state.goalY))
    succ.append(
        State.State(elevations[state.x + 1][state.y],
                    Terrain.GetTerrainVal(pix[state.x + 1, state.y]),
                    state.x + 1, state.y, state.goalX, state.goalY))
    succ.append(
        State.State(elevations[state.x + 1][state.y + 1],
                    Terrain.GetTerrainVal(pix[state.x + 1, state.y + 1]),
                    state.x + 1, state.y + 1, state.goalX, state.goalY))
    succ.append(
        State.State(elevations[state.x][state.y - 1],
                    Terrain.GetTerrainVal(pix[state.x, state.y - 1]), state.x,
                    state.y - 1, state.goalX, state.goalY))
    succ.append(
        State.State(elevations[state.x][state.y + 1],
                    Terrain.GetTerrainVal(pix[state.x, state.y + 1]), state.x,
                    state.y + 1, state.goalX, state.goalY))
    succ.append(
        State.State(elevations[state.x - 1][state.y - 1],
                    Terrain.GetTerrainVal(pix[state.x - 1, state.y - 1]),
                    state.x - 1, state.y - 1, state.goalX, state.goalY))
    succ.append(
        State.State(elevations[state.x - 1][state.y],
                    Terrain.GetTerrainVal(pix[state.x + 1, state.y]),
                    state.x + 1, state.y, state.goalX, state.goalY))
    succ.append(
        State.State(elevations[state.x - 1][state.y + 1],
                    Terrain.GetTerrainVal(pix[state.x - 1, state.y + 1]),
                    state.x - 1, state.y + 1, state.goalX, state.goalY))
    return succ
    def setTerrain(self, col, row):
        rand = random.randint(0, 100)
        if (self.difficulty == 1):
            if (rand <= 80):
                Terrain(self, col, row, 1)
            elif (rand > 80 and rand <= 90):
                Terrain(self, col, row, 2)
            else:
                Terrain(self, col, row, 3)

        if (self.difficulty == 2):
            if (rand <= 60):
                Terrain(self, col, row, 1)
            elif (rand > 60 and rand <= 80):
                Terrain(self, col, row, 2)
            else:
                Terrain(self, col, row, 3)
Beispiel #32
0
 def loadBackground(self):
     self.terrain = Terrain(self)
from Terrain import *
T = Terrain(128)
T.simplex(5)
T.mesh()
Beispiel #34
0
import pygame
import config
import Player
import Terrain
import Inventory
import showcoords

pygame.init()
window = pygame.display.set_mode((config.screen_width, config.screen_height))
pygame.display.set_caption("Minecraft2D")

terrain = Terrain.Terrain()
player = Player.Player(terrain)
equipment = Inventory.Inventory()


def update(ev):
    player.update(ev, terrain, equipment)
    equipment.update(ev)


def draw():
    window.fill((0, 0, 0))
    terrain.draw(window, player)
    player.draw(window)
    equipment.draw(window)
    showcoords.draw(window, player)


terrain.create_terrain()
Beispiel #35
0
    def cross_section(self,**kwargs):
    
        field_array=kwargs['field']

        ''' calculate wind components'''
        u_array=self.u_array
        v_array=self.v_array
        ''' along cross section assuming self.azimuth within [0, 90]     '''
        wind_dir_section = self.azimuth -180.
        wx = u_array*np.sin(wind_dir_section*np.pi/180.)
        wy = v_array*np.cos(wind_dir_section*np.pi/180.)
        wind_array = -(wx+wy)
        ''' perpendicular to cross section '''
        orthogonal_dir_section =wind_dir_section + 90.
        qx = u_array*np.sin(orthogonal_dir_section*np.pi/180.)
        qy = v_array*np.cos(orthogonal_dir_section*np.pi/180.)
        orth_array = (qx+qy)            

        self.slice_type='cross_section'
        self.set_panel(option=self.slice_type,wind=False)        
        figsize=self.figure_size['vertical']

        ''' get indices of starting and ending coordinates '''
        latix_0=cm.find_index_recursively(array=self.lats,value=self.slice[0][0],decimals=2)
        lonix_0=cm.find_index_recursively(array=self.lons,value=self.slice[0][1],decimals=2)
        latix_1=cm.find_index_recursively(array=self.lats,value=self.slice[1][0],decimals=2)
        lonix_1=cm.find_index_recursively(array=self.lons,value=self.slice[1][1],decimals=2)

        ''' create grid for the entire domain '''
        xx = np.arange(0,self.axesval['x'].size)
        yy = np.arange(0,self.axesval['y'].size)
        zz = np.arange(0,self.axesval['z'].size)
        xm,ym,zm = np.meshgrid(xx,yy,zz)

        ''' convert grid and plotting field to vector columns'''
        xd=np.reshape(xm,[1,xm.size]).tolist()
        yd=np.reshape(ym,[1,ym.size]).tolist()
        zd=np.reshape(zm,[1,zm.size]).tolist()
        xd=xd[0]
        yd=yd[0]
        zd=zd[0]

        ''' specify grid for interpolated cross section '''
        hres = 100
        vres = 44
        xi = np.linspace(lonix_0, lonix_1, hres)
        yi = np.linspace(latix_0, latix_1, hres)
        zi = np.linspace(0, 43, vres)
        zi=np.array([zi,]*hres)
        ki=np.ma.empty([vres,hres])
        wi=np.ma.empty([vres,hres])
        qi=np.ma.empty([vres,hres])
#        fillv = field_array.fill_value
        
        ''' convert to standard numpy array (not masked)
        and replace fill values for nans '''
        kd=np.ma.filled(field_array, fill_value=np.nan)
        wd=np.ma.filled(wind_array, fill_value=np.nan)
        qd=np.ma.filled(orth_array, fill_value=np.nan)

        ''' convert to 1 column array '''
        kd=np.reshape(kd,[kd.size,1])
        wd=np.reshape(wd,[wd.size,1])
        qd=np.reshape(qd,[qd.size,1])

        ''' create kdTree with entire domain'''
        coords=zip(xd,yd,zd)
        tree = cKDTree(coords)

        ''' interpolate using kdTree (nearest neighbor) 
            and averaging the neighborhood
        '''
        neigh = 8
        for k in range(vres):
            coords = zip(yi, xi, zi[:,k])
            dist, idx = tree.query( coords, k=neigh, eps=0, p=1, distance_upper_bound=10)        
            kd_mean = np.nanmean(kd[idx],axis=1)
            wd_mean = np.nanmean(wd[idx],axis=1)
            qd_mean = np.nanmean(qd[idx],axis=1)
            ki[k,:]=kd_mean.T
            wi[k,:]=wd_mean.T
            qi[k,:]=qd_mean.T
        
        component = [wi, qi]
        comptitle = ['Along-section wind speed [m s-1] (contours)\n',
                    'Cross-section wind speed [m s-1] (contours)\n']
        for n in range(2):
            """make plot with wind speed along cross section """
            with sns.axes_style("white"):
                fig,ax = plt.subplots(figsize=(8,11*0.5))

            ''' add field as image '''
            zsynth = self.axesval['z']
            gate_hgt=0.25 #[km]
            extent = [0, self.distance, zsynth[0]-gate_hgt/2., zsynth[-1]+gate_hgt/2.]
#            im, cmap, norm = self.add_field(ax,array=ki,field=self.var, extent=extent)
            im, cmap, norm = self.add_field2(ax,array=ki,field=self.var, extent=extent)

            ''' add terrain profiel '''
            prof = Terrain.get_altitude_profile(self)
            prof = np.asarray(prof)
            self.add_terrain_profile(ax, prof ,None)
            self.terrain.array['profile']=prof
            
            ''' add contour of wind section '''
            X,Y = np.meshgrid(np.linspace(0, self.distance, hres), zsynth)
            sigma=0.5
            section = gaussian_filter(component[n], sigma,mode='nearest')    
            cs = ax.contour(X,Y,section,colors='k',
                            linewidths=1.5, levels=range(-4,26,2))    
            # cs = ax.contour(X,Y,component[n],colors='k',linewidths=0.5, levels=range(-4,26,2))            
            ax.clabel(cs, fontsize=12,    fmt='%1.0f',)

            ax.set_yticks(zsynth[1::2])
            ytlabels = ["{:3.1f}".format(z) for z in zsynth[1::2]]
            ax.set_yticklabels(ytlabels)
            ax.set_ylim(0. , 7.5)
            ax.set_xlim(0. , self.distance)

            legname = os.path.basename(self.file)
            ta=ax.transAxes
            ax.text(0.05,0.9, legname[:3].upper() + " " + legname[3:5], transform = ta,weight='bold')
            y,x = zip(*self.slice)
            stlat='{:3.2f}'.format(y[0])
            stlon='{:3.2f}'.format(x[0])
            ax.text(0.05,0.85, 'start: ('+stlat+','+stlon+')', transform = ta)
            enlat='{:3.2f}'.format(y[-1])
            enlon='{:3.2f}'.format(x[-1])
            ax.text(0.05,0.8, 'end: ('+enlat+','+enlon+')', transform = ta)            
            staz='{:3.1f}'.format(self.azimuth)
            ax.text(0.05, 0.75, 'az: '+staz, transform=ta)

            ax.set_xlabel('Distance along cross section [km]')
            ax.set_ylabel('Altitude [km]')

            if self.verticalGridMajorOn:
                ax.grid(True, which = 'major',linewidth=1)

            if self.verticalGridMinorOn:
                ax.grid(True, which = 'minor',alpha=0.5)
                ax.minorticks_on()

            ''' add color bar '''
            fig.colorbar(im,cmap=cmap, norm=norm)

            ''' add title '''
            titext='Dual-Doppler Synthesis: '+ self.get_var_title(self.var)+' (color coded)\n'
            titext=titext+comptitle[n]
            line_start='Start time: '+self.synth_start.strftime('%Y-%m-%d %H:%M')+' UTC\n'
            line_end='End time: '+self.synth_end.strftime('%Y-%m-%d %H:%M')+' UTC'        
            fig.suptitle(titext+line_start+line_end)

            plt.subplots_adjust(top=0.85,right=1.0)
            plt.draw()

        return ki,component
Beispiel #36
0
def main(genomes, config):

    nets = []
    ge = []
    birds = []
    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        birds.append(Bird.Bird(230, 350))
        g.fitness = 0
        ge.append(g)

    base = Terrain.Base(730)
    pipes = [Pipe.Pipe(700)]
    win = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    clock = pygame.time.Clock()
    score = 0

    run = True
    while run:
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        # bird move
        pipe_ind = 0
        if len(birds) > 0:
            if len(pipes) > 1 and birds[
                    0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width():
                pipe_ind = 1
        else:
            run = False
            break

        for x, bird in enumerate(birds):
            bird.move()
            ge[x].fitness += 0.3

            output = nets[x].activate(
                (bird.y, abs(bird.y - pipes[pipe_ind].height),
                 abs(bird.y - pipes[pipe_ind].bottom)))
            if output[0] > 0.5:
                bird.jump()

        add_pipe = False
        rem = []
        for pipe in pipes:
            for x, bird in enumerate(birds):
                if pipe.collide(bird):
                    ge[x].fitness -= 0.5
                    birds.pop(x)
                    nets.pop(x)
                    ge.pop(x)

                if not pipe.passed and pipe.x < bird.x:
                    pipe.passed = True
                    add_pipe = True

            if pipe.x + pipe.PIPE_TOP.get_width() < 0:
                rem.append(pipe)
            pipe.move()
        if add_pipe:
            score += 1
            for g in ge:
                g.fitness += 5
            pipes.append(Pipe.Pipe(600))

        for r in rem:
            pipes.remove(r)

        for x, bird in enumerate(birds):
            if bird.y + bird.img.get_height() >= 730 or bird.y < 0:
                birds.pop(x)
                nets.pop(x)
                ge.pop(x)

        base.move()
        draw_window(win, birds, pipes, base, score)
Beispiel #37
0
    def vertical_plane(self,**kwargs):

        field_array=None
        for key,value in kwargs.iteritems():
            if key == 'field':
                isWind=False            
                field_array=value
            if key == 'spd':
                isWind=True
                windname=value
            elif key == 'sliceo':
                self.sliceo=value

        u_array=self.u_array
        v_array=self.v_array
        w_array=self.w_array

        self.slice_type='vertical'
        self.set_panel(option=self.slice_type,wind=isWind)        

        figsize=self.figure_size['vertical']
        fig = plt.figure(figsize=figsize)

        plot_grids=ImageGrid( fig,111,
                                nrows_ncols = self.rows_cols,
                                axes_pad = 0.0,
                                add_all = True,
                                share_all=False,
                                label_mode = "L",
                                cbar_location = "top",
                                cbar_mode="single",
                                aspect=True)

        """ get list with slices """
        uComp  = self.get_slices(u_array)
        vComp  = self.get_slices(v_array)
        wComp  = self.get_slices(w_array)
        profiles = Terrain.get_altitude_profile(self)

        if isWind:
            if windname == 'u':
                field_group = uComp
                colorName='U'
                varName=colorName
            elif windname == 'v':
                field_group = vComp
                colorName='V'
                varName=colorName
            elif windname == 'w':
                field_group = wComp
                colorName='WVA'
                varName=colorName
        else:
            field_group = self.get_slices(field_array)
            varName=self.var

        ''' field extent '''
        extent1=self.get_extent()

        ''' if zoomOpt is false then extent1=extent2 '''            
        if self.zoomOpt:
            opt=self.zoomOpt[0]
            extent2=cm.zoom_in(self,extent1,self.zoomCenter[opt])
        else:
            extent2=extent1

        ''' scale for horizontal axis'''
        self.scale=20

        ''' adjust vertical extent '''
        if self.sliceo=='meridional':
            extent3=cm.adjust_extent(self,extent1,'meridional','data')
            extent4=cm.adjust_extent(self,extent2,'meridional','detail')
            horizontalComp=vComp
            geo_axis='Lon: '
        elif self.sliceo=='zonal':
            extent3=cm.adjust_extent(self,extent1,'zonal','data')
            extent4=cm.adjust_extent(self,extent2,'zonal','detail')            
            horizontalComp=uComp
            geo_axis='Lat: '


        """creates iterator group """
        group=zip(plot_grids,
                    field_group,
                    horizontalComp,
                    wComp,
                    profiles['altitude'],profiles['axis'])

        """make gridded plot """
        p=0
        for g,field,h_comp,w_comp,prof,profax in group:

            if isWind:
                im, cmap, norm = self.add_field(g,
                                                array=field.T,                                                
                                                field=varName,
                                                name=colorName,
                                                ext=extent3)
            else:
                im, cmap, norm = self.add_field(g,
                                                array=field.T,
                                                field=varName,
                                                name=self.var,
                                                ext=extent3)

            self.add_terrain_profile(g,prof,profax)

            if self.wind and not isWind:
                self.add_windvector(g,h_comp.T,w_comp.T)

            self.add_slice_line(g)

            g.set_xlim(extent4[0], extent4[1])
            g.set_ylim(extent4[2], extent4[3])    

            if p == 0:
                self.match_horizontal_grid(g)

            self.adjust_ticklabels(g)

            if self.verticalGridMajorOn:
                g.grid(True, which = 'major',linewidth=1)

            if self.verticalGridMinorOn:
                g.grid(True, which = 'minor',alpha=0.5)
                g.minorticks_on()

            if self.sliceo=='meridional':
                geotext=geo_axis+str(self.slicem[p])
            elif self.sliceo=='zonal':
                geotext=geo_axis+str(self.slicez[p])

            g.text(    0.03, 0.9,
                    geotext,
                    fontsize=self.zlevel_textsize,
                    horizontalalignment='left',
                    verticalalignment='center',
                    transform=g.transAxes)
            p+=1

        # add color bar
        plot_grids.cbar_axes[0].colorbar(im,cmap=cmap, norm=norm)

        # add title
        titext='Dual-Doppler Synthesis: '+ self.get_var_title(varName)+'\n'
        line_start='\nStart time: '+self.synth_start.strftime('%Y-%m-%d %H:%M')+' UTC'
        line_end='\nEnd time: '+self.synth_end.strftime('%Y-%m-%d %H:%M')+' UTC'        
        fig.suptitle(titext+self.file+line_start+line_end)

        # show figure
        plt.draw()
Beispiel #38
0
    def horizontal_plane(self , **kwargs):

        field_array=kwargs['field']
        u_array=self.u_array
        v_array=self.v_array
        w_array=self.w_array

        if self.mask:
            field_array.mask=w_array.mask
            u_array.mask=w_array.mask
            v_array.mask=w_array.mask

        if self.panel:
            self.set_panel(option='single')
            figsize=self.figure_size['single']
        else:
            self.set_panel(option='multi')
            figsize=self.figure_size['multi']

        self.slice_type='horizontal'

        with sns.axes_style("white"):
            fig = plt.figure(figsize=figsize)
            plot_grids=ImageGrid( fig,111,
                                    nrows_ncols = self.rows_cols,
                                    axes_pad = 0.0,
                                    add_all = True,
                                    share_all=False,
                                    label_mode = "L",
                                    cbar_location = "top",
                                    cbar_mode="single")
    
        ''' field extent '''
        extent1=self.get_extent()

        ''' if zoomOpt is false then extent1=extent2 '''            
        if self.zoomOpt:
            opt=self.zoomOpt[0]
            extent2=cm.zoom_in(self,extent1,self.zoomCenter[opt])
        else:
            extent2=extent1


        ''' make slices '''
        field_group = self.get_slices(field_array)
        ucomp = self.get_slices(u_array)
        vcomp = self.get_slices(v_array)        

        ''' creates iterator group '''
        group=zip(plot_grids,self.zlevels,field_group,ucomp,vcomp)
        gn=0
        
        ''' make gridded plot '''
        for g,k,field,u,v in group:

            self.add_coastline(g)
            self.add_flight_path2(g)

            im, cmap, norm = self.add_field2(g,
                                            array=field.T,
                                            field=self.var)

            if self.terrain.file:
                Terrain.add_contour(g,k,self)

            if self.wind:
                self.add_windvector(g,u.T,v.T,gn)

            if self.slice:
                self.add_slice_line(g,gn)

            if self.markersLocations:
                self.add_location_markers(g, gn)

            g.set_xlim(extent2[0], extent2[1])
            g.set_ylim(extent2[2], extent2[3])                

            if gn == 0:
                legname = os.path.basename(self.file)
                g.text(0.02,0.15, legname[:3].upper() + " " + legname[3:5],
                       horizontalalignment='left',
                       transform = g.transAxes,weight='bold')

            if self.horizontalGridMajorOn:
                g.grid(True, which = 'major',linewidth=1)

            if self.horizontalGridMinorOn:
                g.grid(True, which = 'minor',alpha=0.5)
                g.minorticks_on()

            ztext=str(k)+'km MSL'
            g.text(    0.02, 0.03,
                    ztext,
                    fontsize=self.zlevel_textsize,
                    horizontalalignment='left',
                    verticalalignment='center',
                    transform=g.transAxes)

            self.horizontal['ymajor'] = g.get_yticks(minor=False)
            self.horizontal['yminor'] = g.get_yticks(minor=True)
            self.horizontal['xmajor'] = g.get_xticks(minor=False)
            self.horizontal['xminor'] = g.get_xticks(minor=True)            
            gn+=1

        ''' add color bar '''
        plot_grids.cbar_axes[0].colorbar(im,cmap=cmap, norm=norm)

        ''' add title '''
        st=self.synth_start
        en=self.synth_end
        t1='Dual-Doppler Synthesis: '+ self.get_var_title(self.var) +'\n'
        t2='Date: '+st.strftime('%Y-%m-%d') + '\n'
        t3= 'Time: '+st.strftime('%H:%M')+'-'+en.strftime('%H:%M UTC') + '\n'        
        # fig.suptitle(t1+t2+t3+self.file)
        fig.suptitle(t1+t2+t3)

        plt.draw()
        self.haxis=g
Beispiel #39
0
    def plot_meteo(self,xaxis,dots):

        topo=Terrain.get_topo(lats=self.met['lats'], lons=self.met['lons'])

        varname={    0:{'var':'atemp','name': 'air temperature',
                            'loc':3,'ylim':None,'fmt':False},
                    1:{'var':'dewp','name': 'dew point temp',
                            'loc':3,'ylim':None,'fmt':False},
                    2:{'var':'wdir','name':'wind direction',
                            'loc':(0.05,0.9),'ylim':None,'fmt':True},                            
                    3:{'var':'apres','name': 'air pressure',
                            'loc':(0.05,0.9),'ylim':None,'fmt':False},                        
                    4:{'var':'relh','name':'relative humidity',
                            'loc':(0.05,0.05),'ylim':[80,101],'fmt':True},                            
                    5:{'var':'wspd','name': 'wind speed',
                            'loc':(0.05,0.9),'ylim':None,'fmt':True},
                    6:{'var':'galt','name': 'geopotential alt',
                            'loc':(0.05,0.9),'ylim':None,'fmt':True},
                    7:{'var':'jwlwc','name':'liquid water content',
                            'loc':(0.05,0.9),'ylim':None,'fmt':False},
                    8:{'var':'wvert','name':'vertical velocity',
                            'loc':(0.05,0.9),'ylim':[-2,4],'fmt':True},
                    9:{'var':'palt','name': 'pressure alt',
                            'loc':(0.05,0.9),'ylim':None,'fmt':True}}


        fig, ax = plt.subplots(3,3, sharex=True,figsize=(15,10))
        axs=ax.ravel()
        for i in varname.items():
            item = i[0]            
            var = i[1]['var']
            name = i[1]['name']
            loc = i[1]['loc']
            ylim = i[1]['ylim']
            ax = axs[item-1]
            if item < 2: # air temp and dew point in the same plot
                axs[0].plot(xaxis,self.met[var],label=name)
                if ylim: axs[0].set_ylim(ylim)
                if item == 1:
                    axs[0].grid(True)
                    axs[0].legend(loc=loc,frameon=False)
            else:
                ax.plot(xaxis,self.met[var],label=name)
                if item == 6: 
                    ax2 = ax.twinx()
                    ax2.plot(xaxis,topo,'r')
                    ax2.set_ylabel('topography [m]', color='r')
                    for tl in ax2.get_yticklabels():
                        tl.set_color('r')
                    ax2.grid(False)
                if ylim: ax.set_ylim(ylim)
                ax.grid(True)
                ax.annotate(name, fontsize=16,
                                    xy=loc, 
                                    xycoords='axes fraction')
                if item == 8:
                    ax.set_xlabel('Distance from beginning of flight [km]')

        new_xticks=[xaxis[i] for i in dots]
        adjust_xaxis(axs,new_xticks)
        adjust_yaxis(axs) # --> it's affecting formatter
        l1='Flight level meteorology for '+self.name
        l2='\nStart time: '+self.time[0].strftime('%Y-%m-%d %H:%M')+' UTC'
        l3='\nEnd time: '+self.time[1].strftime('%Y-%m-%d %H:%M')+' UTC'
        fig.suptitle(l1+l2+l3,y=0.98)
        fig.subplots_adjust(bottom=0.08,top=0.9,
                            hspace=0,wspace=0.2)
        plt.draw