Пример #1
0
 def startNewRound(self, isFirst=True):
     # python random is terrible
     random.seed(datetime.now())
     if not isFirst:
         print("Car lost", self.calculateScore())
         print("Distance", self.car.car.position[0], "Time",
               (pygame.time.get_ticks() - self.simStartTime))
         print("Beginning train.  This could take some time.")
         self.carController.learn()
         print("Done")
         self.carController.startNewRound()
         self.car.destroy()
         # self.terrain.destroy()
         if self.roundsLeftToSkip == 0:
             self.roundsLeftToSkip = self.ROUNDS_TO_SKIP
         else:
             self.roundsLeftToSkip -= 1
         print("Rounds left", self.roundsLeftToSkip)
     else:
         self.roundsLeftToSkip = 0
         self.terrain = Terrain(
             self, 0, self.SCREEN_HEIGHT / self.PPM / 3, 1, 300,
             TerrainGenerator.Composer(0.9,
                                       math.pi,
                                       offset=(random.random() * math.pi,
                                               random.random() * math.pi /
                                               2)))
     self.car = Car(self, 5, 20, self.carController)
     self.distanceSinceLastCheck = self.car.car.position[0]
     self.simStartTime = pygame.time.get_ticks()
Пример #2
0
    def create():
        Map.generate_lakes()
        Map.generate_valleys()

        # Make mud around lakes
        for sq in Map.spawnable:
            sq.terrain = Terrain(0, 1)
Пример #3
0
    def init_landscape_from_json(self, json_object):
        # forest
        scene_objects = SceneObjects()
        scene_objects.set_sim(self.get_sim())
        scene_objects.init_objects_from_json(json_object)
        self.scene_objects = scene_objects

        # terrain
        terrain = Terrain()
        terrain.set_sim(self.get_sim())
        terrain.init_terrain_from_json(json_object)
        self.terrain = terrain

        # optical properties
        ops = OpticalProperties()
        ops.init_ops_from_json(json_object)
        self.optical_properties = ops

        # temperature
        self.temperature_properties = json_object["scene"][
            "temperature_properties"]

        # others
        self.extra_scene = json_object["scene"]["extra_scene"]

        return self
Пример #4
0
def runGame():
    global WIDTH, HEIGHT, SCALE, OCTAVES, PERSISTANCE, LACUNARITY
    playerBoat = Boat(SELECTED_BOAT, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
    SEED = np.random.randint(0, 100)
    world = Terrain(HEIGHT, WIDTH)
    world.generateTopTerrain(SCALE, OCTAVES, PERSISTANCE, LACUNARITY, SEED)
    world.generateTopColor(-0.2, 0.01, 0.055, 0.25, 0.33, 0.47, 0.55)
    image = pg.surfarray.make_surface(world.topColorTerrain).convert()

    while True:
        deltaTime = clock.get_time()
        backgroundInputCheck(pg.event.get())

        playerBoat.getInput(pg.key.get_pressed(), deltaTime)
        playerBoat.update(
            deltaTime, world.topColorTerrain[len(world.topColorTerrain) -
                                             int(playerBoat.position.x)]
            [len(world.topColorTerrain[0]) - int(playerBoat.position.y)])

        screen.fill(BLACK)
        screen.blit(image, (-playerBoat.position.x, -playerBoat.position.y))
        playerBoat.draw(screen, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)

        clock.tick(60)
        pg.display.flip()
Пример #5
0
    def __init__(self, physicsWorld):
        pygame.init()

        # constants
        self.PPM = 20.0  # pixels per meter
        self.TARGET_FPS = 60
        self.TIME_STEP = 1.0 / self.TARGET_FPS
        self.SCREEN_WIDTH = 1200
        self.SCREEN_HEIGHT = 800
        
        self.screenSize = (self.SCREEN_WIDTH, self.SCREEN_HEIGHT)
        self.zoom = 1.0
        self.offset = (0.0, 0.0)
        self.viewCenter = (self.SCREEN_WIDTH/2, self.SCREEN_HEIGHT/2)
        
        self.clock = pygame.time.Clock()

        # core objects
        self.screen = pygame.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT))
        self.world = physicsWorld

        # world objects
        self.terrain = Terrain(self, 0, self.SCREEN_HEIGHT/self.PPM/2, 2, 25, TerrainGenerator.Composer(1, math.pi))
        self.car = Car(self, 0, 0)
        
        self.keys = pygame.key.get_pressed()
Пример #6
0
def main():
    # initializing and drawing background UI elements
    background = UIBox(g_const.screen_size, (0, 0, 0), (0, 0))
    arena = UIBox(g_const.arena_size, (50, 50, 50), g_const.arena_pos)
    sidebar = UIBox(g_const.sidebar_size, (50, 50, 50), g_const.sidebar_pos)
    background.draw()
    sidebar.draw()

    evt_man = EventManager()
    terrain = Terrain()
    game_state = GameState(terrain)

    start = time.time()
    evt_man.start_world_update()

    while True:
        dt = time.time() - start

        if dt >= frame_length:
            start = time.time()  # reset start tick

            events = evt_man.processEvents()  # handle events

            game_state.update(events)  # update game state

            # draw objects
            arena.draw()
            game_state.curr_shape.draw()
            terrain.draw()

            # update display
            pyg.display.update()
Пример #7
0
 def cycle(self):
     #un cycle de la mutation
     listeTerrain=[]
     for i in range (self.sizePopulation):
         listeTerrain.append(Terrain())
     with open('solarIA.DD', 'wb') as fichier:
         #mon_pickler = pickle.Pickler(fichier)
         #mon_pickler.dump(score)
Пример #8
0
 def __init__(self, i, j, field):
     Cell.total_cells += 1
     self.__cell_n = Cell.total_cells
     self._is_empty = True
     self.__entity = None
     self.__terrain = Terrain(field, self)
     self.__coordinates = (i, j)
     self.field = field
Пример #9
0
 def newRound(self, enemyCount):
     self.enemies.clear()
     self.terrain = Terrain(self.canvasWidth, self.canvasHeight, self)
     self.terrain.genMaze(0, 0)
     for i in range(enemyCount):
         self.enemies.append(
             Tank(
                 Tank.newTankPos(self.terrain, self.canvasWidth,
                                 self.canvasHeight), self))
     self.player = self.newPlayer()
     self.playerClonePos = self.player.pos.copy()
     self.roundCount = enemyCount
     self.score += self.roundCount
Пример #10
0
    def __init__(self):
        super().__init__()
        # forest
        self.scene_objects = SceneObjects()

        # terrain
        self.terrain = Terrain()

        # optical properties
        self.optical_properties = OpticalProperties()

        # temperature
        self.temperature_properties = {}

        # others
        self.extra_scene = ""
Пример #11
0
    def __init__(self,
                 agents,
                 width=DEFAULT_WIDTH,
                 height=DEFAULT_HEIGHT,
                 biomes=None,
                 seed=DEFAULT_SEED):
        self.tick = 0
        self.seed = seed
        self.width = width
        self.height = height
        self.agents = agents
        if biomes:
            self.biomes = biomes
        else:
            self.biomes = self._generate_biomes()

        self.terrain = Terrain(self.biomes, width, height, seed)
        self.visualizer = self._generate_gui()
Пример #12
0
def showLand(waterLevel):
    global WIDTH, HEIGHT, SCALE, OCTAVES, PERSISTANCE, LACUNARITY
    SEED = np.random.randint(0, 100)
    world = Terrain(HEIGHT, WIDTH)
    world.generateTopTerrain(SCALE, OCTAVES, PERSISTANCE, LACUNARITY, SEED)
    world.raiseTerrain(-0.3)
    print("Land Generated")

    while True:
        backgroundInputCheck(pg.event.get())
        world.generateTopColor(waterLevel, waterLevel + 0.045,
                               waterLevel + 0.24, waterLevel + 0.32,
                               waterLevel + 0.46, waterLevel + 0.54)
        image = pg.surfarray.make_surface(world.topColorTerrain).convert()
        screen.fill(BLACK)
        screen.blit(image, (0, 0))

        clock.tick(30)
        pg.display.flip()
Пример #13
0
    def __init__(self, proto_tile=None, block=None, mat_library=None):

        if not (proto_tile is None or block is None or mat_library is None):
            self.proto_tile = proto_tile
            self.global_x = block.x * 16 + proto_tile.x
            self.global_y = block.y * 16 + proto_tile.y
            self.global_z = block.z
            typeindex = getattr(self.proto_tile, 'material_type', -1)
            matindex = getattr(self.proto_tile, 'material_index', -1)
            # right now this is hacked manually by editing the Tile_pb2.py.
            # In the future this should be integrated also in the Tile.proto
            if typeindex == -1 or matindex == -1:
                self.material = proto.Tile_pb2.Tile.TileMaterialType.Name(
                    self.proto_tile.tile_material)
            else:
                try:
                    self.material = mat_library[typeindex][matindex]
                except IndexError:
                    self.material = 'unknown'
            self.terrain = Terrain(proto_tile.type)
Пример #14
0
    def __init__(self, file):
        self.terrain = []
        with open(file) as csvfile:
            readCSV = csv.reader(csvfile)

            for row in readCSV:
                if len(row) != 10:
                    raise Exception("** Exception: CSV file for Board invalid")
                coords = []
                for i in range(2, len(row)):
                    coords_from_file = row[i].split('-')
                    if len(coords_from_file) != 3:
                        raise Exception("** Exception: CSV file for Board invalid")

                    x = float(coords_from_file[0])
                    y = float(coords_from_file[1])
                    z = float(coords_from_file[2])
                    coords.append(Point(x, y, z))

                self.terrain.append(Terrain(coordinates=coords, name=row[0].strip(), terrain_type=row[1].strip()))
Пример #15
0
 def __init__(self, parameters=None):
     """
         dict parameters should contain the following keys:
             height (int)
             width (int)
             slope (float)
             gamma (float)
             rho (float)
             mu (float)
             cells (list of lists of dict containing the keys:
                 height_of_terrain
                 height_of_water
                 concentration_of_nutrients
                 peat_bog_thickness)
     """
     self.parameters = parameters
     self.gamma = self.parameters['gamma']
     self.rho = self.parameters['rho']
     self.mu = self.parameters['mu']
     self.terrain = Terrain(parameters)
     self.max_depth = 0
Пример #16
0
def createLand(initWaterLevel, increment):
    global WIDTH, HEIGHT, SCALE, OCTAVES, PERSISTANCE, LACUNARITY
    SEED = np.random.randint(0, 100)
    world = Terrain(HEIGHT, WIDTH)
    world.generateTopTerrain(SCALE, OCTAVES, PERSISTANCE, LACUNARITY, SEED)
    print("Land Generated")

    waterLevel = initWaterLevel

    while waterLevel < world.findMaxHeight():
        backgroundInputCheck(pg.event.get())
        world.generateTopColor(waterLevel, waterLevel + 0.045,
                               waterLevel + 0.24, waterLevel + 0.32,
                               waterLevel + 0.46, waterLevel + 0.54)
        image = pg.surfarray.make_surface(world.topColorTerrain).convert()

        screen.fill(BLACK)
        screen.blit(image, (0, 0))

        waterLevel += increment
        clock.tick(30)
        pg.display.flip()
Пример #17
0
from Terrain import Terrain
from PositionLocator import PositionLocator
import matplotlib.pyplot as plt
from matplotlib import animation
import math

terrain_map = Terrain(4099, 0.8, 0.936846)
height_map = terrain_map.height_map
terrain_map.height_map[1600:1600 + 700] = [terrain_map.height_map[1600]] * 700
#height_map = [0.1] * 4099
locator = PositionLocator(height_map, 500, 0.0001, 5)

# fig = plt.figure()
# plt.hist(locator.particles, 100)
#
# for i in xrange(0, locator.particle_count):
#     locator.weights[i] = (1/math.sqrt(2*math.pi*locator.obs_noise)) \
#                               * math.exp(-(locator.particles[i]-2000)**2/(2*locator.obs_noise))
#         # normalise weights
# locator.weights = [locator.weights[i]/sum(locator.weights) for i in xrange(0, locator.particle_count)]
#
#
# locator.resample_particles()
# plt.hist(locator.particles, 100)

#locator.find_location()

x = range(0, 4099)
y = height_map

fig = plt.figure()
Пример #18
0
 def __init__(self):
     self.players = []
     self.terrain = Terrain()
     self.judge = MoveJudge(self.terrain)
Пример #19
0
            self.robotControl.setXC(event.xdata)
            self.robotControl.setYC(event.ydata)
            self.robotControl.setThetaC(2)


terrain_lines = np.array([[[0, 0], [0, 2000]], [[0, 2000], [3000, 2000]],
                          [[3000, 2000], [3000, 0]], [[3000, 0], [0, 0]]])

nbpts = 1 / 0.005 * 5
trajectory_t = np.linspace(0, 20, nbpts * 10)
trajectory = np.array(
    [500 * np.cos(trajectory_t) + 1500, 500 * np.sin(trajectory_t) + 1500])
# trajectory = np.array([trajectory_t*200+700,
#                         np.ones_like(trajectory_t)*1500])

terrain = Terrain(terrain_lines)
robot = Robot(700, 900, 0)
robotControl = RobotControl(robot.getX(), robot.getY(), robot.getTheta(),
                            robot)
lidar = Lidar([robot.getX(), robot.getY()], 0, 50, np.pi / 30, terrain_lines)
pickConsign = PickConsign(robotControl)

dT = 0.005
i = 0
robotpos = [[], []]
Tmax = int(50 / dT)
for t in range(Tmax):

    #computing
    robot.update(dT)
    robotControl.update(dT)
Пример #20
0
import pygame

from env import *
from World import World
from Terrain import Terrain
from Player import Player

pygame.init()

window = pygame.display.set_mode(WINDOW_SIZE)

# Generate World
World.generate_world(100)

# Creating the terrain
terrain = Terrain()

pygame.display.set_caption('API Game')
running = True

# Event loop
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            # keys = pygame.key.get_pressed()
            direction = -1

            if event.key == pygame.K_UP:
Пример #21
0
import matplotlib.pyplot as plt
from Terrain import Terrain
from Constants import SlopeAlgorithms, SlopeUnits

if __name__ == "__main__":
    # Create a terrain object from a Digital Elevation Model
    terrain = Terrain(dem="example_data\\Alabama_NED.tif", cell_resolution=30)

    # Calculate the terrain outputs from the input DEM
    slope = terrain.calculate_slope(algorithm=SlopeAlgorithms.NEIGHBORHOOD,
                                    units=SlopeUnits.DEGREES)
    aspect = terrain.calculate_aspect()
    hillshade = terrain.calculate_hillshade(azimuth=315)
    elevation_profile = terrain.create_elevation_profile(pt1=(33.5, -87),
                                                         pt2=(31.7, -86))

    # Preview the terrain outputs using pyplot
    slope.preview()
    aspect.preview()
    hillshade.preview()
    elevation_profile.preview()

    # # Save the terrain outputs as local files
    slope.save("example_data\\output\\slope.png")
    aspect.save("example_data\\output\\aspect.png")
    hillshade.save("example_data\\output\\hillshade.png")
    elevation_profile.save("example_data\\output\\elevprof.png")
Пример #22
0
from Water import Water

arr = []  # map

# creating a map 10x10
for line in range(15):
    arr.append([])
    for row in range(15):

        # Random choose if next object is a terrain or water
        types = random.randrange(
            0, 6)  # water (0-1) or terrain (2-5) - proportion 2:4

        # if object is a terrain
        if types < 2:
            arr[line].append(Terrain())
            # print("Terrain", line, row)

        # if object is a water
        else:

            # for elements other than first
            if line > 0 and row > 0:

                #  Water elements should be connected if possible.
                #  Check last row and last object if it's a water element.
                if isinstance(arr[line][row - 1], Water) or isinstance(
                        arr[line - 1][row], Water):
                    arr[line].append(Water())
                    # print("Water", line, row)
                else:
Пример #23
0
 def set_terrain(self, terrain_id, sub_terrain_id=0):
     if self.terrain.terrain_id == terrain_id and self.terrain.sub_id == sub_terrain_id:
         return
     self.terrain = Terrain(terrain_id, sub_terrain_id)
Пример #24
0
 def __init__(self, location, terrain_id=0, sub_terrain_id=0):
     self.terrain = Terrain(terrain_id, sub_terrain_id)
     self.location = location
     self.creature_list = []
     # Update self when first displayed
     GridSquare.altered.append(self)
Пример #25
0
    def run(self):
        Terrain(200, 350, 400, 50)
        Terrain(200, 230, 150, 50)
        Terrain(450, 230, 150, 50)

        while not self.done:

            ### INPUT PROCESSING

            keys = pygame.key.get_pressed()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True

                # Processing keys
                if event.type in [pygame.KEYDOWN, pygame.KEYUP] and \
                   event.key in Controls:
                    Controls[event.key][event.type - 2]()

                # Processing mouse
                mouse = pygame.mouse.get_pos()

            ########

            ### RENDERING

            # Game state
            if self.game_state == GameState.GAME:
                screen.fill(BGCOLOR)
                game_surface.fill(BGCOLOR)

                # Move screen depending on mouse position
                self.screen_offset.xy = [
                    (screen.get_width() / 2 - mouse[0]) / 3,
                    (screen.get_height() / 2 - mouse[1]) / 3
                ]

                if self.screen_offset.magnitude() > 150:
                    self.screen_offset = self.screen_offset.normalize() * 150

                self.screen_offset.xy += [
                    screen.get_width() / 2,
                    screen.get_height() / 2
                ]
                self.screen_offset.xy -= Game().player.sprite.rect.topleft

                for terrain in Terrain.all:
                    game_surface.blit(terrain.image, terrain.rect)

                self.player.sprite.process(clock.get_time())
                game_surface.blit(self.player.sprite.image,
                                  self.player.sprite.rect)

                screen.blit(game_surface, self.screen_offset)

            # Menu state
            if self.game_state == GameState.MENU:
                screen.fill((0, 255, 255))

            pygame.display.flip()
            clock.tick(120)
Пример #26
0
			player.setLastActivity("terrain", frame)
			return player.getTerrainChanges()
		return ""
		
	def remote_getEffectDrawList(self, pID):
		global frame
		player = Globals.players.getPlayer(pID)
		if player and player.getLastActivity("effects") != frame:
			player.setLastActivity("effects", frame)
			return Globals.effects.getDrawList(player)
		return ""
		
Globals.players = Players()
Globals.effects = EffectStruct()
Globals.units = UnitStruct()
Globals.terrain = Terrain()
Globals.projectiles = ProjectileStruct()

started = True
_done = False
nextReset = 0
spawnDelta = 100

def mainLoop():
	global _done, handicap, frame, nextReset, nextSpawn
	frame = (frame + 1) % 5000
	
	if started:
		Globals.units.update()
		Globals.effects.update()
		Globals.projectiles.update()
Пример #27
0
from Terrain import Terrain
from RoguePy.UI import Colors

EMPTY = Terrain(True, True, "Empty space")

WALL = Terrain(False, False, "Stone wall")\
  .setColors(Colors.light_grey, Colors.darkest_grey * 0.4)\
  .setChar('#')

FLOOR = Terrain(True, True, "Stone floor")\
  .setColors(Colors.dark_grey, Colors.darkest_grey * 0.4)\
  .setChar('.')