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()
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()
class Game: def __init__(self, width, height): self.canvasWidth = width self.canvasHeight = height self.score = 0 self.roundCount = 0 self.enemies = [] self.enemyPositions = [] self.currentRound = None self.playerClonePos = None self.terrain = None self.player = None self.gameOverStatus = False self.roundLives = 3 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 def playerDeath(self): if self.roundLives <= 0: self.gameOver() return for enemy in self.enemies: enemy.health = 100 self.player.pos = self.playerClonePos.copy() self.player.health = 100 self.player.shieldStatus = 100 self.player.trackMarks.clear() self.roundLives -= 1 def gameOver(self): self.gameOverStatus = True def newPlayer(self): player = PlayerTank( Tank.newTankPos(self.terrain, self.canvasWidth, self.canvasHeight), self) return player def drawInfo(self, canvas): canvas.draw_text("ROUND: " + str(self.roundCount), (10, 20), 20, "White") canvas.draw_text("LIVES: " + str(self.roundLives), (10, 40), 20, "White") canvas.draw_text("MISSILES: " + str(self.player.homingAmmo), (10, 60), 20, "White") canvas.draw_text("Score: " + str(self.score), (10, 80), 20, "White")
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
def create(): Map.generate_lakes() Map.generate_valleys() # Make mud around lakes for sq in Map.spawnable: sq.terrain = Terrain(0, 1)
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()
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 = ""
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)
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
def __init__(self): self.key_down = [False] * 256 self.myCamera = Camera(rX = 0, pX = 0, pY = 20.5, pZ = 5) self.current_time = time.time() self.frame_count = 0 self.openGLInit() self.terrain = Terrain() self.terrain.load("fractal.bmp") self.run()
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)
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
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()
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
def __init__(self): self.running = True self.clock = pygame.time.Clock() self.initializeScreen() self.viewPositionX = 0 self.viewPositionY = 0 self.terrain = Terrain(40,40) self.population = Population(self.terrain) self.buildingPopulation = BuildingPopulation(self.terrain) self.powers = PowerPopulation() self.explosionTimer = 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()
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()
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()))
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()
class Landscape(Element): 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 = "" 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 def to_json_object(self, sim): json_obj = { "forest": self.scene_objects.to_json_object(), "terrain": self.terrain.to_json_object(), "optical_properties": self.optical_properties.to_json_object(), "temperature_properties": self.temperature_properties, "extra_scene": self.extra_scene } return json_obj def add_op_item(self, op_item): self.optical_properties.add_optical_item(op_item) def get_op_item(self, op_name): return self.optical_properties.get_optical_item(op_name) def add_object(self, scene_object: SceneObject, override_file=True, translate_to_origin="no"): self.scene_objects.add_object(scene_object, override_file, translate_to_origin) def place_object(self, obj_name, x=50.0, y=50.0, z=0.0, rotate=0.0): self.scene_objects.place_object_to(obj_name, x, y, z, rotate) def set_terrain_op(self, op_name): self.terrain.optical = op_name def get_terrain(self): return self.terrain def get_op_properties(self): return self.optical_properties def get_scene_objects(self): return self.scene_objects
class SugarScape: def __init__(self): self.players = [] self.terrain = Terrain() self.judge = MoveJudge(self.terrain) @LoadObject def load(self): for key in itersplit(self.playerKeys, ','): player = Player(key, self) player.load() self.players.append(player) self.terrain.load(self.players) def start(self): self.terrain.start() self.judge.start() for player in self.players: player.start() @SaveObject def join(self): try: gevent.joinall([self.terrain] + [self.judge] + self.players) except SystemExit: for player in self.players: player.running = False gevent.joinall(self.players) self.judge.running = False self.terrain.running = False gevent.joinall([self.terrain]) @SaveObject def born(self, player): self.players.append(player) return self.terrain.born(player) @SaveObject def dead(self, player): self.players.remove(player) return self.terrain.dead(player) def peek(self, position): return self.terrain.peek(position) def existPlayer(self, position): return self.terrain.existPlayer(position) def isMovable(self, position): return self.terrain.isMovable(position) def requestMove(self, request): return self.judge.inbox.put(request) def movePlayer(self, player, position): return self.terrain.movePlayer(player, position) def gather(self, position): return self.terrain.gather(position) def Data(self): return {'playerKeys': ','.join((p.Key() for p in self.players))} def Key(self): return 'sugarscape'
def __init__(self): self.players = [] self.terrain = Terrain() self.judge = MoveJudge(self.terrain)
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:
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")
class Model(object): 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 def init_statistics(self): self.water_out = [] self.water_in = [] self.total_water = [self.get_total_water()] self.total_peat = [self.get_total_peat()] self.terrain_timeline = [self.terrain.get_summary()] def gather_statistics(self): self.water_out.append(self.current_water_out) self.water_in.append(self.current_water_in) self.total_water.append(self.get_total_water()) self.total_peat.append(self.get_total_peat()) self.terrain_timeline.append(self.terrain.get_summary()) def run(self, timesteps=10, dump_to_file=True): self.init_statistics() for t in range(timesteps): self.current_water_out = 0 self.current_water_in = 0 print("Timestep {}".format(t + 1)) self.timestep() self.gather_statistics() summary = self.get_summary() if dump_to_file: with open('output.json', 'w') as file: print("Output to output.json") json.dump(summary, file) return summary def run_untill_other_side(self, timesteps=10, dump_to_file=True): self.init_statistics() t = 0 while self.max_depth < 99: t += 1 self.current_water_out = 0 self.current_water_in = 0 print("Timestep {}".format(t)) self.timestep() self.gather_statistics() summary = self.get_summary() if dump_to_file: with open('output.json', 'w') as file: print("Output to output.json") json.dump(summary, file) return summary def timestep(self): # Directly from paper self.mutations = [] self.supply_water() self.remove_water() self.calculate_flows() self.update_water() self.calculate_nutrient_dist() self.calculate_peat_growth() def supply_water(self): # @todo: Make some kind of distribution? # for cell in self.terrain.terrain[0]: # self.mutations.append({ # 'from': None, # 'to': cell, # 'water': 10 # }) self.mutations.append({ 'from': None, 'to': self.terrain.terrain[0][50], 'water': 50 }) def remove_water(self): # @todo: Remove all water from last row? for cell in self.terrain.terrain[-1]: self.mutations.append({ 'from': cell, 'to': None, 'water': cell.height_of_water }) def calculate_flows(self): # mutations is the collection of f[i] in the paper for cell in self.terrain.cells(): mutations = cell.get_water_flow() # "commit" self.mutations += mutations def update_water(self): mutated = 0 for mutation in self.mutations: # None cells are either inlet or outlet if mutation['water'] > 0: if mutation['from'] != None: mutation['from'].height_of_water -= mutation['water'] else: self.current_water_in += mutation['water'] if mutation['to'] != None: mutation['to'].height_of_water += mutation['water'] if mutation['to'].y > self.max_depth: self.max_depth = mutation['to'].y else: self.current_water_out += mutation['water'] mutated += 1 print("Ran {} water mutations, max depth {}.".format( mutated, self.max_depth)) def calculate_nutrient_dist(self): new_terrain = self.terrain.copy() for cell, new_cell in zip(self.terrain.cells(), new_terrain.cells()): if cell.height_of_water > 0: cell.concentration_of_nutrients = 1 else: new_cell.concentration_of_nutrients = self.gamma * max([ neighbour_cell.concentration_of_nutrients for neighbour_cell in cell.neighbours() ]) self.terrain = new_terrain def calculate_peat_growth(self): for cell in self.terrain.cells(): if cell.height_of_water > 0: cell.peat_bog_thickness += self.mu * cell.concentration_of_nutrients else: cell.peat_bog_thickness += self.rho * cell.concentration_of_nutrients def get_total_water(self): total_water = 0 for cell in self.terrain.cells(): total_water += cell.height_of_water return total_water def get_total_peat(self): total_peat = 0 for cell in self.terrain.cells(): total_peat += cell.peat_bog_thickness return total_peat def get_summary(self): self.gamma = self.parameters['gamma'] self.rho = self.parameters['rho'] self.mu = self.parameters['mu'] print(self.total_peat) print(self.total_water) print(self.water_in) print(self.water_out) return { 'gamma': self.gamma, 'rho': self.rho, 'mu': self.mu, 'peat_timeline': self.total_peat, 'water_timeline': self.total_water, 'water_in_timeline': self.water_in, 'water_out_timeline': self.water_out, 'terrain_timeline': self.terrain_timeline }
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)
# encoding : utf-8 import copy import time from gcouchbase.connection import GConnection #from couchbase import Couchbase from couchbase.exceptions import * from Config import Config from Data import GrowthMap, MAP_SIZE from Terrain import Terrain from Player import Player PLAYER_COUNT = 800 players = [Player('player_%d' % i, None) for i in xrange(PLAYER_COUNT)] terrain = Terrain() terrain.size = MAP_SIZE terrain.growth = copy.deepcopy(GrowthMap) terrain.sugar = copy.deepcopy(GrowthMap) for player in players: player.sugar = 10 terrain.born(player) start = time.clock() cb = GConnection(host=Config['dbHost'], bucket=Config['dbBucket']) #cb = Couchbase.connect(host=Config['dbHost'], bucket=Config['dbBucket']) cb.set('sugarscape', {'playerKeys': ','.join((p.Key() for p in players))}) for player in players:
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)
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)
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:
class Game(): def __init__(self): self.running = True self.clock = pygame.time.Clock() self.initializeScreen() self.viewPositionX = 0 self.viewPositionY = 0 self.terrain = Terrain(40,40) self.population = Population(self.terrain) self.buildingPopulation = BuildingPopulation(self.terrain) self.powers = PowerPopulation() self.explosionTimer = 0; def initializeScreen(self): #Initialize Everything pygame.init() self.screen = pygame.display.set_mode((1024, 768)) pygame.display.set_caption('Release the Kraken!') pygame.mouse.set_visible(1) #Create The Background self.background = pygame.Surface(self.screen.get_size()) self.background = self.background.convert() self.background.fill((250, 250, 250)) def handleInput(self): kraken = 0 for event in pygame.event.get(): if event.type == QUIT: self.running = False self.explosionTimer += TIME_QUANTUM if(pygame.mouse.get_pressed()[0] and self.explosionTimer > 500): self.powers.addPower(Explosion((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30)) self.explosionTimer = 0 if(pygame.key.get_pressed()[K_k]): self.population.addCreatureKraken((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, Kraken((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30), self.terrain) phaser_sound = pygame.mixer.Sound("art/release.ogg") channel = phaser_sound.play() if kraken < 1: pygame.mixer.music.load("sfx/carmina.ogg") pygame.mixer.music.play() kraken += 1 if(pygame.key.get_pressed()[K_q]): self.population.addCreature((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, Peasant((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, 0), self.terrain) if(pygame.key.get_pressed()[K_w]): self.population.addCreature((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, Swordsman((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, 0), self.terrain) if(pygame.key.get_pressed()[K_e]): self.population.addCreature((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, Archer((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, 0), self.terrain) if(pygame.key.get_pressed()[K_r]): self.population.addCreature((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, Wizard((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, 0), self.terrain) if(pygame.key.get_pressed()[K_a]): self.population.addCreature((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, Peasant((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, 1), self.terrain) if(pygame.key.get_pressed()[K_s]): self.population.addCreature((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, Swordsman((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, 1), self.terrain) if(pygame.key.get_pressed()[K_d]): self.population.addCreature((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, Archer((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, 1), self.terrain) if(pygame.key.get_pressed()[K_f]): self.population.addCreature((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, Wizard((-self.viewPositionX + pygame.mouse.get_pos()[0])/30, (-self.viewPositionY + pygame.mouse.get_pos()[1])/30, 1), self.terrain) if(pygame.key.get_pressed()[K_UP]): self.viewPositionY+=8 if(pygame.key.get_pressed()[K_DOWN]): self.viewPositionY-=8 if(pygame.key.get_pressed()[K_LEFT]): self.viewPositionX+=8 if(pygame.key.get_pressed()[K_RIGHT]): self.viewPositionX-=8 def run(self): time = pygame.time.get_ticks() pygame.mixer.music.load("art/rose.ogg") pygame.mixer.music.play() while self.running: while(time < pygame.time.get_ticks()): self.handleInput() self.population.process(self.powers, self.buildingPopulation, self.terrain) self.buildingPopulation.process(self.terrain, self.population) self.powers.process(self.terrain, self.population, self.buildingPopulation) time += TIME_QUANTUM self.screen.blit(self.background, (0,0)) self.terrain.paint(self.screen, (self.viewPositionX, self.viewPositionY)) self.buildingPopulation.paint(self.screen, (self.viewPositionX, self.viewPositionY)) self.population.paint(self.screen, (self.viewPositionX, self.viewPositionY)) self.powers.paint(self.screen, (self.viewPositionX, self.viewPositionY)) pygame.display.flip()
class GameEngine: def __init__(self): self.key_down = [False] * 256 self.myCamera = Camera(rX = 0, pX = 0, pY = 20.5, pZ = 5) self.current_time = time.time() self.frame_count = 0 self.openGLInit() self.terrain = Terrain() self.terrain.load("fractal.bmp") self.run() def keyPressed(self, key, x, y): self.key_down[ord(key)] = True def keyReleased(self, key, x, y): self.key_down[ord(key)] = False def checkKeypresses(self): if self.key_down[ord('w')]: self.myCamera.moveForward(MOVEMENT_SPEED) if self.key_down[ord('a')]: self.myCamera.strafeLeft(MOVEMENT_SPEED) if self.key_down[ord('s')]: self.myCamera.moveBackward(MOVEMENT_SPEED) if self.key_down[ord('d')]: self.myCamera.strafeRight(MOVEMENT_SPEED) if self.key_down[ord('c')]: self.myCamera.diveDown(MOVEMENT_SPEED) if self.key_down[ord(' ')]: self.myCamera.flyUp(MOVEMENT_SPEED) if self.key_down[ord('x')]: sys.exit(1) def mouseMoved(self, x, y): self.myCamera.look(x, y) def openGLInit(self): glutInit() glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT) glutCreateWindow("Terrain Generator") glClearColor(1, 1, 1, 1) glutDisplayFunc(self.display) glutIdleFunc(self.display) glMatrixMode(GL_PROJECTION) gluPerspective(45., 1., .1, 1500.) glMatrixMode(GL_MODELVIEW) glShadeModel(GL_SMOOTH) glutKeyboardFunc(self.keyPressed) glutKeyboardUpFunc(self.keyReleased) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) #glEnable(GL_CULL_FACE) #glutMotionFunc(self.mouseMoved) glutPassiveMotionFunc(self.mouseMoved) # glutSetKeyRepeat(GLUT_KEY_REPEAT_OFF) glutSetCursor(GLUT_CURSOR_NONE) # glEnable(GL_LIGHTING) # lightZeroPosition = [50, 40, 50, 0] # lightZeroColor = [.5, 1, .1, 0.0] # glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition) # glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor) # glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1) # glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05) # glEnable(GL_LIGHT0) # light_ambient = (1, 1, 1, 1) # light_position = (10, 50, 0, 0) # glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient) # glLightfv(GL_LIGHT1, GL_POSITION, light_position) #glEnable(GL_LIGHT1) def run(self): glutMainLoop() def calculateFPS(self): elapsed_time = time.time() - self.current_time if elapsed_time > 0: return "FPS: %.2f" % (self.frame_count / elapsed_time) self.current_time = time.time() self.frame_count = 0 def display(self): self.frame_count += 1 self.checkKeypresses() glLoadIdentity() glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) self.myCamera.render() self.terrain.render() #self.terrain.optimizedRender() glColor3f(1, 0, 0) glWindowPos2i(WINDOW_WIDTH - 150, WINDOW_HEIGHT - 50) fps = self.calculateFPS() glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, fps) glutSwapBuffers()
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('.')
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()
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()
from tkinter import * import numpy as np from Mob import Mob from WorgRider import WorgRider from Solar import Solar from Warlord import Warlord from Barbare import Barbare from Terrain import Terrain # ### # Constante terrain = Terrain() time = 3 w = terrain.tailleX h = terrain.tailleY # ### # Affichage de la fenetre def affiche_fenetre(): global fenetre, canvas fenetre = Tk() fenetre.title('Dongeons et Dragons') fenetre.resizable(False, False) fenetre.after(time, affichage) canvas = Canvas(fenetre, width=w, height=h, background='white')