def populate(self): if not os.path.exists(self.path): os.mkdir(self.path) if os.path.exists('%s/level.dat' % self.path): cantLoad = False f = open('%s/level.dat' % self.path, 'r') try: json.loads(f.read()) except: cantLoad = True self.server.log.error( 'level.dat unreadable or unparsable - resetting') f.close() defaults = { 'seed': random.randrange(-9999999, 9999999), 'time': 0, 'name': '' } if not os.path.exists('%s/level.dat' % self.path) or cantLoad: f = open('%s/level.dat' % self.path, 'w') f.write(json.dumps(defaults)) f.close() f = open('%s/level.dat' % self.path, 'r') self.level = json.loads(f.read()) f.close() self.terrain = Terrain(self.level['seed'])
def __init__(self, screen: pygame.Surface): global current_game current_game = self self.screen = screen spritesheet = SpriteSheet('./assets/sprites.png') self.life_image = pygame.transform.scale( spritesheet.image_at((423, 345, 16, 8), color_key=-1), (64, 32)) self.checkpoint_image = pygame.transform.scale( spritesheet.image_at((389, 335, 8, 8), color_key=-1), (32, 32)) self.simplex = OpenSimplex() self.font = pygame.font.Font('freesansbold.ttf', 24) self.next_hole = self.screen.get_width( ) + random.random() * HOLE_SPACE_VAR self.holes = [] self.checkpoint = 0 self.checkpoint_score = 0 self.lives = 3 self.score = 0 self.highest_score = 0 self.terrain = Terrain(screen, MARTIAN_BROWN, self.terrain_point) self.all_sprites = pygame.sprite.Group() self.player = Player(START_LOCATION, 0) self.all_sprites.add(self.player)
def __init__(self): self.debug = False ShowBase.__init__(self) self.accept("escape",sys.exit) # the dt should depend on the framerate self.dt = 0.25 """try: self.database = Database() self.ranking = self.database.getRankingFromDatabase() except: pass""" self.musicManager.setConcurrentSoundLimit(2) #initiate game state self.state = 'Menu' self.terrain = Terrain(1024) """try: self.classement = Classement(self.ranking) self.classement.hideMenu() except: pass""" self.menu = Menu() self.loadStartMenu() if(self.debug == False): self.disableMouse()
def Initialize(credentials="persistent", opt_url=None): """Initialize the EE library. If this hasn't been called by the time any object constructor is used, it will be called then. If this is called a second time with a different URL, this doesn't do an un-initialization of e.g.: the previously loaded Algorithms, but will overwrite them and let point at alternate servers. Args: credentials: OAuth2 credentials. 'persistent' (default) means use credentials already stored in the filesystem, or raise an explanatory exception guiding the user to create those credentials. opt_url: The base url for the EarthEngine REST API to connect to. """ if credentials == "persistent": credentials = _GetPersistentCredentials() data.initialize(credentials, (opt_url + "/api" if opt_url else None), opt_url) # Initialize the dynamically loaded functions on the objects that want them. ApiFunction.initialize() Element.initialize() Image.initialize() Feature.initialize() Collection.initialize() ImageCollection.initialize() FeatureCollection.initialize() Filter.initialize() Geometry.initialize() List.initialize() Number.initialize() String.initialize() Date.initialize() Dictionary.initialize() Terrain.initialize() _InitializeGeneratedClasses() _InitializeUnboundMethods()
class Gameplay: MIN_CAM_PLAYER_DISTANCE = 5 MAX_CAM_PLAYER_DISTANCE = 10 def __init__(self, base): self.base = base # hud self.label = addLabel(self.base, "?") # camera self.cam = self.base.camera def start(self): log.info("start...") # collisions self.base.cTrav = CollisionTraverser() #self.base.cTrav.showCollisions(self.base.render) #self.base.messenger.toggleVerbose() # objects self.terrain = Terrain(self.base) self.player = Player(self.base) self.player.actor.setPos(self.terrain.startPos) # self.placeZorritos() # self.terrain.plightP.reparentTo(self.player.actor) self.terrain.plightP.setPos(0, 3, 10) # camera self.cam.reparentTo(self.player.actor) self.cam.setPos(0, 4, 1.5) self.cam.lookAt(self.player.camNode) # task self.base.taskMgr.add(self.update, "gameplayUpdateTask") log.info("started.") def stop(self): log.info("stop...") self.base.taskMgr.remove("gameplayUpdateTask") self.player.destroy() self.terrain.destroy() log.info("stoped.") def update(self, task): self.label.setText( "Zorrito path finding behavior status is %s" % self.zorritos[0].aiBehaviors.behaviorStatus("pathfollow")) return task.cont def placeZorritos(self): self.zorritos = [] cantZorritos = 1 #int(len(self.terrain.zorritoStartPosList)/2) zorritosPosList = random.sample(self.terrain.zorritoStartPosList, cantZorritos) log.debug("placeZorritos:\n\t%(list)s" % {"list": str(self.terrain.zorritoStartPosList)}) for zorritoPos in zorritosPosList: zorrito = Zorrito(self.base, self.player) zorrito.actor.setPos(0, -20, 0) #zorritoPos) log.debug("zorrito pos is %s" % str(zorritoPos)) self.zorritos.append(zorrito)
def test_dijkstra(self): """Test dijkstras.""" grid = Grid(5) grid.create_grid() hexagon = Hex(-1, 1, 0) grid.get_hextile((0, 0, 0)).terrain = Terrain(TerrainType.MOUNTAIN, BiomeType.GRASSLAND) grid.get_hextile((0, 1, -1)).terrain = Terrain(TerrainType.MOUNTAIN, BiomeType.GRASSLAND) grid.get_hextile((-1, 0, 1)).terrain = Terrain(TerrainType.MOUNTAIN, BiomeType.GRASSLAND) result = [ Hex(-1, 1, 0), Hex(-1, 2, -1), Hex(-2, 2, 0), Hex(-2, 1, 1), Hex(0, 2, -2), Hex(2, 0, -2), Hex(2, -1, -1), Hex(-2, 0, 2), Hex(2, -2, 0), Hex(1, -2, 1), Hex(0, -2, 2) ] dijkstra = [x for x in grid.dijkstra(hexagon, 2)] result = set(result).difference(dijkstra) self.assertEqual(set(), result)
def __init__(self, width, height): Level.__init__(self, width, height) ##initialize blocks## boxtop = Terrain(20, -19, 40, 2, 0, 0,100, self, 0.5) boxleft= Terrain(-1,-5,2,30,0,0,100,self,0.5) boxbottom= Terrain(27.0,9.0,54.0,2.0,0.0,0.0,100,self,0.5) boxright= Terrain(55,-5,2,30,0,0,100,self,0.5) goal= Goal(53,5,1,5,0,0,100,self,0.5) b = Block(2, 2, 4, 1, 0, 0, 1, self, 0.5) c = Player(7, 5, 1, 2, 0, 0, 1, self, 0.5) d = Block(4, 2, 4, 1, 0, 5, 2, self, 0.5) a = GoalBlock(4, 5, 2, 2, 0, 5, 2, self, 0.5) m = Trampoline(30, -4, 2, 1, 0, 0, 1, self, 0.5) e = Spike(30.0, 7.5, 41.0, 1.0, 0.0, 0.0, 100, self, 0.1) f = Spike(29.0, 6.5, 1.0, 1.0, 0.0, 0.0, 100, self, 0.1) self.add_elem(c) self.add_elem(m) self.add_elem(b) self.add_elem(a) self.add_elem(d) self.add_elem(e) self.add_elem(f) self.add_elem(boxtop) self.add_elem(boxright) self.add_elem(boxbottom) self.add_elem(boxleft) self.add_elem(goal)
def setup(self): ''' Setting up the environment. ''' # Setting up space. self.space = pymunk.Space() self.space.gravity = GRAVITY self.space.sleep_time_threshold = 1 # Creating cars. self.cars = [] for _ in range(NUM_CARS): self.cars.append(BoxCar(self.space)) # Setting up terrain and checkpoints. self.terrain = Terrain(self.space) self.checkpoints = self.terrain.get_checkpoints() # Setting up extra UI elements. self.goal = arcade.create_line(self.checkpoints[-1].x - 40, self.checkpoints[-1].y, self.checkpoints[-1].x - 40, self.checkpoints[-1].y + 50, arcade.color.GREEN, 2) self.generation_number = 1 self.best_score = 0 self.plot_history = [] self.score_history = [] self.score_list = arcade.ShapeElementList()
def __init__(self, knot_points_per_phase, steps, total_duration, model='hopper', terrain='flat'): super().__init__() self.knot_points_per_phase = knot_points_per_phase self.num_phases = steps self.total_duration = total_duration if model == 'hopper': self.model = Hopper() self.time_phases = {} self.terrain = Terrain(type=terrain) self.opti = ca.Opti() self.q = {} self.qdot = {} self.u = {} self.p0 = {} # i = 0 self.dp0 = {} # i = 0 self.f10 = {} # i = 0 self.ceq = [] self.ciq = [] self.setVariables() self.setConstraints() self.setBounds()
def get_attack_targets( self, start: Tuple[int, int], terr: terrain.Terrain, steps: int, active_civ: int, shoot: bool, ) -> List[Spot]: s = set() q: Deque[Spot] = collections.deque() s.add(start) q.append(Spot(start, 0, None)) targets: List[Spot] = [] while len(q) > 0: spot = q.popleft() spr, civ = self.occupant(spot.tile) keep_going = True if spot.steps >= steps: keep_going = False if spot.steps > 0 and spr is not None: if not civ == active_civ: targets.append(spot) if not shoot: keep_going = False if keep_going: for neigh in terr.adjacent(spot.tile): if neigh in s: continue # Already been there if terr.tile(neigh) == 1 and not shoot: continue # Don't go on water s.add(neigh) q.append(Spot(neigh, spot.steps + 1, spot)) return targets
class GameScene(BaseScene): def __init__(self, director: Director) -> None: super().__init__(director) self.level = 1 self.terrain = Terrain() self.terrain.generate(self.level) self.player = Player(self.terrain.data) self.input_manager = InputManager() self.gradation_render = GradationRender() def update(self) -> None: self.player.update() self.input_manager.update() if self.player.state == "idle": move_keys = self.input_manager.move_keys if move_keys.left_key: self.player.move(Direction.LEFT) elif move_keys.right_key: self.player.move(Direction.RIGHT) elif move_keys.up_key: self.player.move(Direction.UP) elif move_keys.down_key: self.player.move(Direction.DOWN) def render(self) -> None: self.terrain.render(self.player.transform.draw_position) self.player.render() self.gradation_render.render(8)
def reset(self, level=1): pygame.mixer.music.stop() pygame.mixer.music.play(10**8) self.menu = Menu() self.menu.add_button('Continue', (self.width // 2 - 150, 200), target=self.open_menu) self.menu.add_button('Music', target=self.switch_music, switch=True) self.menu.add_button('Sounds', target=self.switch_sounds, switch=True) self.menu.add_button('Quit game', target=self.terminate) self.sprite_groups = {k: pygame.sprite.Group() for k in range(20, 30)} self.conditions = {k: False for k in range(40, 50)} self.conditions[RUNNING] = True self.conditions[FULLSCREEN] = True self.keys_pressed = [] self.terrain = Terrain(16 * 3 * 3, 16 * 3 * 3, level) self.sprite_groups[CHUNKS] = pygame.sprite.Group(self.terrain.chunks) for chunk in self.sprite_groups[CHUNKS]: self.sprite_groups[ALL].add(chunk) self.screen2 = pygame.Surface((self.width, self.height), pygame.HWSURFACE, 32) self.player = Player( (self.sprite_groups[ENTITIES], self.sprite_groups[ALL]), (500, 500)) self.camera = Camera(self.terrain.get_width(), self.terrain.get_height(), self.player, self.width // 2, self.height // 2) self.pathfinder = PathFinder(self.terrain.obst_grid) self.paths = dict() self.sprite_groups[PLAYER].add(self.player) self.camera.update()
def __init__(self, terrain_name): pygame.init() self.terrain = Terrain(terrain_name) self.window_size = [self.terrain.pixel_size[0] + 250, self.terrain.pixel_size[1] + 150] self.window = pygame.display.set_mode(self.window_size) self.init_content()
def __init__(self, director: Director) -> None: super().__init__(director) self.level = 1 self.terrain = Terrain() self.terrain.generate(self.level) self.player = Player(self.terrain.data) self.input_manager = InputManager() self.gradation_render = GradationRender()
def _create_terrain(self, terrain_number, terrain_type): """Create a terrain block """ terrain = Terrain(self, terrain_type) terrain_width, terrain_height = terrain.rect.size terrain.x = (terrain_width - 2) * terrain_number terrain.rect.x = terrain.x terrain.rect.y = 750 self.terrain_group.add(terrain)
def __init__(self, map_width, map_height, map_depth): """ Get the width, the height and the depth of the map """ self.map_width = map_width self.map_height = map_height self.map_depth = map_depth self.light_direction = (50000, 500, 500) # self.terrain = Terrain("Objects/ground/heightmap_squared.png", light_direction=self.light_direction, translate_y=-100, translate_x=-600, translate_z=-800, scale_total=8) self.terrain = Terrain("Objects/ground/heightmap.png", light_direction=self.light_direction, translate_y=-100, translate_x=-600, translate_z=-800, scale_total=8)
def initOsm(self, op, context, basePath, addonName): self.op = op self.assetPath = os.path.join(basePath, "assets") self.setDataDir(context, basePath, addonName) # create a sub-directory under <self.dataDir> for OSM files osmDir = os.path.join(self.dataDir, self.osmDir) if not os.path.exists(osmDir): os.makedirs(osmDir) # <self.logger> may be set in <setup(..)> self.logger = None # a Python dict to cache Blender meshes loaded from Blender files serving as an asset library self.meshes = {} self.setAttributes(context) addon = context.scene.blender_osm if addon.osmSource == "server": # find a file name for the OSM file osmFileName = self.osmFileName % "" counter = 1 while True: osmFilepath = os.path.realpath( os.path.join(osmDir, osmFileName) ) if os.path.isfile(osmFilepath): counter += 1 osmFileName = self.osmFileName % "_%s" % counter else: break self.osmFilepath = osmFilepath self.download( self.osmUrl % (app.minLon, app.minLat, app.maxLon, app.maxLat), osmFilepath ) else: self.osmFilepath = os.path.realpath(bpy.path.abspath(self.osmFilepath)) if self.loadMissingMembers: self.incompleteRelations = [] self.missingWays = set() if not app.has(defs.Keys.mode3d): self.mode = '2D' # check if have a terrain Blender object set terrain = Terrain(context) self.terrain = terrain if terrain.terrain else None if self.terrain: terrain.init() # manager (derived from manager.Manager) performing some processing self.managers = [] self.prepareLayers() if self.terrain and self.singleObject and not self.layered: print("Imported OpenStreetMap objects will be arranged into layers") self.layered = True # tangent to check if an angle of the polygon is straight Polygon.straightAngleTan = math.tan(math.radians( abs(180.-self.straightAngleThreshold) ))
def init(self): self.initStyles() self.initMaps() Terrain.initImages() Terrain.initSounds() self.initMenus() self.stopwatch = Stopwatch() self.initHelp() self.mode = "menu" self.menu = self.mainMenu
def main(): pg.init() a = pg.display.set_mode((800, 400)) testsurf = pg.surface.Surface((2, 2)) testsurf.fill(COLOURS['green']) t = Terrain('dirt', 'flattish') t_surf = t.build_surface() a.blit(t_surf, (0, 0)) print('blitted') #d = CharacterImage('test', WeaponDummy(testsurf), (0, 0), {}, {}) #d.start_thread((200, 100), a) print( CharacterImage.get_topleft_coord(t, *CharacterImage.find_closest_of( t, '*'))) truecoord = CharacterImage.find_closest_of( t, '*')[0], CharacterImage.find_closest_of(t, '*')[1] print( CharacterImage.get_topleft_coord(t, *truecoord), CharacterImage.get_topleft_coord(t, *CharacterImage.find_closest_of( t, '*'))) #s.start_thread(CharacterImage.get_topleft_coord(t, *CharacterImage.find_closest_of(t, '#')), a) # for i in range(100): # i = CharacterImage('test', WeaponDummy(testsurf), (0,0), {}, {}) # i.start_thread((0, 0 ), a) pause = events.Pause() s = CharacterImage('test', WeaponDummy(testsurf), CharacterImage.get_topleft_coord(t, *truecoord), {}, {}) print(CharacterImage.get_topleft_coord(t, *truecoord)) s.start_thread(800, a) while True: #a.blit(PICS['Maps']['army'], CharacterImage.get_topleft_coord(t, *CharacterImage.find_closest_of(t, '*'))) #s.build_image(a) for i in pg.event.get(): if i.type == QUIT: print('hello?') # cleanup and saving and stuff like that can go here, but for now time.sleep tests it. # always remove the pause from _internal_events before putting Quit os._exit(0) #import time; time.sleep(1) try: pg.display.update() a.fill(COLOURS['black']) a.blit(t_surf, (0, 0)) except pg.error: # os._exit is about to be called in a seperate thread pass print('updated') CLOCK.tick(FPS)
class Dungeon: def __init__(self, player): self.player = player self.terrain = Terrain() self.level = 1 def generate(self): self.terrain.generate(self.level) def render(self): self.terrain.render(self.player.position.x, self.player.position.y)
def __init__(self, window, gamers): self.terrain = Terrain(1200) self.worms = [] self.gamers = gamers for i in range(len(gamers)): self.worms += [ Worm(300 + i * 200, self.terrain.get_level(300 + i * 200) + 5, gamers[i], i) ] self.rockets = [] self.window = window self.control = []
def __init__(self, width, height): Level.__init__(self, width, height) ##initialize blocks## boxtop = Terrain(20, -19, 40, 2, 0, 0, 100, self, 0.5) boxleft = Terrain(-1, -5, 2, 30, 0, 0, 100, self, 0.5) boxbottom = Terrain(20, 9, 40, 2, 0, 0, 100, self, 0.5) boxright = Terrain(41, -5, 2, 30, 0, 0, 100, self, 0.5) goal = Goal(38, 5, 1, 5, 0, 0, 100, self, 0.5) b10 = Block(1, 7, 2, 2, 0, 0, 1, self, 0.5) b20 = Block(3, 7, 2, 2, 0, 0, 1, self, 0.5) b30 = Block(5, 7, 2, 2, 0, 0, 1, self, 0.5) b40 = Block(7, 7, 2, 2, 0, 0, 1, self, 0.5) b50 = Block(9, 7, 2, 2, 0, 0, 1, self, 0.5) b11 = Block(1, 5, 2, 2, 0, 0, 1, self, 0.5) b21 = Block(3, 5, 2, 2, 0, 0, 1, self, 0.5) b31 = Block(5, 5, 2, 2, 0, 0, 1, self, 0.5) b41 = Block(7, 5, 2, 2, 0, 0, 1, self, 0.5) b51 = Block(9, 5, 2, 2, 0, 0, 1, self, 0.5) b12 = Block(1, 3, 2, 2, 0, 0, 1, self, 0.5) b22 = Block(3, 3, 2, 2, 0, 0, 1, self, 0.5) b32 = Block(5, 3, 2, 2, 0, 0, 1, self, 0.5) b42 = Block(7, 3, 2, 2, 0, 0, 1, self, 0.5) b52 = Block(9, 3, 2, 2, 0, 0, 1, self, 0.5) p = Player(15, 5, 1, 2, 0, 0, 1, self, 0.5) g = GoalBlock(17, 5, 2, 2, 0, 0, 2, self, 0.5) barrier = Terrain(35, -3, 1, 22, 0, 0, 100, self, 0.5) self.add_elem(p) self.add_elem(b10) self.add_elem(b20) self.add_elem(b30) self.add_elem(b40) self.add_elem(b50) self.add_elem(b11) self.add_elem(b21) self.add_elem(b31) self.add_elem(b41) self.add_elem(b51) self.add_elem(b12) self.add_elem(b22) self.add_elem(b32) self.add_elem(b42) self.add_elem(b52) self.add_elem(barrier) self.add_elem(g) self.add_elem(boxtop) self.add_elem(boxright) self.add_elem(boxbottom) self.add_elem(boxleft) self.add_elem(goal)
def on_draw(self): self.draw_number += 1 glLoadIdentity() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.camera.draw() shape = self.shape terrain = Terrain(self.textures[0], shape) mat = terrain.get_example_mat(20, 20) import matTerrian matTerrian.draw(texture=terrain.sand_texture, mat=mat)
def test_shortest_path(self): """Test shortest path.""" grid = Grid(5) grid.create_grid() start = Hex(-1, 1, 0) end = Hex(1, -1, 0) grid.get_hextile((0, 0, 0)).terrain = Terrain(TerrainType.MOUNTAIN, BiomeType.GRASSLAND) grid.get_hextile((0, 1, -1)).terrain = Terrain(TerrainType.MOUNTAIN, BiomeType.GRASSLAND) grid.get_hextile((-1, 0, 1)).terrain = Terrain(TerrainType.MOUNTAIN, BiomeType.GRASSLAND) result = [Hex(-1, 2, -1), Hex(2, -2, 0), Hex(1, -1, 0)] self.assertEqual(grid.shortest_path(start, end, 3), result)
def initializeGL(self): GL.glClearColor(0.50, 0.50, 0.50, 1.0) self.heightMap = HeightMap('textures/atacama_height2.png') self.projection = QMatrix4x4() self.projection.perspective(self.fov, self.width / self.height, 0.01, 10000) self.cameraPos = QVector3D(0.0, 1.0, 1.0) self.terrainPos = QVector3D(0.0, 0.0, 0.0) self.roverPos = QVector3D(0.0, 0.0, 0.0) print(GL.glGetString(GL.GL_VERSION)) self.camera = Camera(self.cameraPos, self.heightMap) self.terrain = Terrain(self.terrainPos, self.heightMap) self.mask = np.zeros([1001, 1001]) self.terrain.updateRewards(self.mask)
def addTerrainType(self, tile = None): if tile: x = tile.id() else: x = -1 terrain = Terrain(self.mTileset.terrainCount(), self.mTileset, QString(), x) terrain.setName(self.tr("New Terrain")) self.mMapDocument.undoStack().push(AddTerrain(self.mMapDocument, terrain)) # Select the newly added terrain and edit its name index = self.mTerrainModel.index(terrain) selectionModel = self.mUi.terrainList.selectionModel() selectionModel.setCurrentIndex(index, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows) self.mUi.terrainList.edit(index)
def test_movement_cost_of_path(self): """Test the movement_cost_of_path function.""" civ = Civilisation("myCiv", grid, logger) hextile = Hex(0, 0, 0) hextile2 = Hex(1, 0, -1) hextile3 = Hex(1, 1, -2) hextile._terrain = Terrain(TerrainType.FLAT, BiomeType.GRASSLAND) hextile2._terrain = Terrain(TerrainType.HILL, BiomeType.GRASSLAND) hextile3._terrain = Terrain(TerrainType.HILL, BiomeType.DESERT) # costs are 1, 2 and 3 respectively hexes = [hextile, hextile2, hextile3] archer = Archer(1, 1, hextile, "myCiv") archer.actions = 2 cost = civ.movement_cost_of_path(hexes) self.assertEqual(cost, 6)
def importTerrain(self, context): verts = [] indices = [] try: heightOffset = Terrain(context).terrain["height_offset"] except Exception: heightOffset = None minHeight = self.buildTerrain(verts, indices, heightOffset) # apply the offset along z-axis for v in verts: v[2] -= minHeight # create a mesh object in Blender mesh = bpy.data.meshes.new("Terrain") mesh.from_pydata(verts, [], indices) mesh.update() obj = bpy.data.objects.new("Terrain", mesh) obj["height_offset"] = minHeight context.scene.objects.link(obj) context.scene.blender_osm.terrainObject = obj.name # force smooth shading obj.select = True context.scene.objects.active = obj bpy.ops.object.shade_smooth()
def __init__(self, queue, door_coords): self.agent_queue = queue source = Human_source(1500) event_list = [ Generator('0_0', door_coords[0][0], source, 3), Generator('0_1', door_coords[0][1], source, 3), Generator('0_2', door_coords[0][2], source, 3), Generator('0_3', door_coords[0][3], source, 3), Generator('1_0', door_coords[1][0], source, 3), Generator('1_1', door_coords[1][1], source, 3), Generator('2_0', door_coords[2][0], source, 3), Generator('3_0', door_coords[3][0], source, 3), Generator('4_0', door_coords[4][0], source, 3), Generator('5_0', door_coords[5][0], source, 3) ] for area, timming, initial_light in grid_info.traffic_lights : green,red = timming green,red = green*grid_info.FPS, red*grid_info.FPS light = Traffic_light(area, (green,red), initial_light) event_list.append(light) self.engine = Engine(terrain = Terrain("grid_bits.txt"), initial_event_list = event_list) super(Simulator, self).__init__()
async def on_start(self): self.terrain: Terrain = Terrain(self) self.creep_manager: CreepManager = CreepManager(self, self.terrain) await self.terrain.store_map_feature_coordinates() await self.terrain.calculate_expansion_path_distances() await self.map_chunks()
def on_init(self): pygame.init() self.screen = pygame.display.set_mode( self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) # Fill background and blits everything to the screen self.background = pygame.Surface(self.size) self.background = self.background.convert() self.background.fill(BG_COLOR) self.screen.blit(self.background, (0, 0)) pygame.display.flip() self.terrain = Terrain() self.beaver = Beaver() self.beaversprite = pygame.sprite.RenderPlain(self.beaver) self.generationtime = pygame.time.get_ticks() self.brain = Brain() self.brain.environment.setbeaver(self.beaver) self.wolf = Wolf() self.wolfsprite = pygame.sprite.RenderPlain(self.wolf) self._clock = pygame.time.Clock() self._running = True
def fight(tribes, terrain=None): results = [] for tribe in tribes: opponent = random.choice(tribes) terrain = terrain or Terrain() results.append(terrain.pit(tribe, opponent)) return results
def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) pyglet.clock.schedule_interval(self.update, 1./60) self.strafe = [0, 0] def fps(dt): print 'FPS is %f' % pyglet.clock.get_fps() pyglet.clock.schedule_interval(fps, 2) # Current (x, y, z) position in the world, specified with floats. Note # that, perhaps unlike in class, the y-axis is the vertical axis. self.position = (12, 8, 12) self.press = {} self.press["light"] = 0 # First element is rotation of the player in the x-z plane (ground # plane) measured from the z-axis down. The second is the rotation # angle from the ground plane up. Rotation is in degrees. # # The vertical plane rotation ranges from -90 (looking straight down) to # 90 (looking straight up). The horizontal rotation range is unbounded. self.rotation = (0, 0) self.reticle = None self.t = Terrain(a=33,water_line=1.5,generate=False) self.spin = 180 self.fps = pyglet.clock.ClockDisplay() #self.skybox = SkyBox.fromDir("../example/texture/bluesky", "bluesky") #self.skybox = SkyBox.fromDir("../example/texture/lake2", "jajlake2") self.kostka = Kostka(self.t)
def __init__(self, knot_points_per_phase, steps, total_duration, model='biped', terrain='flat'): super().__init__() self.knot_points_per_phase = knot_points_per_phase self.num_phases = steps self.total_duration = total_duration if model == 'biped': self.model = Biped1() self.time_phases = {'Left Leg': {}, 'Right Leg': {}} self.terrain = Terrain(type=terrain) self.opti = ca.Opti() self.lq = {} self.lqdot = {} # self.lqddot = {} self.rq = {} self.rqdot = {} # self.rqddot = {} self.tq = {} self.tqdot = {} # self.tqddot = {} self.u = {} self.lpos = {} # i = 0 self.dlpos = {} # i = 0 self.ddlpos = {} # i = 0 self.lforce = {} # i = 0 self.rpos = {} # i = 1 self.drpos = {} # i = 1 self.ddrpos = {} # i = 1 self.rforce = {} # i = 1 self.setVariables() self.setConstraints()
def nextLevel(self): # Update and save progress saved = self.progress[self.level] if saved["score"] == None or self.score > saved["score"]: saved["score"] = self.score duration = self.stopwatch.getSeconds() if saved["time"] == None or duration < saved["time"]: saved["time"] = duration self.progress.save() # Load next level Terrain.playSound("happy") index = self.maps.levels.index(self.level) + 1 if index >= len(self.maps.levels): self.mode = "win" else: self.level = self.maps.levels[index] self.loadLevel()
def addTerrainType(self, tile=None): if tile: x = tile.id() else: x = -1 terrain = Terrain(self.mTileset.terrainCount(), self.mTileset, QString(), x) terrain.setName(self.tr("New Terrain")) self.mMapDocument.undoStack().push( AddTerrain(self.mMapDocument, terrain)) # Select the newly added terrain and edit its name index = self.mTerrainModel.index(terrain) selectionModel = self.mUi.terrainList.selectionModel() selectionModel.setCurrentIndex( index, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows) self.mUi.terrainList.edit(index)
class World: def __init__(self, server, path): self.server = server self.chunks = {} self.entities = [] self.spawnPoint = (8, 150, 8) #todo: use data from level.dat self.path = path def populate(self): if not os.path.exists(self.path): os.mkdir(self.path) if os.path.exists('%s/level.dat' % self.path): cantLoad = False f = open('%s/level.dat' % self.path, 'r') try: json.loads(f.read()) except: cantLoad = True self.server.log.error('level.dat unreadable or unparsable - resetting') f.close() defaults = {'seed': random.randrange(-9999999, 9999999), 'time': 0, 'name': '' } if not os.path.exists('%s/level.dat' % self.path) or cantLoad: f = open('%s/level.dat' % self.path, 'w') f.write(json.dumps(defaults)) f.close() f = open('%s/level.dat' % self.path, 'r') self.level = json.loads(f.read()) f.close() self.terrain = Terrain(self.level['seed']) #for x in range(16): # row = [] # for z in range(16): # row.append(self.terrain.generate(x, z)) # self.chunks.append(row) #print self.chunks[0][0].blocks[0][0][0] def touch(self, x, z): # same as unix touch command, basically creates a chunk file if it doesn't exist, otherwise keeps it try: self.chunks[x][z] except: if os.path.exists('%s/chunks/%s,%s' % (self.path, str(x), str(z))): self.parseChunk(x, z) else: if x in self.chunks: self.chunks[x] = {} self.chunks[x][z] = self.terrain.generate(x, z) return self.chunks[x][z] def flush(self): f = open('%s/level.dat' % self.path, 'w') f.write(json.dumps(self.level)) f.close() def loop(self): self.server.log.info('World tick loop begin') while not self.server.abort: self.level['time'] += 1 time.sleep(.05) # 20 ticks/second is 1/20 (.05) seconds per tick
def __init__(self, maze_dim): """ Used to set up attributes that the robot will use to learn and navigate the maze. """ # Position-related attributes self.robot_pos = {'location': [0, 0], 'heading': 'up'} # Current pos self.steps_first_round = 0 self.steps_final_round = 0 self.maze_dim = maze_dim self.maze_representation = None # Goal-related attributes center = maze_dim/2 self.center_locations = [ [center, center], [center - 1, center], [center, center - 1], [center - 1, center - 1]] self.reached_destination = False # For exploring state self.exploring = False self.steps_exploring = 0 self.consecutive_explored_cells = 0 # Initialize terrain self.terrain = Terrain(maze_dim) # Algorithm to use: self.algorithm = None if str(sys.argv[2]).lower() == 'ff': self.algorithm = FloodFill() elif str(sys.argv[2]).lower() == 'ar': self.algorithm = AlwaysRight() elif str(sys.argv[2]).lower() == 'mr': self.algorithm = ModifiedRight() else: raise ValueError( "Incorrect algorithm name. Options are: " "\n- 'ff': flood-fill" "\n- 'ar': always-right" "\n- 'mr': modified-right (prefers unvisited cells)" ) # Explore after reaching center of the maze: if str(sys.argv[3]).lower() == 'true': self.explore_after_center = True elif str(sys.argv[3]).lower() == 'false': self.explore_after_center = False else: raise ValueError( "Incorrect explore value: Options are: " "\n- 'true': to keep exploring after reaching the center" "\n- 'false': to end run immediately after reaching the center" )
class TerrainMain: def __init__ ( self ): #dict with the curve name as index self.terrain = [] #the curve name will always be rCurve + index ( ie rCurve0 ) self.rCurveName = 'rCurve' self.currentTerrain = None self.newTerrain() def newTerrain( self ): self.currentTerrain = Terrain( self.rCurveName + str(len(self.terrain)) ) print self.currentTerrain.rCurveName self.terrain.append( self.currentTerrain ) self.currentTerrain.createRiver () def reloadModule( self ): import terrain reload( terrain ) from terrain import Terrain
def Reset(): """Reset the library. Useful for re-initializing to a different server.""" data.reset() ApiFunction.reset() Element.reset() Image.reset() Feature.reset() Collection.reset() ImageCollection.reset() FeatureCollection.reset() Filter.reset() Geometry.reset() List.reset() Number.reset() String.reset() Date.reset() Dictionary.reset() Terrain.reset() _ResetGeneratedClasses() global Algorithms Algorithms = _AlgorithmsContainer()
def __init__(self): self.window = pyglet.window.Window(fullscreen=True) self.terrain = Terrain(self.window.width, self.window.height-100) self.players = [ Player(name, self, i) for i, name in enumerate(sys.argv[1:])] self.moving = [] # Setup events self.window.event(self.on_draw) Game.register_event_type('next_player') Game.register_event_type('start_moving') Game.register_event_type('stop_moving') Game.register_event_type('explosion') # Start the game. self.reset() # Run the f****r pyglet.app.run()
def __init__(self, terrain, heuristic): self.terrain = Terrain(terrain) self.directions = {'N': (0, -1), 'E': (1, 0), 'S': (0, 1), 'W': (-1, 0)} self.start_node = Node(self.terrain.get_start_position(), 'N', 0) # Push our start position onto the heap self.search_heap = SearchHeap(initial=[self.start_node], g_func=lambda node: node.g, h_func=heuristic, goal=self.terrain.get_goal_position()) self.visited = [] self.position = list(self.terrain.get_start_position()) self.facing = 'N' self.action_costs = {'forward': lambda cost: -cost, 'bash': lambda cost: -3, 'turn': lambda cost: -ceil(float(cost)/float(3)), 'demolish': lambda cost: -4} print "goal position:" print self.terrain.get_goal_position()
def on_key_press( self, symbol, modifier ): global piece, bottom if symbol == key.A: self.strafe[1] -= 1 elif symbol == key.W: self.strafe[0] -= 1 elif symbol == key.S: self.strafe[0] += 1 elif symbol == key.D: self.strafe[1] += 1 elif symbol == key.UP : self.kostka.speed += .1 elif symbol == key.DOWN : self.kostka.speed -= .1 elif symbol == key.LEFT : self.kostka.input[0] = True elif symbol == key.RIGHT : self.kostka.input[1] = True elif symbol == key.F : global WIREFRAME WIREFRAME = not WIREFRAME if WIREFRAME : glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) else : glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) elif symbol == key.N : self.t = Terrain(water_line=1.5,generate=True) elif symbol == key.Q : exit(0) elif symbol == key.ESCAPE: self.set_exclusive_mouse(False) elif symbol == key.O : self.press["light"] = 1 elif symbol == key.P : self.press["light"] = -1
def setUp(self): """ set up data used in the tests. setUp is called before each test function execution. """ pygame.init() pygame.display.set_mode([Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT]) self.input = Input() self.terrain = Terrain() self.teamName = "EJteam" self.team = Team(self.teamName) self.team.setGravity(Direction.DOWN) self.team.hasTurn = True TurnManager().status = TurnStatus.CURRENTTURN TurnManager().teams = [] TurnManager().teams.append(self.team) self.snail = Snail(self.team) self.snail.hasTurn = True
def __init__(self, screen, sfx, rand): self.level = 1 self.ship_type = 1 # 0, 1, 2 self.screen = screen self.sfx = sfx self.terrain = Terrain() self.myship = MyShip(self.ship_type) self.enemy_list = [] self.my_bullet_list = [] self.enemy_bullet_list = [] self.powerup_list = [] self.explosion_list = [] self.milage = RESOLUTION[1] self.rand = rand self.level_dat_path = LEVEL_PATH + '%02d.dat' % self.level self.level_dat = open(self.level_dat_path).readlines() self.next_pos = int(self.level_dat[0].split()[0]) self.status = 'game' sfx.play_bgm() if DEBUG: print 'init : battlefield'
def timerFiredPlay(self): if (self.ball.x < self.maps.left or self.ball.x > self.maps.left + self.maps.width or self.ball.y < self.maps.top or self.ball.y > self.maps.top + self.maps.height): # Ball off map self.killBall() collided = pygame.sprite.spritecollide(self.ball, self.terrain, False, Terrain.collidedFn) if len(collided) > 0: elements = Terrain.manageCollision(self.ball, collided) for element, direction in elements: result = element.interactFromDir(self.ball, direction) if result == "score": self.score += element.points elif result == "win": self.nextLevel() elif result == "fly": self.ballFly(self.ball, element) elif result == "kill": self.killBall() self.ball.update(self.isKeyPressed)
def populate(self): if not os.path.exists(self.path): os.mkdir(self.path) if os.path.exists('%s/level.dat' % self.path): cantLoad = False f = open('%s/level.dat' % self.path, 'r') try: json.loads(f.read()) except: cantLoad = True self.server.log.error('level.dat unreadable or unparsable - resetting') f.close() defaults = {'seed': random.randrange(-9999999, 9999999), 'time': 0, 'name': '' } if not os.path.exists('%s/level.dat' % self.path) or cantLoad: f = open('%s/level.dat' % self.path, 'w') f.write(json.dumps(defaults)) f.close() f = open('%s/level.dat' % self.path, 'r') self.level = json.loads(f.read()) f.close() self.terrain = Terrain(self.level['seed'])
class Game: def __init__(self): self._running = True self.screen = None self.size = self.width, self.height = SCREEN_WIDTH, SCREEN_HEIGHT def on_init(self): pygame.init() self.screen = pygame.display.set_mode( self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) # Fill background and blits everything to the screen self.background = pygame.Surface(self.size) self.background = self.background.convert() self.background.fill(BG_COLOR) self.screen.blit(self.background, (0, 0)) pygame.display.flip() self.terrain = Terrain() self.beaver = Beaver() self.beaversprite = pygame.sprite.RenderPlain(self.beaver) self.generationtime = pygame.time.get_ticks() self.brain = Brain() self.brain.environment.setbeaver(self.beaver) self.wolf = Wolf() self.wolfsprite = pygame.sprite.RenderPlain(self.wolf) self._clock = pygame.time.Clock() self._running = True def on_event(self, event): if event.type == pygame.QUIT: self._running = False def on_loop(self): self.beaver.seteyeview(self.terrain.terraingroup) self.beaversprite.update() self.brain.experiment.doInteractions(1) self.wolf.seteyeview(self.terrain.terraingroup) self.wolf.setscentview(self.beaver) #self.wolfsprite.update() marsh = self.terrain.getmarsh() if (self.beaver.action == Constants.BEAVER_ACTION_DROP_LUMBER and self.beaver.droppedlumber and pygame.sprite.collide_rect(self.beaver, marsh)): marsh.improve() marsh.update() # Reset the wolf if it gets stuck in marsh if pygame.sprite.collide_rect(self.wolf, marsh): self.wolf.respawn() if (self.beaver.energy <= 0 or self.beaver.rect.colliderect(self.wolf.rect)): temp = pygame.time.get_ticks() # Only when beaver starves if self.beaver.energy <= 0: generationtimes.append("%d\t%d" % (self.beaver.generationcount, temp - self.generationtime)) self.generationtime = temp self.beaver.respawn() self.brain.agent.learn() self.brain.agent.reset() if self.beaver.generationcount > NUM_GENERATIONS: self._running = False # Reset the wolf so that it seems as if time has passed # (aka wolf not lurking around marsh on beaver spawn) self.wolf.respawn() # Reset the environment so beavers start alike. marsh.respawn() self.terrain.respawntrees() else: tree = pygame.sprite.spritecollideany(self.beaver, self.terrain.gettreelist()) if tree is not None and not isinstance(tree, Marsh): # Check beaver state if self.beaver.action == Constants.BEAVER_ACTION_EAT: tree.setstate(Constants.TREE_STATE_ATE) tree.update() elif (self.beaver.action == Constants.BEAVER_ACTION_PICK_UP_LUMBER and self.beaver.pickeduplumber): tree.setstate(Constants.TREE_STATE_FORAGED) tree.update() # Check tree state if tree.health <= 0: self.terrain.respawntree(tree) def on_render(self): self.background.fill(BG_COLOR) self.screen.blit(self.background, (0, 0)) # Draws beaver, wolf, marsh, and tree sprites self.terrain.terraingroup.draw(self.screen) self.beaversprite.draw(self.screen) self.wolfsprite.draw(self.screen) # Draws energy and health bars of beaver and trees bx, by = self.beaver.rect.topleft brect = pygame.Rect(bx, by, self.beaver.energybar, HEALTHBAR_HEIGHT) pygame.draw.rect(self.screen, HEALTHBAR_COLOR, brect, 0) for sprite in self.terrain.terraingroup: sx, sy = sprite.rect.topleft srect = pygame.Rect(sx, sy, sprite.healthbar, HEALTHBAR_HEIGHT) pygame.draw.rect(self.screen, HEALTHBAR_COLOR, srect, 0) # Inefficient but works w/o hacking up a blit function for transparent imgs pygame.display.update() self._clock.tick(FRAMERATE) def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while (self._running): for event in pygame.event.get(): self.on_event(event) self.on_loop() self.on_render() self.on_cleanup()
class Game(DirectObject): def __init__(self): #the window props wp = WindowProperties.getDefault() wp.setUndecorated(False) wp.setFullscreen(False) wp.setSize(cfg['win-size'][0], cfg['win-size'][1]) wp.setOrigin(-2,-2) wp.setFixedSize(False) wp.setTitle("Grass and Gas - wezu -PyWeek 21") #open the window base.openMainWindow(props = wp) base.setBackgroundColor(0, 0, 0, 1) base.disableMouse() self.mode=DRIVING #make sure the config is ok cfg['hardware-skinning']=ConfigVariableBool('hardware-skinning', True).getValue() cfg['srgb']=ConfigVariableBool('framebuffer-srgb', False).getValue() cfg['win-size']=[ConfigVariableInt('win-size', '640 480').getWord(0), ConfigVariableInt('win-size', '640 480').getWord(1)] cfg['music-volume']=ConfigVariableInt('music-volume', '50').getValue() cfg['sound-volume']=ConfigVariableInt('sound-volume', '100').getValue() cfg['key-forward']=ConfigVariableString('key-forward','w').getValue() cfg['key-back']=ConfigVariableString('key-back','s').getValue() cfg['key-left']=ConfigVariableString('key-left','a').getValue() cfg['key-right']=ConfigVariableString('key-right','d').getValue() cfg['key-jump']=ConfigVariableString('key-jump','space').getValue() cfg['key-cut-grass']=ConfigVariableString('key-cut-grass','shift').getValue() cfg['key-enter-exit-car']=ConfigVariableString('key-enter-exit-car','tab').getValue() cfg['shadow-size']=ConfigVariableInt('shadow-size',1024).getValue() cfg['shadow-area']=ConfigVariableInt('shadow-area',50).getValue() self.accept('escape', self.doExit) self.accept('f1', self.hideHelp) self.accept(cfg['key-jump'], self.doFlip) self.accept( cfg['key-enter-exit-car'], self.changeMode) self.accept(cfg['key-cut-grass'], self.shear) self.accept( 'window-event', self.onWindowEvent) inputState.watchWithModifiers('forward', cfg['key-forward']) inputState.watchWithModifiers('reverse', cfg['key-back']) inputState.watchWithModifiers('turnLeft', cfg['key-left']) inputState.watchWithModifiers('turnRight', cfg['key-right']) # Task taskMgr.add(self.update, 'updateWorld') taskMgr.doMethodLater(5.0, self.countGrass, 'grass_counter') # Physics self.setup() # _____HANDLER_____ def hideHelp(self): if self.hud.help_frame.isHidden(): self.hud.help_frame.show() else: self.hud.help_frame.hide() def doExit(self): self.cleanup() sys.exit(1) def doReset(self): self.cleanup() self.setup() def toggleWireframe(self): base.toggleWireframe() def toggleTexture(self): base.toggleTexture() def toggleDebug(self): if self.debugNP.isHidden(): self.debugNP.show() else: self.debugNP.hide() def doScreenshot(self): base.screenshot('Bullet') def onWindowEvent(self,window=None): if window is not None: # window is none if panda3d is not started self.filters.update() self.hud.updateGuiNodes() def countGrass(self, task): current=self.grass.getStatus() if self.grass_to_cut ==0: self.grass_to_cut=current if current == 0: return v= (float(current)/float(self.grass_to_cut)) #print self.grass_to_cut, current self.hud.counter['text']= str(int(v*100.0))+"%" return task.again def update(self, task): dt = globalClock.getDt() if self.mode==DRIVING: self.car.drive(dt) self.hud.showSpeed(self.car.getKmph()) self.hud.showFuel(self.car.fuel) self.grass.setMowerPos(self.car.blade_node) self.hud.grradar_display['frameTexture']=self.grass.gradar['tex'] node_to_follow=self.car.node speed=0.3 elif self.mode==WALKING: self.char.walk(dt) node_to_follow=self.char.actor_node speed=0.03 self.world.doPhysics(dt, 10, 0.001) if self.mode!=EXITING: self.camera.follow(node_to_follow, dt, speed) self.sun_sky.sun_node.setPos(self.camera.cam_node.getPos(render)) return task.cont def cleanup(self): self.world = None self.worldNP.removeNode() def _setMode(self, mode): self.mode=mode #self.camera.zoomIn() def changeMode(self): if self.mode==DRIVING: if self.car.stopEngine(): self.car.exitCar() self.char.exitCar(self.car.node) #self.char.getOutOfCar(self.car.node) Sequence(Wait(3.6), Func(self._setMode, WALKING)).start() self.mode=EXITING #self.camera.zoomIn() self.hud.hide() self.driving_music.stop() self.walking_music.play() elif self.mode==WALKING: if abs(self.char.node.getDistance(self.car.node))<2.0: #if self.char self.mode=DRIVING #self.camera.zoomOut() self.hud.show() self.char.enterCar() self.car.enterCar() self.driving_music.play() self.walking_music.stop() #self.car.node.node().setMass(self.car.mass) def doFlip(self): if self.mode==DRIVING: self.car.flip() self.grass.getStatus() if self.mode==WALKING: self.char.jump() def shear(self): if self.mode==DRIVING: if self.car.blade_spining: self.car.blade_spining=False self.grass.mower_blade.hide() else: self.car.blade_spining=True self.grass.mower_blade.show() def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.hide() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Plane #shape = BulletPlaneShape(Vec3(0, 0, 1), 0) #mesh = BulletTriangleMesh() #geomNodes = loader.loadModel('levels/test1/collision').findAllMatches('**/+GeomNode') #geomNode = geomNodes.getPath(0).node() #geom = geomNode.getGeom(0) #mesh.addGeom(geom) #shape = BulletTriangleMeshShape(mesh, dynamic=False, bvh=True ) #np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) #np.node().addShape(shape) #np.setPos(0, 0, 20.0) #np.setCollideMask(BitMask32.allOn()) #self.world.attachRigidBody(np.node()) #sky dome self.sun_sky=Sky() self.sun_sky.setTime(17.0) #terrain self.ground=Terrain(self.world, self.worldNP) self.ground.loadMesh(path+'levels/gandg2/collision') self.ground.setMaps(path+'levels/gandg2/') self.ground.setTextures((39, 1, 2, 15, 4, 5)) #grass self.grass=Grass() self.grass.setMap(path+'levels/gandg2/grass.png') self.grass_to_cut=self.grass.getStatus() # Car self.car=Car(self.world, self.worldNP) self.car.setPos(161.0,160.0,26) #camera self.camera=FlyingCamera() #car to character scale 0.0128 self.char=Character(self.world, self.worldNP) self.char.enterCar() #self.char.setPos(256, 250, 80) #filter manager, post process self.filters=Postprocess() #self.filters.setupFxaa() #no time to make it work, sorry... self.filters.setupFilters() #map objects .. hardcoded because of time self.object_root=render.attachNewNode('object_root') obj=[ (path+'models/pyweek_wall1',0.0,(303.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(301.0,405.0,25.0980434417725),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(299.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(297.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(295.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(293.0,405.0,25.0980434417725),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(291.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(289.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(287.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(285.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(283.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(281.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(281.0,385.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(283.0,385.0,25.0980453491211),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(285.0,385.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,404.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,402.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,400.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,398.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,396.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,394.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,392.0,25.237850189209),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,404.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,398.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,396.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,394.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,392.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,390.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,388.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,386.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(286.0,386.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(286.0,388.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(286.0,390.0,25.0980434417725),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(287.0,391.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(289.0,391.0,25.1190624237061),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(291.0,391.0,25.1960334777832),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(293.0,391.0,25.1596641540527),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(295.0,391.0,25.2697868347168),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(297.0,391.0,25.3282146453857),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(299.0,391.0,25.3496627807617),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(301.0,391.0,25.2688617706299),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(303.0,391.0,25.2534332275391),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,402.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_box',0.0,(279.600006103516,401.700012207031,25.0980415344238),None), (path+'models/pyweek_box',0.0,(279.399993896484,402.200012207031,25.0980415344238),None), (path+'models/pyweek_box',0.0,(279.600006103516,402.700012207031,25.0980415344238),None), (path+'models/pyweek_box',0.0,(279.399993896484,403.399993896484,25.0980415344238),None), (path+'models/pyweek_box',0.0,(278.799987792969,402.799987792969,25.0980415344238),None), (path+'models/pyweek_box',0.0,(278.799987792969,402.100006103516,25.0980415344238),None), (path+'models/pyweek_box',0.0,(279.0,401.5,25.0980415344238),None), (path+'models/pyweek_box',0.0,(278.5,401.600006103516,25.0980415344238),None), (path+'models/pyweek_box',0.0,(278.799987792969,401.899993896484,25.5980415344238),None), (path+'models/pyweek_box',90.0,(279.5,402.600006103516,25.5980415344238),None), (path+'models/pyweek_box',90.0,(279.0,402.5,25.5980415344238),None), (path+'models/pyweek_box',90.0,(279.399993896484,402.0,25.5980415344238),None), (path+'models/pyweek_box',90.0,(278.100006103516,402.299987792969,25.0980415344238),None), (path+'models/pyweek_box',90.0,(277.799987792969,401.700012207031,25.0980415344238),None), (path+'models/pyweek_box',90.0,(278.200012207031,401.899993896484,25.5980415344238),None), (path+'models/pyweek_box',90.0,(279.399993896484,402.399993896484,26.0980415344238),None), (path+'models/pyweek_box',90.0,(279.0,401.899993896484,26.0980415344238),None), (path+'models/pyweek_box',90.0,(278.799987792969,402.399993896484,26.0980415344238),None) ] for i in obj: loadObject(model=i[0], H=i[1], pos=i[2], world=self.world, worldNP=self.worldNP, root=self.object_root, collision_solid=i[3]) self.object_root.flattenStrong() #models/pyweek_gate,90.0,(280.0,399.0,25.0980415344238)) #gui self.hud=HUD() #volume sfxMgr = base.sfxManagerList[0] sfxMgr.setVolume(cfg['sound-volume']*0.01) musicMgr = base.musicManager musicMgr.setVolume(cfg['music-volume']*0.01) #music self.driving_music=loader.loadMusic(path+'music/driving.ogg') self.driving_music.setLoop(True) self.driving_music.play() self.walking_music=loader.loadMusic(path+'music/walking.ogg') self.walking_music.setLoop(True) print self.char.actor.getScale(render)
def __call__(self): """Actually build the Minecraft world that corresponds to a tile.""" if self.skip == True: self.log.log_info("Skipping extant tile %dx%d" % (self.tilex, self.tiley)) self.world = mclevel.MCInfdevOldLevel(self.tiledir) peak = self.world.playerSpawnPosition() self.peak = peak[1] - 2 del self.world return self.peak # calculate offsets ox = (self.tilex-self.tiles['xmin'])*self.size oy = (self.tiley-self.tiles['ymin'])*self.size sx = self.size sy = self.size # load arrays from map file mapds = gdal.Open(self.mapname, GA_ReadOnly) lcarray = mapds.GetRasterBand(Region.rasters['landcover']).ReadAsArray(ox, oy, sx, sy) elarray = mapds.GetRasterBand(Region.rasters['elevation']).ReadAsArray(ox, oy, sx, sy) bathyarray = mapds.GetRasterBand(Region.rasters['bathy']).ReadAsArray(ox, oy, sx, sy) crustarray = mapds.GetRasterBand(Region.rasters['crust']).ReadAsArray(ox, oy, sx, sy) orthor = mapds.GetRasterBand(Region.rasters['orthor']).ReadAsArray(ox, oy, sx, sy) orthog = mapds.GetRasterBand(Region.rasters['orthog']).ReadAsArray(ox, oy, sx, sy) orthob = mapds.GetRasterBand(Region.rasters['orthob']).ReadAsArray(ox, oy, sx, sy) orthoir = mapds.GetRasterBand(Region.rasters['orthoir']).ReadAsArray(ox, oy, sx, sy) # calculate Minecraft corners self.mcoffsetx = self.tilex * self.size self.mcoffsetz = self.tiley * self.size # build a Minecraft world via pymclevel from blocks and data self.world = mclevel.MCInfdevOldLevel(self.tiledir, create=True) tilebox = box.BoundingBox((self.mcoffsetx, 0, self.mcoffsetz), (self.size, self.world.Height, self.size)) self.world.createChunksInBox(tilebox) # do the terrain thing (no trees, ore or building) self.peak = [0, 0, 0] treeobjs = dict([(tree.name, tree) for tree in treeObjs]) self.trees = dict([(name, list()) for name in treeobjs]) for myx, myz in product(xrange(self.size), xrange(self.size)): mcx = int(self.mcoffsetx+myx) mcz = int(self.mcoffsetz+myz) mcy = int(elarray[myz, myx]) lcval = int(lcarray[myz, myx]) bathyval = int(bathyarray[myz, myx]) crustval = int(crustarray[myz, myx]) rval = int(orthor[myz, myx]) gval = int(orthog[myz, myx]) bval = int(orthob[myz, myx]) irval = int(orthoir[myz, myx]) if mcy > self.peak[1]: self.peak = [mcx, mcy, mcz] (blocks, datas, tree) = Terrain.place(mcx, mcy, mcz, lcval, crustval, bathyval, self.doSchematics, rval, gval, bval, irval) [ self.world.setBlockAt(mcx, y, mcz, block) for (y, block) in blocks if block != 0 ] [ self.world.setBlockDataAt(mcx, y, mcz, data) for (y, data) in datas if data != 0 ] # if trees are placed, elevation cannot be changed if tree: Tree.placetreeintile(self, tree, mcx, mcy, mcz) # now that terrain and trees are done, place ore if self.doOre: Ore.placeoreintile(self) # replace all 'end stone' with stone EndStoneID = self.world.materials["End Stone"].ID StoneID = self.world.materials["Stone"].ID for xpos, zpos in self.world.allChunks: chunk = self.world.getChunk(xpos, zpos) chunk.Blocks[chunk.Blocks == EndStoneID] = StoneID # stick the player and the spawn at the peak setspawnandsave(self.world, self.peak) # write Tile.yaml with relevant data (peak at least) # NB: world is not dump-friendly. :-) del self.world stream = file(os.path.join(self.tiledir, 'Tile.yaml'), 'w') yaml.dump(self, stream) stream.close() # return peak return self.peak
class Window(pyglet.window.Window): def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) pyglet.clock.schedule_interval(self.update, 1./60) self.strafe = [0, 0] def fps(dt): print 'FPS is %f' % pyglet.clock.get_fps() pyglet.clock.schedule_interval(fps, 2) # Current (x, y, z) position in the world, specified with floats. Note # that, perhaps unlike in class, the y-axis is the vertical axis. self.position = (12, 8, 12) self.press = {} self.press["light"] = 0 # First element is rotation of the player in the x-z plane (ground # plane) measured from the z-axis down. The second is the rotation # angle from the ground plane up. Rotation is in degrees. # # The vertical plane rotation ranges from -90 (looking straight down) to # 90 (looking straight up). The horizontal rotation range is unbounded. self.rotation = (0, 0) self.reticle = None self.t = Terrain(a=33,water_line=1.5,generate=False) self.spin = 180 self.fps = pyglet.clock.ClockDisplay() #self.skybox = SkyBox.fromDir("../example/texture/bluesky", "bluesky") #self.skybox = SkyBox.fromDir("../example/texture/lake2", "jajlake2") self.kostka = Kostka(self.t) def set_exclusive_mouse(self, exclusive): """ If `exclusive` is True, the game will capture the mouse, if False the game will ignore the mouse. """ super(Window, self).set_exclusive_mouse(exclusive) self.exclusive = exclusive def _update(self, dt): """ Private implementation of the `update()` method. This is where most of the motion logic lives, along with gravity and collision detection. Parameters ---------- dt : float The change in time since the last call. """ # walking speed = 5 d = dt * speed # distance covered this tick. dx, dy, dz = self.get_motion_vector() # New position in space, before accounting for gravity. dx, dy, dz = dx * d, dy * d, dz * d # collisions x, y, z = self.position self.position = (x + dx, y + dy, z + dz) self.kostka.update(dt) def update( self, dt ): self._update(dt) def get_motion_vector(self): """ Returns the current motion vector indicating the velocity of the player. Returns ------- vector : tuple of len 3 Tuple containing the velocity in x, y, and z respectively. """ if any(self.strafe): x, y = self.rotation strafe = degrees(atan2(*self.strafe)) y_angle = radians(y) x_angle = radians(x + strafe) m = cos(y_angle) dy = sin(y_angle) if self.strafe[1]: # Moving left or right. dy = 0.0 m = 1 if self.strafe[0] > 0: # Moving backwards. dy *= -1 # When you are flying up or down, you have less left and right # motion. dx = cos(x_angle) * m dz = sin(x_angle) * m # else: # dy = 0.0 # dx = cos(x_angle) # dz = sin(x_angle) else: dy = 0.0 dx = 0.0 dz = 0.0 return (dx, dy, dz) def on_resize(self, width, height): """ Called when the window is resized to a new `width` and `height`. """ # label #self.label.y = height - 10 # reticle if self.reticle: self.reticle.delete() x, y = self.width / 2, self.height / 2 n = 10 self.reticle = pyglet.graphics.vertex_list(4, ('v2i', (x - n, y, x + n, y, x, y - n, x, y + n)) ) def on_draw(self): self.clear() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT) self.water_line = 1.5 self.water_color = (0.3,0.3,1,1) self.set_3d() glTranslatef(-16, 0, -16) # kostka self.t.draw(self.position[1]) self.kostka.draw() glPopMatrix() # set_3d camera transf self.set_2d() glColor3d(0, 0, 0) self.fps.draw() def set_2d(self): """ Configure OpenGL to draw in 2d. """ width, height = self.get_size() glDisable(GL_DEPTH_TEST) glDisable(GL_LIGHTING) glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, width, 0, height, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def set_3d(self): """ Configure OpenGL to draw in 3d. """ width, height = self.get_size() glEnable(GL_DEPTH_TEST) glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(65.0, width / float(height), 0.1, 500.0) # gluPerspective(65, width / float(height), 15, 0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() # set camera glPushMatrix() rx, ry = self.rotation glRotatef(rx, 0, 1, 0) glRotatef(-ry, cos(radians(rx)), 0, sin(radians(rx))) x, y, z = self.position #y = self.t.Height(x, z, floating=True)+.3 glTranslatef(-x, -y, -z) #self.skybox.draw(yrot=rx, xrot=-ry) # set lightning source self.spin += self.press["light"] self.spin %= 360 glPushMatrix(); x = lambda s : sin(radians(s))*30 z = lambda s : cos(radians(s))*30 self.t.lightPos = ( x(self.spin), 15., z(self.spin) ) #self.shader.uniform3fv("lightPos[0]", *[x(self.spin), 15, z(self.spin)]) #self.shader.uniform3fv("lightPos[1]", *[x(self.spin+120), 15, z(self.spin+120)]) #self.shader.uniform3fv("lightPos[2]", *[x(self.spin+240), 15, z(self.spin+240)]) glTranslatef(0, 25, 0) glRotated(self.spin, 1.0, 0.0, 0.0); glTranslated (0.0, 0.0, 30.0); glLightfv(GL_LIGHT0, GL_POSITION, vec(0, 0, 0, 1)) glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, vec(0, -1, 0)) glDisable (GL_LIGHTING); glColor3f (0.0, 1.0, 1.0); glutWireCube (2.0); glEnable (GL_LIGHTING); glPopMatrix() def on_mouse_press(self, x, y, button, modifiers): """ Called when a mouse button is pressed. See pyglet docs for button amd modifier mappings. Parameters ---------- x, y : int The coordinates of the mouse click. Always center of the screen if the mouse is captured. button : int Number representing mouse button that was clicked. 1 = left button, 4 = right button. modifiers : int Number representing any modifying keys that were pressed when the mouse button was clicked. """ if self.exclusive: pass else: self.set_exclusive_mouse(True) def on_mouse_motion(self, x, y, dx, dy): """ Called when the player moves the mouse. Parameters ---------- x, y : int The coordinates of the mouse click. Always center of the screen if the mouse is captured. dx, dy : float The movement of the mouse. """ if self.exclusive: m = 0.15 x, y = self.rotation x, y = x + dx * m, y + dy * m y = max(-90, min(90, y)) self.rotation = (x, y) def on_key_press( self, symbol, modifier ): global piece, bottom if symbol == key.A: self.strafe[1] -= 1 elif symbol == key.W: self.strafe[0] -= 1 elif symbol == key.S: self.strafe[0] += 1 elif symbol == key.D: self.strafe[1] += 1 elif symbol == key.UP : self.kostka.speed += .1 elif symbol == key.DOWN : self.kostka.speed -= .1 elif symbol == key.LEFT : self.kostka.input[0] = True elif symbol == key.RIGHT : self.kostka.input[1] = True elif symbol == key.F : global WIREFRAME WIREFRAME = not WIREFRAME if WIREFRAME : glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) else : glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) elif symbol == key.N : self.t = Terrain(water_line=1.5,generate=True) elif symbol == key.Q : exit(0) elif symbol == key.ESCAPE: self.set_exclusive_mouse(False) elif symbol == key.O : self.press["light"] = 1 elif symbol == key.P : self.press["light"] = -1 def on_key_release(self, symbol, modifiers): """ Called when the player releases a key. See pyglet docs for key mappings. Parameters ---------- symbol : int Number representing the key that was pressed. modifiers : int Number representing any modifying keys that were pressed. """ if symbol == key.W: self.strafe[0] += 1 elif symbol == key.S: self.strafe[0] -= 1 elif symbol == key.A: self.strafe[1] += 1 elif symbol == key.D: self.strafe[1] -= 1 elif symbol == key.LEFT : self.kostka.input[0] = False elif symbol == key.RIGHT : self.kostka.input[1] = False elif symbol == key.O : self.press["light"] = 0 elif symbol == key.P : self.press["light"] = 0
class Agent(object): """ Class to handle decisions about getting to the goal. :param: Terrain - the terrain on which the agent is navigating :param: Heuristic - the difficulty level of the heuristic """ def __init__(self, terrain, heuristic): self.terrain = Terrain(terrain) self.directions = {'N': (0, -1), 'E': (1, 0), 'S': (0, 1), 'W': (-1, 0)} self.start_node = Node(self.terrain.get_start_position(), 'N', 0) # Push our start position onto the heap self.search_heap = SearchHeap(initial=[self.start_node], g_func=lambda node: node.g, h_func=heuristic, goal=self.terrain.get_goal_position()) self.visited = [] self.position = list(self.terrain.get_start_position()) self.facing = 'N' self.action_costs = {'forward': lambda cost: -cost, 'bash': lambda cost: -3, 'turn': lambda cost: -ceil(float(cost)/float(3)), 'demolish': lambda cost: -4} print "goal position:" print self.terrain.get_goal_position() def a_star_search(self): """A* search for the goal""" while self.search_heap.is_not_empty(): node = self.search_heap.pop() # add the node to self.visited to show we visited it self.visited.append(node) """ print "current position:" print node.position print "current direction:" print node.direction print "node g score:" print node.g """ if self.terrain.is_goal_node(node): # TODO: make it return the path to the goal # as a sequence of nodes print "Score of the path:" print node.g + 100 print "Number of actions required to reach the goal:" print node.depth print "Number of nodes expanded:" print len(self.visited) break for action, neighbor in self.get_search_neighbors(node).iteritems(): last_time_visited = self.has_been_visited_already(neighbor) if last_time_visited is None and self.terrain.node_inside_terrain(neighbor): neighbor.g = self.assign_g_cost(neighbor, node, self.terrain, action) self.search_heap.push(neighbor) def get_search_neighbors(self, node): """Returns a list of node leaves from the given node.""" # These things create nodes turn_left = Node(position=node.position, direction=self.turn_left(node), depth=node.depth + 1) turn_right = Node(position=node.position, direction=self.turn_right(node), depth=node.depth + 1) move_forward = Node(position=self.forward(node), direction=node.direction, depth=node.depth + 1) bash_and_forward = Node(position=self.bash_and_forward(node), direction=node.direction, depth=node.depth + 1) # return the nodes return {'turn_left': turn_left, 'turn_right': turn_right, 'move_forward': move_forward, 'bash_and_forward': bash_and_forward} def assign_g_cost(self, node, parent, terrain, action): if 'turn' in action: # Update the g costs of the nodes return(parent.g + self.action_costs['turn']( self.terrain.get_cost_from_tuple( node.position))) elif action == 'move_forward': return parent.g + self.action_costs['forward']( self.terrain.get_cost_from_tuple( node.position)) else: return parent.g + self.action_costs['bash'](0) + self.action_costs['forward']( self.terrain.get_cost_from_tuple( node.position)) def forward(self, node): """The rules to move forward""" new_pos = (node.position[0] + self.directions[node.direction][0], node.position[1] + self.directions[node.direction][1]) # TODO: Update the score return new_pos def bash_and_forward(self, node): """The rules to bash and move forward""" return self.forward(Node(position=self.forward(node), direction=node.direction, depth=node.depth + 1)) def turn_right(self, node): """The rules to turn right""" dirs = ['N', 'E', 'S', 'W'] return dirs[(dirs.index(node.direction)+1) % len(dirs)] def turn_left(self, node): """The rules to turn left""" dirs = ['N', 'E', 'S', 'W'] return dirs[(dirs.index(node.direction)-1) % len(dirs)] def has_been_visited_already(self, node): """ Returns None or a Node This function will return None if the node has not been previously visited OR if the given node is less expensive to reach than the previous time we visited that position+direction pairing :param: Node - the node to check against for having already visited that position + direction pairing """ for visited in self.visited: # compare the two nodes if visited.is_the_same(node): if node.g > visited.g: return visited return None
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.hide() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Plane #shape = BulletPlaneShape(Vec3(0, 0, 1), 0) #mesh = BulletTriangleMesh() #geomNodes = loader.loadModel('levels/test1/collision').findAllMatches('**/+GeomNode') #geomNode = geomNodes.getPath(0).node() #geom = geomNode.getGeom(0) #mesh.addGeom(geom) #shape = BulletTriangleMeshShape(mesh, dynamic=False, bvh=True ) #np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) #np.node().addShape(shape) #np.setPos(0, 0, 20.0) #np.setCollideMask(BitMask32.allOn()) #self.world.attachRigidBody(np.node()) #sky dome self.sun_sky=Sky() self.sun_sky.setTime(17.0) #terrain self.ground=Terrain(self.world, self.worldNP) self.ground.loadMesh(path+'levels/gandg2/collision') self.ground.setMaps(path+'levels/gandg2/') self.ground.setTextures((39, 1, 2, 15, 4, 5)) #grass self.grass=Grass() self.grass.setMap(path+'levels/gandg2/grass.png') self.grass_to_cut=self.grass.getStatus() # Car self.car=Car(self.world, self.worldNP) self.car.setPos(161.0,160.0,26) #camera self.camera=FlyingCamera() #car to character scale 0.0128 self.char=Character(self.world, self.worldNP) self.char.enterCar() #self.char.setPos(256, 250, 80) #filter manager, post process self.filters=Postprocess() #self.filters.setupFxaa() #no time to make it work, sorry... self.filters.setupFilters() #map objects .. hardcoded because of time self.object_root=render.attachNewNode('object_root') obj=[ (path+'models/pyweek_wall1',0.0,(303.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(301.0,405.0,25.0980434417725),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(299.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(297.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(295.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(293.0,405.0,25.0980434417725),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(291.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(289.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(287.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(285.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(283.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(281.0,405.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(281.0,385.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(283.0,385.0,25.0980453491211),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(285.0,385.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,404.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,402.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,400.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,398.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,396.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,394.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(304.0,392.0,25.237850189209),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,404.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,398.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,396.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,394.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,392.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,390.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,388.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,386.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(286.0,386.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(286.0,388.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(286.0,390.0,25.0980434417725),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(287.0,391.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(289.0,391.0,25.1190624237061),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(291.0,391.0,25.1960334777832),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(293.0,391.0,25.1596641540527),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(295.0,391.0,25.2697868347168),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(297.0,391.0,25.3282146453857),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(299.0,391.0,25.3496627807617),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(301.0,391.0,25.2688617706299),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',0.0,(303.0,391.0,25.2534332275391),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_wall1',90.0,(280.0,402.0,25.0980415344238),path+'models/pyweek_wall1_collision'), (path+'models/pyweek_box',0.0,(279.600006103516,401.700012207031,25.0980415344238),None), (path+'models/pyweek_box',0.0,(279.399993896484,402.200012207031,25.0980415344238),None), (path+'models/pyweek_box',0.0,(279.600006103516,402.700012207031,25.0980415344238),None), (path+'models/pyweek_box',0.0,(279.399993896484,403.399993896484,25.0980415344238),None), (path+'models/pyweek_box',0.0,(278.799987792969,402.799987792969,25.0980415344238),None), (path+'models/pyweek_box',0.0,(278.799987792969,402.100006103516,25.0980415344238),None), (path+'models/pyweek_box',0.0,(279.0,401.5,25.0980415344238),None), (path+'models/pyweek_box',0.0,(278.5,401.600006103516,25.0980415344238),None), (path+'models/pyweek_box',0.0,(278.799987792969,401.899993896484,25.5980415344238),None), (path+'models/pyweek_box',90.0,(279.5,402.600006103516,25.5980415344238),None), (path+'models/pyweek_box',90.0,(279.0,402.5,25.5980415344238),None), (path+'models/pyweek_box',90.0,(279.399993896484,402.0,25.5980415344238),None), (path+'models/pyweek_box',90.0,(278.100006103516,402.299987792969,25.0980415344238),None), (path+'models/pyweek_box',90.0,(277.799987792969,401.700012207031,25.0980415344238),None), (path+'models/pyweek_box',90.0,(278.200012207031,401.899993896484,25.5980415344238),None), (path+'models/pyweek_box',90.0,(279.399993896484,402.399993896484,26.0980415344238),None), (path+'models/pyweek_box',90.0,(279.0,401.899993896484,26.0980415344238),None), (path+'models/pyweek_box',90.0,(278.799987792969,402.399993896484,26.0980415344238),None) ] for i in obj: loadObject(model=i[0], H=i[1], pos=i[2], world=self.world, worldNP=self.worldNP, root=self.object_root, collision_solid=i[3]) self.object_root.flattenStrong() #models/pyweek_gate,90.0,(280.0,399.0,25.0980415344238)) #gui self.hud=HUD() #volume sfxMgr = base.sfxManagerList[0] sfxMgr.setVolume(cfg['sound-volume']*0.01) musicMgr = base.musicManager musicMgr.setVolume(cfg['music-volume']*0.01) #music self.driving_music=loader.loadMusic(path+'music/driving.ogg') self.driving_music.setLoop(True) self.driving_music.play() self.walking_music=loader.loadMusic(path+'music/walking.ogg') self.walking_music.setLoop(True) print self.char.actor.getScale(render)
class testSnail(unittest.TestCase): """ A test class for the Snail module. """ def setUp(self): """ set up data used in the tests. setUp is called before each test function execution. """ pygame.init() pygame.display.set_mode([Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT]) self.input = Input() self.terrain = Terrain() self.teamName = "EJteam" self.team = Team(self.teamName) self.team.setGravity(Direction.DOWN) self.team.hasTurn = True TurnManager().status = TurnStatus.CURRENTTURN TurnManager().teams = [] TurnManager().teams.append(self.team) self.snail = Snail(self.team) self.snail.hasTurn = True def testInitialized(self): self.assertEqual(self.snail.team.name, self.teamName) # self.assertEqual(self.snail.hasTurn, False) def testFollowMouse(self): self.input.mouse_x = 100 self.input.mouse_y = 100 self.snail.update(self.input, self.terrain) self.assertEqual(self.snail.rect.centerx, 100) self.assertEqual(self.snail.rect.centery, 100) self.input.mouse_x = 150 self.input.mouse_y = 150 self.terrain.addBlock(150, 150) self.snail.update(self.input, self.terrain) self.assertNotEqual(self.snail.rect.centerx, 150) self.assertNotEqual(self.snail.rect.centery, 150) def testSnailPlaceSnailCorrect(self): self.input.mouse_x = 100 self.input.mouse_y = 100 self.input.mouse_left = True self.input.mouse_left_click = True self.snail.update(self.input, self.terrain) self.assertTrue(self.snail.isPlaced) def testSnailPlaceSnailWrong(self): self.input.mouse_x = 150 self.input.mouse_y = 150 self.terrain.addBlock(150, 150) self.input.mouse_left = True self.snail.update(self.input, self.terrain) self.assertFalse(self.snail.isPlaced) def testGravityDown(self): self.testSnailPlaceSnailCorrect() self.team.setGravity(Direction.DOWN) old_y = self.snail.rect.centery for i in range(0,10): self.snail.update(self.input, self.terrain) self.assertTrue(self.snail.rect.centery > old_y) def testGravityDownSpeed(self): self.testSnailPlaceSnailCorrect() self.assertEqual(self.snail.direction['jump'], 0) self.snail.updateGravity() self.assertEqual(self.snail.direction['jump'], self.snail.speed['fall']) waitTurns = 5 / self.snail.speed['fall'] for i in range(0, waitTurns + 5): self.snail.updateGravity() self.assertEqual(self.snail.direction['jump'], 5) def testGravityUp(self): self.testSnailPlaceSnailCorrect() self.snail.gravity_direction = Direction.UP old_y = self.snail.rect.centery for i in range(0,10): self.snail.update(self.input, self.terrain) self.assertTrue(self.snail.rect.centery < old_y) def testGravityRight(self): self.testSnailPlaceSnailCorrect() self.snail.gravity_direction = Direction.RIGHT old_x = self.snail.rect.centerx for i in range(0,10): self.snail.update(self.input, self.terrain) self.assertTrue(self.snail.rect.centerx > old_x) def testGravityLeft(self): self.testSnailPlaceSnailCorrect() self.snail.gravity_direction = Direction.LEFT old_x = self.snail.rect.centerx for i in range(0,10): self.snail.update(self.input, self.terrain) self.assertTrue(self.snail.rect.centerx < old_x) def testAiming(self): pass def testShooting(self): pass def testMoving(self): pass def testJumping(self): pass def testDie(self): self.assertEquals(self.snail.hitpoints, 100) def testCollision(self): pass def testTouchingSalt(self): pass
def setUp(self): pygame.init() pygame.display.set_mode([Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT]) self.terrain = Terrain()
def collide(self, elem): if isinstance(elem, GoalBlock): self.mylevel.game_over = True else: Terrain.collide(self, elem)
def newTerrain( self ): self.currentTerrain = Terrain( self.rCurveName + str(len(self.terrain)) ) print self.currentTerrain.rCurveName self.terrain.append( self.currentTerrain ) self.currentTerrain.createRiver ()
class testTerrain(unittest.TestCase): def setUp(self): pygame.init() pygame.display.set_mode([Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT]) self.terrain = Terrain() def testAddTerrainBlock(self): self.terrain.addBlock(100, 150) self.assertEqual(len(self.terrain.sprites()), 1) self.assertEqual(self.terrain.sprites()[0].rect.x, 100) self.assertEqual(self.terrain.sprites()[0].rect.y, 150) def testCreateTerrain(self): self.terrain.createEastBorder(5) self.terrain.createNorthBorder(5) self.terrain.createSouthBorder(5) self.terrain.createWestBorder(5) self.assertEqual(len(self.terrain.sprites()), 5 * 4)
def __init__(self, x_co, y_co, w_co, h_co, vx_co, vy_co, mass, level_co, c_co): Terrain.__init__(self, x_co, y_co, w_co, h_co, vx_co, vy_co, mass, level_co, c_co) self.graphics = TiledGraphics("img/goal.png", self.mylevel.meter, self.mylevel.meter)
def __init__(self, name, locations=None, map=None, color="black"): Terrain.__init__(self, name, locations, map) self._color = color