def __init__(self, simVars, delta=50, tick=0): self.delta = delta self.simVars = simVars self.map = Map(simVars) self.spawner = Spawner(self) self.tick = tick self.physics = Physics()
def __init__(self, *args, **kwags): super(SitePlugin, self).__init__(*args, **kwags) # Now spawn background process if needed io = {"output": self.backgroundOutput, "input": self.backgroundInput, "allowed_import": (), "modules": storage.modules} self.spawner = Spawner(self, io=io) self.spawned_background_processes = False if "BACKGROUND" in self.settings["permissions"]: self.spawnBackgroundProcesses()
def __init__(self, world): self.id = type(self).instance_num # const and public type(self).instance_num += 1 # TODO: switches and goals and hives self.spawner = Spawner(world) self.wall = Wall(world) self.mines = Mines(world) self.balls = Balls(world) self.elapsed_time = KahanSum() self.can_mutate = True
def __init__(self, population_size, mutation_rate, target, good_sample_size, random_sample_size, spawner=None, ): self.mutation_rate = mutation_rate self.population_size = population_size self.target = target self.good_sample_size = good_sample_size self.random_sample_size = random_sample_size self.spawner = Spawner() if spawner is None else spawner
def start(): PixelsManager.setup() Map.setup() GameEnder.setup() TimeManager.setup() InputManager() Player.get_instance() Spawner() print("Starting game") GameManager.get_instance().run() print("Ending game") TimeManager.destroy() Player.destroy_instance() ObjectsHolder.objects.clear()
def __init__(self, *args, **kwags): super(SitePlugin, self).__init__(*args, **kwags) # Now spawn background process if needed io = { "output": self.backgroundOutput, "input": self.backgroundInput, "allowed_import": ("json",), "modules": storage.modules, "site": self, "scope0": [] } self.spawner = Spawner(self, io=io) self.spawned_background_processes = False if "BACKGROUND" in self.settings["permissions"]: self.spawnBackgroundProcesses() self.onFileDone.append(self.reloadBackgroundProcess)
#!/usr/bin/env python import pika import time import asyncio from utils.color import style from spawner import Spawner if __name__ == '__main__': connection = pika.BlockingConnection( pika.ConnectionParameters('localhost')) if connection.is_closed: print( "The RabbitMQ server was not found (check connection localhost:5672). Quitting simulation." ) channel = connection.channel() if channel.is_closed: print("The RabbitMQ server was not found. Quitting simulation.") connection.close() task_spawner = Spawner() task_spawner.execute_concurrent() # asyncio.run(task_spawner.execute_concurrent()) # canceled = False # while canceled == False: # time.sleep(1) print(style.GREEN('Program exited normally.'))
def main(): # Importing data from config with open('data/config.json') as cfg: data=json.load(cfg) terminal_width=data['terminal_width'] terminal_height=data['terminal_height'] map_width=data['map_width'] map_height=data['map_height'] fov_algorithm=data['fov_algorithm'] fov_light_walls=data['fov_light_walls'] fov_radius=data['fov_radius'] # Init root console tcod.console_set_custom_font('gfx/fonts/terminal12x16_gs_ro.png', tcod.FONT_TYPE_GREYSCALE | tcod.tcod.FONT_LAYOUT_CP437) console_root=tcod.console_init_root(terminal_width, terminal_height, 'Python Game Lol', False, tcod.RENDERER_SDL2, 'C', False) console_display=tcod.console.Console(terminal_width, terminal_height, 'C') with open('gfx/palette.json') as colours: palette=json.load(colours) console_display.bg[:]=palette['terminal_green'] #console_interface=tcod.console.Console(terminal_width, map_height, 'C') game_map=GameMap(map_width, map_height) spawner=Spawner(map_width, map_height, 0) # Testing creatures generate_test_area(game_map, spawner) player=spawner.entities[0] # Then generate map fov_recompute=True # message log game_state=GameStates.TURN_PLAYER prev_game_state=game_state #targeting_item=None # Rendering for the first time game_map.recompute_fov(player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) render_all(console_root, console_display, spawner.entities, game_map, fov_recompute) fov_recompute=False tcod.console_flush() # Game loop while True: # Render if fov_recompute: game_map.recompute_fov(player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) render_all(console_root, console_display, spawner.entities, game_map, fov_recompute) fov_recompute=False tcod.console_flush() erase_entities(console_display, spawner.entities, game_map) # Processing action action=handle_event(game_state) move=action.get('move') pickup=action.get('pickup') take_inventory=action.get('take_inventory') fullscreen=action.get('fullscreen') exit=action.get('exit') # Player's Turn results_player=[] # Results: Extend if player turn ends and append if doesn't? Tcod tutorial is confusing. if game_state==GameStates.TURN_PLAYER: if move: dx, dy=move results_movement=player.handle_move(dx, dy, spawner, game_map.path_map, swappable=True) if results_movement: results_player.extend(results_movement) fov_recompute=True game_state=GameStates.TURN_ALLY elif pickup: # Should implement a pickup list like POWDER for entity in spawner.entities: if entity.item and entity.x==player.x and entity.y==player.y: print('ADD ITEM') # Add item break else: print('GRAB GROUND') # Message log to grab ground if take_inventory: prev_game_state=game_state game_state=GameStates.MENU_INVENTORY if exit: if game_state.value>=10: # Game states >= 10 are menus: inventory, quipment, etc. game_state=prev_game_state if game_state.value>=20: # Game states >= 20 are targetings results_player.append({'targeting_cancelled': True}) # else brings up main menu if fullscreen: tcod.console_set_fullscreen(not tcod.console_is_fullscreen()) # Player turn messages: handled by an announcer (translation friendly probably) # Faction turns (handled by an announcer also) if game_state==GameStates.TURN_ALLY: for entity in spawner.entities: if entity.faction==Factions.ALLY and entity!=player: results_ally=entity.ai.take_turn(spawner, game_map.path_map) game_state=GameStates.TURN_ENEMY if game_state==GameStates.TURN_ENEMY: for entity in spawner.entities: if entity.faction==Factions.ENEMY: results_enemy=entity.ai.take_turn(spawner, game_map.path_map) game_state=GameStates.TURN_NEUTRAL if game_state==GameStates.TURN_NEUTRAL: for entity in spawner.entities: if entity.faction==Factions.NEUTRAL: if entity.ai: resutls_neutral=entity.ai.take_turn(spawner, game_map.path_map) game_state=GameStates.TURN_PLAYER
from force_ball import ForceBall from game_state import GameState from physics import update_ball, handle_wall_collision #Set window position on screen os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50, 50) pygame.init() SCREEN_WIDTH = 1200 SCREEN_HEIGHT = 900 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) balls = initial_balls(SCREEN_WIDTH, SCREEN_HEIGHT) force_balls = [] game_state = GameState() object_handler = Spawner() painter = screen_painter.ScreenPainter() painter.ball_painting_algorithm = screen_painter.speed while game_state.running: game_state.handle_inputs(pygame.event.get()) object_handler.update(game_state.get_click_spawn_behaviour()) if pygame.mouse.get_pressed()[0]: object_handler.handle_action(game_state.get_click_action(), balls, force_balls, game_state.get_new_spawn_force()) if not game_state.paused: balls_to_delete = [] for ball in balls:
import pygame from player import Player from spawner import Spawner from menu import Menu pygame.init() player = Player() spawner = Spawner() menu = Menu() menu.game_run(player, spawner)
import pickle pygame.init() objects = [] mousex = 0 mousey = 0 width = 800 height = 800 size = width, height lives = 3 font = pygame.font.Font('freesansbold.ttf', 32) screen = pygame.display.set_mode(size) game_running = True move1 = False s = Spawner(width, height) round_num = 1 fire_cooldown = 0 score = 0 pygame.display.set_caption('Asteriods') def game_over(): if score > get_high_score(): with open('score.bat', 'wb') as file: pickle.dump(score, file) print("New High Score!") else: print("All time high score is " + str(get_high_score()))
from spawner import Spawner from genetic_algo import GeneticAlgo population_size = 1000 a = Spawner() generation = a.spawn_generation('tomallpress', population_size) c = GeneticAlgo(population_size, 0.01, 'tomallpress', 100, 1) for i in range(20): generation = c.get_next_generation(generation) print(generation.display())
def main(): """ Main game logic loop. """ containerTextStyle = { 'color': '#ffffff', 'font': '10px', 'stroke': '#000000', 'strokeWidth': .15 } spawnerRole = Spawner() # Clean up memory for creepName in Object.keys(Memory.creeps): if not Game.creeps[creepName]: if Memory.creeps[creepName].role == "remoteHarvester": print("Cleaning up remoteHarvester. It mined: " + Memory.creeps[creepName].totalHarvested) del Memory.creeps[creepName] #print("Clearing non-existent creep memory: " + creepName) if Game.cpu.bucket == 10000: Game.cpu.generatePixel() # Run each creep for name in Object.keys(Game.creeps): creep = Game.creeps[name] if creep.memory.role in Spawner.roles: Spawner.roles[creep.memory.role].run(creep) else: creep.say("No role") # Run tower code homeRoom = Object.values(Game.spawns)[0].room towers = [ struct for room in Object.values(Game.rooms) for struct in room.find(FIND_STRUCTURES) if struct.structureType == STRUCTURE_TOWER ] hostiles = homeRoom.find(FIND_HOSTILE_CREEPS) for tower in towers: structures = sorted([ struct for struct in tower.room.find(FIND_STRUCTURES) if struct.hits < struct.hitsMax ], key=lambda struct: struct.hits) if len(hostiles) > 0: tower.attack(tower.pos.findClosestByPath(hostiles)) continue for structure in structures: if structure.hits < structure.hitsMax and structure.hits < 100000: tower.repair(structure) break # Run visuals for room in Object.values(Game.rooms): for container in [ struct for struct in room.find(FIND_STRUCTURES) if struct.structureType == STRUCTURE_CONTAINER or struct.structureType == STRUCTURE_STORAGE ]: room.visual.text( Spawner.roles['harvester'].getStructureFutureEnergy(container), container.pos, containerTextStyle) # Run each spawn for name in Object.keys(Game.spawns)[0:1]: spawn = Game.spawns[name] spawnerRole.run(spawn)
def main(): # Initial setup: pygame.init() pygame.display.set_mode(config.resolution, DOUBLEBUF | OPENGL) gluPerspective(config.camera_fov, config.resolution[0] / config.resolution[1], 0.1, 50.0) glTranslatef(0, 0, config.camera_z) # Entities simulated = list() drawn = list() test_cube = Entity((0, 0, 0)) move = 0.5 drawn.append(test_cube) asteroid_spawner = Spawner(drawn, simulated, Asteroid, 2) wait_t = int(config.delta_t*1000) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.key == pygame.K_w: test_cube.pos = add(test_cube.pos, (0, move, 0)) if event.key == pygame.K_s: test_cube.pos = add(test_cube.pos, (0, -move, 0)) if event.key == pygame.K_a: test_cube.pos = add(test_cube.pos, ( -move, 0, 0)) if event.key == pygame.K_d: test_cube.pos = add(test_cube.pos, (move, 0, 0)) print("x: {} y: {} z: {}".format(test_cube.pos[0], test_cube.pos[1], test_cube.pos[2])) for entity in simulated: entity.sim() asteroid_spawner.sim() # Collisions # Despawn for entity in simulated: if entity.pos[0] < config.x_min - config.margin: simulated.remove(entity) drawn.remove(entity) mouse_pos = get_input() test_cube.pos = (mouse_pos[0], mouse_pos[1], 0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) for entity in drawn: entity.draw() pygame.display.flip() pygame.time.wait(wait_t)
def run(self): player = Player((Settings.WIDTH // 2, Settings.HEIGHT // 2)) if Settings.AGENT_PLAYER: player.attach_controller(AgentController(player)) else: player.attach_controller( HumanController(player, { "FORWARD": pg.K_w, "BACKWARD": pg.K_s })) if Settings.AGENT_PLAYER: episode = player.controller.agent.current_episode start_time = t.time() l = 0 while True: player.reset((Settings.WIDTH // 2, Settings.HEIGHT // 2)) if Settings.AGENT_PLAYER: player.controller.reset_training_data() # 0: Players, 1: Player Projectiles, 2: Enemies, 3: Enemy Projectiles self.env = {0: [player], 1: [], 2: [], 3: []} self.spawner = Spawner(self.env) ScoreManager.SCORE = 0 while True: e = pg.event.poll() if (e.type == pg.QUIT): quit(0) deleted_elements = [] collidable_elements = [] ScoreManager.TRIGGER = 0 # Check Collisions for key in self.env: collidable_elements += self.env[key] for i in range(len(collidable_elements)): for j in range(i + 1, len(collidable_elements)): result = collidable_elements[i].check_collide( collidable_elements[j]) if (result): collidable_elements[i].on_collide( collidable_elements[j]) collidable_elements[j].on_collide( collidable_elements[i]) # Handle all GameObjects for key in self.env: for obj in self.env[key]: if obj.destroyed: deleted_elements.append((obj, key)) continue if key % 2 == 0: # Controllable obj.controller.handle(e, self.env) else: # Projectile obj.step() self._delete_elements(deleted_elements) if player.destroyed: # Player dead if Settings.AGENT_PLAYER: player.controller.add_reward(Settings.DIE_REWARD) break else: if Settings.AGENT_PLAYER: reward = Settings.ALIVE_REWARD if ScoreManager.TRIGGER: reward += Settings.KILL_REWARD player.controller.add_reward(reward) self.spawner.spawn() self._render_all() # Use to control the frame rate of the game # Disable while training to make training faster # t.sleep(1/Settings.FRAME_RATE) # Use to save screen: # l += 1 # pg.image.save(self.screen, f"../resources/generated_images/{Settings.LOAD_MODEL_EPISODE}/model-{Settings.LOAD_MODEL_EPISODE}-{l}.png") if Settings.AGENT_PLAYER and Settings.TRAINING_MODE: episode += 1 player.controller.train_wrapper(episode) elapsed_time = t.time() - start_time time_str = t.strftime("%H:%M:%S", t.gmtime(elapsed_time)) output_string = "Episode: {:0>4} Score: {:0>5} Reward: {:07.3f} T+: {}".format( episode, ScoreManager.SCORE, sum(player.controller.rewards), time_str) print(output_string) else: print(f"Game Over. Score: {ScoreManager.SCORE}")