def update(self, time): if Globals.WIN: if Globals.CURRENT_LEVEL == "five": if self.bossWinTimer > 0.0: self.bossWinTimer -= time else: self.exitFinal() return else: if Globals.TIME > 0: Globals.SCORE = Globals.SCORE + 10 * int(Globals.TIME) self.exitGame() return if Globals.PLAYER.isDead: self.timer -= time if self.timer <= 0: self.deadScreen() return if InputManager.getPressed("esc"): self.exitScreen() return Globals.TIME = Globals.TIME - time World.update(time) if not Globals.CHECKPOINT_SET and\ Globals.CURRENT_LEVEL in Globals.CHECKPOINT_POS: if Globals.PLAYER.rect.x > Globals.getCheckpointPos()[0]: Globals.CHECKPOINT_SET = True
def enter_entry(self): if not Globals.PLAYER is None: Globals.PLAYER.kill(False) Globals.PLAYER = None World.cleanupCompletely() Globals.CURRENT_LEVEL = "one" Globals.initSunTracker(True) Globals.PLAYER_MAX_HEALTH = 15 SKILL_MAX_HEALTH = 0 PLAYER_REGEN_TIME = 7 PLAYER_DAMAGE = 5 SKILL_DAMAGE = 0 PLAYER_MAX_MP = 10 PLAYER_SKILL = 0 PLAYER_JUMP = 610.0 SKILL_JUMP = 0 ARROW_VELOCITY = 700.0 ARROW_HITS = 1 ARROW_DAMAGE = 2 BOW_COOLDOWN = 0.7 MAX_SKILL = 9 MINI_SUNS = 0 LEVELS_BEAT = 0 SCORE = 0 TIME = 120 Globals.STATE = ControlScreen.ControlScreen()
def run(): global discount time.sleep(1) alpha = 1 t = 1 episode_hist = [] while True: # Pick the right action s = World.player max_act, max_val = max_Q(s) chosen_act = policy(max_act) (s, a, r, s2) = do_action(chosen_act) episode_hist.append((s, a, r, s2)) # Update Q max_act, max_val = max_Q(s2) inc_Q(s, a, alpha, r + discount * max_val) # Check if the game has restarted t += 1.0 if World.has_restarted(): backPropagate(episode_hist, alpha) World.restart_game() time.sleep(0.01) t = 1.0 episode_hist = [] # Update the learning rate alpha = pow(t, -0.1) # MODIFY THIS SLEEP IF THE GAME IS GOING TOO FAST. time.sleep(0.05)
def move(self, dx, dy): if World.tile_exists(self.location_x + dx, self.location_y + dy): self.location_x += dx self.location_y += dy print(World.tile_exists(self.location_x, self.location_y).intro_text()) else: print("You bump into an invisible wall.")
def get_block_at(self, x, y, background): if y < 0 or y >= World.HEIGHT: return "air" if background: return World.get_id_name(self.background_blocks[y][x]) else: return World.get_id_name(self.foreground_blocks[y][x])
def generate_structure(self, structure, x): #TODO: add background blocks defined separately if structure["type"] == "column": height = random.randint(structure["minheight"], structure["maxheight"]) for y in range(self.heights[x] - height, self.heights[x]): self.set_block_at(x, y, World.get_block(structure["block"]), False) elif structure["type"] == "json": structure_file = open(structure["location"]) structure_json = json.load(structure_file) curr_y = self.heights[x] - len(structure_json["shape"]) for line in structure_json["shape"]: curr_world_x = Convert.chunk_to_world(x, self) for char in line: #find the right chunk chunk = self #world.chunks[Convert.world_to_chunk(x)[1]]- can't really do this... curr_chunk_x = Convert.world_to_chunk(curr_world_x)[0] if curr_chunk_x < WIDTH: if char == " ": block_name = "water" else: block_name = structure_json["blocks"][char] block = World.get_block(block_name) #TODO: add background chunk.set_block_at(curr_chunk_x, curr_y, block, False) if block["entity"] != "": #generate the block entity EntityClass = getattr(importlib.import_module("ent." + block["entity"]), block["entity"]) instance = EntityClass([curr_world_x, curr_y], self) self.entities.append(instance) curr_world_x += 1 curr_y += 1 structure_file.close() elif structure["type"] == "singleblock": self.set_block_at(x, self.heights[x] - 1, World.get_block(structure["block"]), False)
def exitGame(self): ImageManager.unloadSet("debug") AudioManager.unloadSfxSet("debug") World.cleanupCompletely() Globals.PLAYER = None pygame.mixer.music.fadeout(1000) if Globals.CURRENT_LEVEL == "one": Globals.CURRENT_LEVEL = "two" if Globals.LEVELS_BEAT < 1: Globals.LEVELS_BEAT = 1 elif Globals.CURRENT_LEVEL == "two": Globals.CURRENT_LEVEL = "three" if Globals.LEVELS_BEAT < 2: Globals.LEVELS_BEAT = 2 elif Globals.CURRENT_LEVEL == "three": Globals.CURRENT_LEVEL = "four" if Globals.LEVELS_BEAT < 3: Globals.LEVELS_BEAT = 3 elif Globals.CURRENT_LEVEL == "four": Globals.CURRENT_LEVEL = "five" if Globals.LEVELS_BEAT < 4: Globals.LEVELS_BEAT = 4 Globals.MINI_SUNS_INLVL = 0 Globals.STATE = WinScreen.WinScreen() Globals.CHECKPOINT_SET = False
def generate_structure(self, structure, x): if structure["type"] == "column": height = random.randint(structure["minheight"], structure["maxheight"]) for y in range(self.heights[x] - height, self.heights[x]): self.blocks[y][x] = World.get_block(structure["block"]) elif structure["type"] == "json": structure_file = open(structure["location"]) structure_json = json.load(structure_file) curr_y = self.heights[x] - len(structure_json["shape"]) for line in structure_json["shape"]: curr_world_x = Convert.chunk_to_world(x, self) for char in line: #find the right chunk chunk = self #world.chunks[Convert.world_to_chunk(x)[1]]- can't really do this... curr_chunk_x = Convert.world_to_chunk(curr_world_x)[0] if curr_chunk_x < WIDTH: if char == " ": block = "water" else: block = structure_json["blocks"][char] chunk.blocks[curr_y][curr_chunk_x] = World.get_block(block) curr_world_x += 1 curr_y += 1 structure_file.close() elif structure["type"] == "other": #why did I write this? pass
def __init__(self, name, port, approved, usingGlacier2, glacier2Host, glacier2Port, client_prx, ip_string, reporter = None, threshold = 300): """ Initialize a main-to-game session. @param name Server's name. @param port Port that the server listens for clients on. @param approved True if the server is 'approved' by this server, otherwise False. @param usingGlacier2 [bool] True if clients must use Glacier2 to connect. @param glacier2Host Host name of the Glacier2 router. @param glacier2Port Port number that the Glacier2 router listens on. @param client_prx Proxy to the client's callback. @param ip_string IP obtained from the current.con.toString() method. @param reporter Debug reporter. Optional. """ Base_Servant.__init__(self, ip_string, Client_Types.THEATRE_CLIENT_TYPE, 0, reporter); self.name = name; self.port = port; self.config = World.get_world().get_config(); self.database = World.get_world().get_database(); self.approved = approved; self.client_prx = MainToGameSession.ClientSessionPrx.uncheckedCast(client_prx.ice_timeout(8000)); self.usingGlacier2 = usingGlacier2; self.glacier2Host = glacier2Host; self.glacier2Port = glacier2Port; self.player_limit = 100; self.forced_limit = False; self.player_list = {}; self.threshold = threshold; self.current_map = ""; self.current_mode = VTankObject.GameMode.DEATHMATCH;
def run(): global discount time.sleep(1) alpha = 1 t = 1 while True: # Pick the right action s = World.player max_act, max_val = max_Q(s) (s, a, r, s2) = do_action(max_act) # Update Q max_act, max_val = max_Q(s2) inc_Q(s, a, alpha, r + discount * max_val) # Check if the game has restarted t += 1.0 if World.has_restarted(): World.restart_game() time.sleep(0.01) t = 1.0 # Update the learning rate alpha = pow(t, -0.1) # MODIFY THIS SLEEP IF THE GAME IS GOING TOO FAST. time.sleep(0.1)
def render_block(self, x, y, screen, viewport, background): #don't render air if background: block = World.get_block_from_id(self.background_blocks[y][x]) else: block = World.get_block_from_id(self.foreground_blocks[y][x]) if block["name"] != "air": Game.get_world().render_block(block["id"], [Convert.chunk_to_world(x, self), y], block["connectedTexture"], screen, viewport, background, self)
def set_blocks_from_noise(self, x, y, noise, background): #TODO: variable thresholds from biome if noise > -0.4: self.set_block_at(x, y, World.get_block(self.biome["base"]), background) elif noise > -0.5: self.set_block_at(x, y, World.get_block(self.biome["surface"]), background) else: self.set_block_at(x, y, World.get_block("water"), background)
def exitFinal(self): ImageManager.unloadSet("debug") AudioManager.unloadSfxSet("debug") World.cleanupCompletely() AudioManager.loadMusic("title") pygame.mixer.music.play(-1) if Globals.LEVELS_BEAT < 5: Globals.LEVELS_BEAT = 5 Globals.SCORE = Globals.SCORE + 5000*Globals.MINI_SUNS Globals.PLAYER = None Globals.STATE = CompletedGameScreen.CompletedGameScreen() Globals.CHECKPOINT_SET = False
def play(): global gamemode gamemode = PLAYING World.load_data() global viewport viewport = pygame.Rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) global player player = Player.Player([0, 140], "img/player.png") global world world = World.World("defaultworld", player) global hotbarGui hotbarGui = HotbarGUI(player, "img/gui/hotbar.png")
def adjacent_moves(self): """Returns all move actions for adjacent tiles.""" moves =[] if World.tile_exists(self.x + 1, self.y): moves.append(Actions.MoveEast()) if World.tile_exists(self.x - 1, self.y): moves.append(Actions.MoveWest()) if World.tile_exists(self.x, self.y + 1): moves.append(Actions.MoveNorth()) if World.tile_exists(self.x, self.y - 1): moves.append(Actions.MoveSouth()) return moves
def play(): global gamemode gamemode = PLAYING World.load_data() global viewport viewport = pygame.Rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) global player player = Player.Player([0, 140], "img/player.png") global world world = World.World("defaultworld", player) #improve this later global img_target img_target = pygame.image.load("img/target.png").convert_alpha()
def populate(self): #Fill in blocks based on heights for y in range(len(self.foreground_blocks)): for x in range(len(self.foreground_blocks[y])): surface_depth = self.heights[x] + 2 + random.randrange(4) if y < World.SEA_LEVEL: self.set_blocks_at(x, y, World.get_block("air")) elif y < self.heights[x]: self.set_blocks_at(x, y, World.get_block("water")) elif y < surface_depth: self.set_blocks_at(x, y, World.get_block(self.biome["surface"])) else: self.set_blocks_at(x, y, World.get_block(self.biome["base"])) self.decorate()
def updatePosition(entity): entity.rect.x = int(entity.posx) collided = False h = [] h.append(World.hashpos(entity.rect.x, entity.rect.y)) h.append(World.hashpos(entity.rect.x + entity.rect.width, entity.rect.y)) h.append(World.hashpos(entity.rect.x, entity.rect.y + entity.rect.height)) h.append(World.hashpos( entity.rect.x + entity.rect.width, entity.rect.y + entity.rect.height)) for hashVal in h: try: for tile in World.tileBuckets[hashVal].objects(): if pygame.sprite.collide_rect(entity, tile): if entity.rect.x < tile.rect.x: entity.rect.x = tile.rect.x - entity.rect.width - 1 elif entity.rect.x > tile.rect.x: entity.rect.x = tile.rect.x +\ tile.rect.width + 1 entity.velx = 0 entity.posx = entity.rect.x collided = True break if collided: break except IndexError: pass if entity.isGrounded: entity.rect.y += 1 else: entity.rect.y = int(entity.posy) collided = False h = [] h.append(World.hashpos(entity.rect.x, entity.rect.y)) h.append(World.hashpos(entity.rect.x + entity.rect.width, entity.rect.y)) h.append(World.hashpos(entity.rect.x, entity.rect.y + entity.rect.height)) h.append(World.hashpos( entity.rect.x + entity.rect.width, entity.rect.y + entity.rect.height)) for hashVal in h: try: for tile in World.tileBuckets[hashVal].objects(): if pygame.sprite.collide_rect(entity, tile): #entity.vely = 0 if entity.rect.y < tile.rect.y: entity.rect.y = tile.rect.y - entity.rect.height entity.isGrounded = True entity.vely = 0 elif entity.rect.y > tile.rect.y: entity.rect.y = tile.rect.y +\ tile.rect.height + 1 entity.vely = entity.vely + 100 entity.posy = entity.rect.y collided = True break if collided: break except IndexError: pass if not collided: entity.isGrounded = False
def use_discrete(self, world, player, mouse_pos, viewport): pos = player.find_angle_pos(mouse_pos, viewport) block = world.get_block_at(pos, False) if block == "flint": Game.play_sound("sfx/rock/hit.wav") world.set_block_at(pos, World.get_block("flint_knapped_1"), False) elif block == "flint_knapped_1": Game.play_sound("sfx/rock/hit.wav") world.set_block_at(pos, World.get_block("flint_knapped_2"), False) elif block == "flint_knapped_2": Game.play_sound("sfx/rock/hit.wav") world.set_block_at(pos, World.get_block("flint_knapped_3"), False) elif block == "flint_knapped_3": Game.play_sound("sfx/rock/hit.wav") world.set_block_at(pos, World.get_block("flint_knapped_4"), False)
def populate(self): #Fill in blocks based on heights for y in range(len(self.blocks)): for x in range(len(self.blocks[y])): surface_depth = self.heights[x] + 2 + random.randrange(4) if y < World.SEA_LEVEL: self.blocks[y][x] = World.get_block("air") elif y < self.heights[x]: self.blocks[y][x] = World.get_block("water") elif y < surface_depth: #for some reason this sometimes makes base blocks above surface blocks, but it looks cool so I'll probably leave it self.blocks[y][x] = World.get_block(self.biome["surface"]) else: self.blocks[y][x] = World.get_block(self.biome["base"]) self.decorate()
def play(): World.load_tiles() gamePlayer = Player() while gamePlayer.is_alive() and not gamePlayer.victory: room = World.tile_exists(gamePlayer.location_x, gamePlayer.location_y) room.modify_Player(gamePlayer) if gamePlayer.is_alive() and not gamePlayer.victory: print ("What will you do?:\n") available_actions = room.available_Actions() for action in available_actions: print (action) Action_input = raw_input('Action: ') for checkAction in available_actions: if Action_input == checkAction.hotkey: gamePlayer.do_action(checkAction, **checkAction.kwargs) break
def right_click_continuous(self, world, mouse_pos, viewport, background): item = self.get_held_item() block_pos = self.find_angle_pos(mouse_pos, viewport) if item is None: return item.use_continuous(world, self, mouse_pos, viewport) if item.can_place: #try to place the block #don't want to place a solid block over an entity if not background: entities = world.get_nearby_entities(self.get_chunk()) entities.append(self) #check against player too for entity in entities: if entity.collides(block_pos) and entity.background == background and World.get_block(item.name)["solid"]: return if world.get_block_at(block_pos, False) == "water" and \ (not background or world.get_block_at(block_pos, True) == "water"): world.set_block_at(block_pos, World.get_block(item.name), background) blockentity = item.data if blockentity is not None: blockentity.load_image() blockentity.set_pos(block_pos) blockentity.background = background world.create_entity(blockentity) self.remove_held_item()
def __init__(self, w=800, h=600): self._root = Tk() self._root.title("Braitenberg Vehicles") self._root.resizable(width=FALSE, height=FALSE) self._canvas = Canvas(self._root, width=w, height=h, bd=1, relief=SUNKEN, background=self._canvasColor, ) self._menu = Frame(self._root, width=self._menuWidth, height=self._menuHeight, bd=1, relief=SUNKEN, bg=self._menuColor, ) self._canvas.grid(row=0, column=0, sticky=N+W, padx=2, pady=2) self._canvas.grid_propagate(False) self._menu.grid(row=0, column=1, sticky=N+W, padx=2, pady=2) self._menu.grid_propagate(False) self._k11 = StringVar() self._k12 = StringVar() self._k21 = StringVar() self._k22 = StringVar() self._bx = StringVar() self._by = StringVar() self._bs = StringVar() #this is added for the size of the bot self._lx = StringVar() self._ly = StringVar() self._world = World() self._initMenu() self._isRunning = False
def completed(self): """Creates a new startup textbox, with specified text, and places it in the location on the specified world world: Essentially the window to which entities are added to, should be a World object entity: Arbitrary label to hold a new TextBox Entity """ self.world = World(startup_screen_backdrop) hordelogo = MainImage(self.world) hordelogo.location = Vector((screen_size[0]/2),(screen_size[1]/3)) self.world.add_entity(hordelogo) btn_new = ButtonImageNew(self.world) w,h = hordelogo.image.get_size() btn_new.location = Vector(hordelogo.location.get_x(), hordelogo.location.get_y() +h) self.world.add_entity(btn_new) btn_quit = ButtonImageQuit(self.world) w,h = btn_new.image.get_size() btn_quit.location = Vector(btn_new.location.get_x(), btn_new.location.get_y() + h) self.world.add_entity(btn_quit) text = CompletedText(self.world) text.location = Vector(220,120) self.world.add_entity(text)
def __init__(self): # first elements self.world = World() self.events = EventsManager() # second elements self.graphics = GraphicEngine( self.world, self.events) self.physics = PhysicEngine( self.world, self.events)
def __init__(self, *args): """Constructor for the Game class,ensures that the Game class starts on the correct state state: The phase the game is running in, determines what world and entities should be created """ self.world = World(startup_screen_backdrop) self.world.state = "startup"
def RequestJoinGameServer(self, server, current=None): self.refresh_action(); if not self.active_tank: raise VTankException("You must select a tank first!"); world = World.get_world(); game = world.get_game_server_by_name(server.name); if not game: self.report("Tried to get a game server by the name of \"%s\", "\ "but it didn't exist." % (server.name)); raise PermissionDeniedException("That server is not available."); # Generate a key that would be unique. hash_value = "!!ASDFJKL:%s%s%s" % (str(random.randint(0, 10000)), server.name, self.name); key = sha1(hash_value).hexdigest(); joined = True; try: if not game.add_player(key, self.name, self.userlevel, self.active_tank): self.report("%s tried to join %s, but was already in a game." % ( str(self), str(game))); joined = False; except Ice.Exception, e: self.report("Game server %s disconnected forcefully." % server.name); world.kick_user_by_name(server.name); raise PermissionDeniedException("That server is not available.");
def update(self, time): if InputManager.getPressed("up"): self.selectionID -= 1 if self.selectionID < 0: self.selectionID = (Globals.LEVELS_BEAT + 1) elif InputManager.getPressed("down"): self.selectionID =\ (self.selectionID + 1) % (Globals.LEVELS_BEAT + 2) if InputManager.getPressed("enter"): if self.selectionID == 0: World.cleanupCompletely() Globals.PLAYER = None Globals.STATE = EntryScreen.EntryScreen() Globals.CURRENT_LEVEL = "one" elif self.selectionID == 1 and Globals.LEVELS_BEAT > 0: World.cleanupCompletely() Globals.PLAYER = None Globals.STATE = EnterMountainScreen.EnterMountainScreen() Globals.CURRENT_LEVEL = "two" elif self.selectionID == 2 and Globals.LEVELS_BEAT > 1: World.cleanupCompletely() Globals.PLAYER = None Globals.STATE = EnterCaveScreen.EnterCaveScreen() Globals.CURRENT_LEVEL = "three" elif self.selectionID == 3 and Globals.LEVELS_BEAT > 2: World.cleanupCompletely() Globals.PLAYER = None Globals.STATE = EnterSnowScreen.EnterSnowScreen() Globals.CURRENT_LEVEL = "four" elif self.selectionID == 4 and Globals.LEVELS_BEAT > 3: World.cleanupCompletely() Globals.PLAYER = None Globals.STATE = EnterFinalScreen.EnterFinalScreen() Globals.CURRENT_LEVEL = "five" elif self.selectionID == (Globals.LEVELS_BEAT + 1): self.enter_back() if InputManager.getPressed("esc"): self.enter_back() self.time += time if self.time < MapScreen.FADEINTIME: ratio = self.time / MapScreen.FADEINTIME value = int(ratio * 255) halfValue = int(ratio * 127) self.color = pygame.color.Color(value, value, value) self.selectedColor =\ pygame.color.Color(halfValue, value, halfValue)
def play(): World.load_tiles() player = Player() #These lines load the starting room and display the text while player.is_alive() and not player.victory: room = World.tile_exists(player.location_x, player.location_y) room.modify_Player(player) #check again since the room could have changed the player's state print("choose an action:\n") available_actions = room.available_actions() for action in available_actions: print(action) action_input = input('action: ') for action in available_actions: if action_input == action.hotkey: player.do_action(action, **action.kwargs) break
def draw_block_highlight(self, world, mouse_pos, viewport, screen, shift): #if player can break the block at the position, highlight it #if player is holding a block and can place it, render a preview block_pos = self.find_angle_pos(mouse_pos, viewport) held_item = self.get_held_item() if held_item is None: harvest_level = 0 else: harvest_level = held_item.get_harvest_level() block = World.get_block(world.get_block_at(block_pos, shift)) samewater = block["name"] == "water" fgwater = World.get_block(world.get_block_at(block_pos, False))["name"] == "water" if block["breakable"] and block["harvestlevel"] <= harvest_level and (not shift or fgwater): self.render_break_preview(shift, world, block, block_pos, screen, viewport) elif held_item is not None and held_item.can_place and samewater: self.render_block_preview(shift, held_item, world, block_pos, screen, viewport)
rom pygal.maps.world import World wm = World() wm.force_uri_protocol = 'http' wm.title = 'Populations of Countries in North America' wm.add('North America', {'ca': 34126000, 'us': 309349000, 'mx': 113423000}) wm.render_to_file('na_population.svg')
def main(): app = QApplication(sys.argv) world = World() world.start_game() sys.exit(app.exec_())
import simpy import World as w from Perception import Event as e from Platform import Platform as plat, PlatformTask as platTask from matplotlib import pyplot as plt """create simulation objects""" env = simpy.Environment() simpleWorld = w.World(3, 3, env) simpleTask = platTask.PlatformTask('A3') platform1 = plat.Platform('platform 1', env, simpleWorld) """1.create world model(s)""" platform1.WM.createArea(3, 3, 0, 'A') platform1.WM.createArea(1.5, 1.5, 1, 'A1') platform1.WM.createArea(1.5, 1.5, 1, 'A2') platform1.WM.createArea(1.5, 1.5, 1, 'A3') platform1.WM.containArea('A', 'A1', [-0.75, -0.75]) platform1.WM.containArea('A', 'A2', [-0.75, 0.75]) platform1.WM.containArea('A', 'A3', [0.75, 0.75]) platform1.WM.linkAreas('A1', 'A2') platform1.WM.linkAreas('A2', 'A3') platform1.WM.setStartingArea('A1') simpleWorld.setAreaList(platform1.WM.areaList) """2. give tasks""" platform1.giveTask(simpleTask) """3. generate paths""" """4. generate plans""" platform1.plan.addState('start', None, None) platform1.plan.addState('PS1', 'waiting in', 'A1')
def move(self, dx, dy): self.location_x += dx self.location_y += dy print(World.tile_exists(self.location_x, self.location_y).intro_text())
class TestWorld(TestCase): """ Test cases for ``World`` data type. """ def setUp(self): """ Common setup for running tests """ self.width, self.height = 10, 12 self.world = World(self.width, self.height) def test_set(self): """ Tests setting value on location (x,y). """ x, y = 4, 6 self.world.set(x, y) self.assertEqual(self.world.world[y][x], 1) value = 7 self.world.set(x, y, 7) self.assertEqual(self.world.world[y][x], 7) def test_get(self): """ Tests getting value from location (x, y). """ x, y = 3, 5 value = 3 self.world.world[y][x] = 3 self.assertEqual(self.world.get(x, y), value) def test_get_neighbours(self): """ Tests getting neighbours from location. """ x, y = 2, 0 value = 4 self.world.set(x, self.height-1, value) neighbours = self.world.get_neighbours(x, y) self.assertEqual(8, len(neighbours)) self.assertIn(value, neighbours) def test_exposure(self): # Set sample cell to one. x_sample, y_sample = 4, 4 self.world.set(x_sample, y_sample, 1) # Set neighbour sample cell to one. x, y = 4, 5 self.world.set(x, y, 1) self.world.update() value = self.world.get(x_sample, y_sample) self.assertEqual(value, 0) def test_overcrowding(self): # Set sample cell to one. x_sample, y_sample = 4, 4 self.world.set(x_sample, y_sample, 1) # Set neighbour sample cells to one. x, y = 4, 5 self.world.set(x, y, 1) x, y = 5, 4 self.world.set(x, y, 1) x, y = 3, 4 self.world.set(x, y, 1) x, y = 4, 3 self.world.set(x, y, 1) self.world.update() value = self.world.get(x_sample, y_sample) self.assertEqual(value, 0) def test_survival_two_neighbours(self): # Set sample cell to one. x_sample, y_sample = 4, 4 self.world.set(x_sample, y_sample, 1) # Set neighbour sample cells to one. x, y = 4, 5 self.world.set(x, y, 1) x, y = 5, 4 self.world.set(x, y, 1) self.world.update() value = self.world.get(x_sample, y_sample) self.assertEqual(value, 1) def test_survival_three_neighbours(self): # Set sample cell to one. x_sample, y_sample = 4, 4 self.world.set(x_sample, y_sample, 1) # Set neighbour sample cells to one. x, y = 4, 5 self.world.set(x, y, 1) x, y = 5, 4 self.world.set(x, y, 1) x, y = 3, 4 self.world.set(x, y, 1) self.world.update() value = self.world.get(x_sample, y_sample) self.assertEqual(value, 1) def test_birth(self): # Set sample cell to zero. x_sample, y_sample = 4, 4 self.world.set(x_sample, y_sample, 0) # Set neighbour sample cells to one. x, y = 4, 5 self.world.set(x, y, 1) x, y = 5, 4 self.world.set(x, y, 1) x, y = 3, 4 self.world.set(x, y, 1) self.world.update() value = self.world.get(x_sample, y_sample) self.assertEqual(value, 1)
class Model(Thread): def __init__(self, seed, activeQueues, modelRefresh = None): """ init function for Model links queue @type activeQueues: list @param activeQueues: list of active queues from someone interface """ Thread.__init__(self) self.simulatingWorld = World(seed) #Shows, what world is simulating in the model self.passedModelIterations = 0 #Info about how many iterations of main loop have passed self.modelIterationTick = 1 #Info about time interval between loop iterations in c self.state = ModelState.Initialised #Model state from ModelState enum mailbox = Pipe() self.mailbox = mailbox[0] #active queue to listen model commands activeQueues.append(mailbox[1]) self.activeQueues = activeQueues # function that runs for model refresh on client side for each model tick self.modelRefresh = modelRefresh def run(self): """ Thread function overriding @return: None """ self.MainLoop() def stop(self): """ Stop model function finish work, shutdown thread and join @return: None """ self.activeQueues.remove(self.mailbox) self.mailbox.send("shutdown") def MainLoop(self): """ Main Model Loop @todo: rewrite with switch dictionary and run necessary according to it @return: None """ while True: if self.mailbox.poll(): self.state = self.mailbox.recv() if self.state == ModelState.Stopping: self.stop() break if self.state == ModelState.Paused: self.state = self.mailbox.recv() if self.state == ModelState.Running: timeStart = time() self.simulatingWorld.MainLoopIteration() if self.modelRefresh: self.modelRefresh() self.passedModelIterations += 1 timeToSleep =self.modelIterationTick - (time() - timeStart) if(timeToSleep < 0.0001): sys.stderr.write('MainLoop: To many calculations! timeToSleep = ' + str(timeToSleep)) #May be it must write to another place sleep(max(0, timeToSleep))
actions = World.actions states = [] Q = {} E = {} for i in range(World.x): for j in range(World.y): states.append((i, j)) for state in states: temp = {} temp_e = {} for action in actions: temp[action] = 0.0 # Set to 0.1 if following greedy policy temp_e[action] = 0.0 World.set_cell_score(state, action, temp[action]) Q[state] = temp E[state] = temp_e for (i, j, c, w) in World.specials: for action in actions: Q[(i, j)][action] = w World.set_cell_score((i, j), action, w) def do_action(action): s = World.player r = -World.score if action == actions[0]: World.try_move(0, -1) elif action == actions[1]:
class Simulator: """ Game of Life simulator. Handles the evolution of a Game of Life ``World``. Read https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life for an introduction to Conway's Game of Life. """ def __init__(self, world=None): """ Constructor for Game of Life simulator. :param world: (optional) environment used to simulate Game of Life. """ self.generation = 0 if world == None: self.world = World(20) else: self.world = world def update(self) -> World: """ Updates the state of the world to the next generation. Uses rules for evolution. :return: New state of the world. """ self.generation += 1 parameters = self.world.get_parameters() for x in range(0, self.world.width): for y in range(0, self.world.height): neighbours = sum(self.world.get_neighbours(x, y)) if neighbours < min(parameters[0]): # This cell will die due to underpopulation self.world.set(x, y, 0) elif neighbours > max(parameters[0]): # This cell will die due to overpopulation self.world.set(x, y, 0) elif neighbours in parameters[1]: # This cell came to life (or if it already was alive it will stay alive) self.world.set(x, y, 1) elif neighbours in parameters[0]: # This cell survived pass return self.world def get_generation(self): """ Returns the value of the current generation of the simulated Game of Life. :return: generation of simulated Game of Life. """ return self.generation def get_world(self): """ Returns the current version of the ``World``. :return: current state of the world. """ return self.world def set_world(self, world: World) -> None: """ Changes the current world to the given value. :param world: new version of the world. """ self.world = world
import matplotlib.pyplot as plt #Configuration TARGET_FPS = 60 WINDOW_SIZE = 750 FILE_NAME = 'D:\LocalFiles\Github\PathPlanningSim\sample_world.json' WINDOW_START_POS_X = 500 WINDOW_START_POS_Y = 100 WORLD_SCALE = 1 #Initialization os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (WINDOW_START_POS_X, WINDOW_START_POS_Y) pygame.init() screen = pygame.display.set_mode((WINDOW_SIZE, WINDOW_SIZE)) W = World.World(FILE_NAME, screen=screen, world_scale=WORLD_SCALE) A = Agent.Agent(screen=screen) clock = pygame.time.Clock() grid = W.get_occupancy_grid(1) grid.debug_draw() plt.show(block=False) plt.pause(0.1) #Main loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()
g2 = goal[1] policy = [] policy.append((g2, g1)) while g1 != start[0] or g2 != start[1]: x2 = g1 - delta[action_grid[g1][g2]][0] y2 = g2 - delta[action_grid[g1][g2]][1] policy.append((y2, x2)) g1 = x2 g2 = y2 World.showExpand(expanded_grid_states, fgh_dict) World.move() policy.reverse() for p in policy: World.move_bot(p[0], p[1]) time.sleep((World.w1.get() + 0.1) / 100) # print "\nOpened map: \n", np.array(grid) print "\nHeuristic (h): \n", np.array(h_grid) print "\nExpanded grid: \n", np.array(expanded_grid) print "\nCost (g): \n", np.array(cost_grid) print "\nExplored Coordinates: ", expanded_grid_states print "Path Coordinates: ", policy t = threading.Thread(target=search) t.daemon = True t.start() World.begin()
def search(): global x, y, p, states, fgh_dict cost_grid = [[-1 for row in range(y)] for col in range(x)] open = [] open.append((0, 0, start[0], start[1])) closed = [] closed.append(start) expanded_grid = [[-1 for row in range(y)] for col in range(x)] expanded_grid_states = [] action_grid = [[-1 for row in range(y)] for col in range(x)] expand_count = 0 g = 0 # Calculation of f, g and h for each state while True: if World.flag is True: continue init_h() if len(open) == 0: World.noPath() print "No Path exists!" sys.exit() else: open.sort() open.reverse() temp = open.pop() # print "Picked: ", temp # print "Open List: ", open # print "Closed List: ", closed (f, g, tx, ty) = (temp[0], temp[1], temp[2], temp[3]) expanded_grid[tx][ty] = expand_count expand_count += 1 expanded_grid_states.append((ty, tx)) # World.showExpand(expanded_grid_states) # time.sleep((World.w1.get() + 0.1)/ 100) if (tx, ty) == goal: print "Goal Found!!" break for i in range(len(delta)): dx = tx + delta[i][0] dy = ty + delta[i][1] # print (dx, dy) if 0 <= dx < x and 0 <= dy < y: if (dx, dy) not in closed and ( dy, dx) not in walls: # and (x2, y2) not in open_list: g2 = g + cost dx1 = tx - goal[0] dy1 = ty - goal[1] dx2 = start[0] - goal[0] dy2 = start[1] - goal[1] cross = abs(dx1 * dy2 - dx2 * dy1) h2 = h_grid[dx][dy] # Pick one of the below two Tie breaker policy # h2 = h2 + cross*0.1 h2 *= (1 + p) f2 = g2 + h2 open.append((f2, g2, dx, dy)) closed.append((dx, dy)) cost_grid[dx][dy] = g2 action_grid[dx][dy] = i fgh_dict[(dy, dx)] = {'f': f2, 'g': g2, 'h': h2} print "action: \n", np.array(action_grid) # Back tracing the shortest path from goal g1 = goal[0] g2 = goal[1] policy = [] policy.append((g2, g1)) while g1 != start[0] or g2 != start[1]: x2 = g1 - delta[action_grid[g1][g2]][0] y2 = g2 - delta[action_grid[g1][g2]][1] policy.append((y2, x2)) g1 = x2 g2 = y2 World.showExpand(expanded_grid_states, fgh_dict) World.move() policy.reverse() for p in policy: World.move_bot(p[0], p[1]) time.sleep((World.w1.get() + 0.1) / 100) # print "\nOpened map: \n", np.array(grid) print "\nHeuristic (h): \n", np.array(h_grid) print "\nExpanded grid: \n", np.array(expanded_grid) print "\nCost (g): \n", np.array(cost_grid) print "\nExplored Coordinates: ", expanded_grid_states print "Path Coordinates: ", policy
boidRange = tileWidth ** 2 boidCollisionRange = 14 ** 2 boidCollisionWeight = 4 boidVelMatchingWeight = 0.5 boidFlockCenteringWeight = 0.3 boidWallRange = 60 boidwalAvoidWeight = 5000 boidMinSpeed = 45 boidMaxSpeed = 60 boidSize = 6 boidViewAngle = 290 * (math.pi/180) boidConfig = [boidRange, boidCollisionRange, boidCollisionWeight, boidVelMatchingWeight, boidFlockCenteringWeight, boidwalAvoidWeight, boidMinSpeed, boidMaxSpeed, boidSize, boidViewAngle, walls, boidWallRange] #640, 360 world = World(640, 360, numBoids, boidConfig, rangeClustering, reclusterNum, tileWidth, clusterIndicators); window = pyglet.window.Window(640, 360, fullscreen=False, caption="Boids Simulation") glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) fps_display = pyglet.window.FPSDisplay(window=window) def update(dt): world.updateLocalBoids() world.updateBoidPos(1/15) # schedule world updates as often as possible
def oldconfigToWorld(filename): jason = open(filename, 'r', encoding = 'utf-8') config = json.load(jason) #Meta Data iterations = config['iterations'] splitter = '\n' if 'splitter' in config: splitter = config['splitter'] secondsplitter = None if 'secondsplitter' in config: secondsplitter = config['secondsplitter'] seed = None if 'seed' in config: seed = config['seed'] #World handelers = [] structure = config['world'].split(splitter) if secondsplitter == None: structure = list(map(lambda x: list(x), structure)) else: structure = list(map(lambda x: x.split(secondsplitter), structure)) temp_blocks = config['blocks'] blocks = {} uniqueAttributes = [] for blockType, attrs in temp_blocks.items(): for attr, val in attrs.items(): if attr not in uniqueAttributes: uniqueAttributes.append(attr) nrOfAttributes = len(uniqueAttributes) print(nrOfAttributes) for blockType, attrs in temp_blocks.items(): attributes = [0]*nrOfAttributes blocks[blockType] = (attributes,[[]]) for attr, val in attrs.items(): attributes[uniqueAttributes.index(attr)] = val needNames = config['objectives'] nrOfNeeds = len(needNames) rewards = config['rewards'] actionNames = [] nrOfActions = len(rewards) temp_action = 0 for action, actionreward in rewards.items(): actionNames.append(action) genericreward = [0]*nrOfNeeds if '*' in actionreward: genericreward = [actionreward['*']]*nrOfNeeds for block, (attributes, [rews]) in blocks.items(): blockactionreward = list(genericreward) if block in actionreward: temp_blockactionreward = actionreward[block] if type(temp_blockactionreward) is int or type(temp_blockactionreward) is float: blockactionreward = [temp_blockactionreward]*nrOfNeeds else: if '*' in temp_blockactionreward: blockactionreward = [temp_blockactionreward['*']]*nrOfNeeds for need, val in temp_blockactionreward.items(): if need == '*': continue blockactionreward[needNames.index(need)] = val rews.append(blockactionreward) if 'MoveHandeler' in config: temp_sid = config['MoveHandeler'] handelers.append(MoveHandeler(list(map(lambda x: actionNames.index(x), temp_sid[0])), temp_sid[1])) if 'transform' in config: transformations = {} for action, transform in config['transform'].items(): transformations[actionNames.index(action)] = transform handelers.append(TransformHandeler(transformations)) if len(handelers) == 0: sideeffectHandeler = None else: sideeffectHandeler = MultiHandeler(handelers) #Animats agent = config['agent'] constants = agent['network'] explorationProb = constants['epsilon'] historyMaxLength = constants['max_reward_history'] learningRate = constants['q_learning_factor'] discount = constants['q_discount_factor'] reward_learning_factor = constants['reward_learning_factor'] structureZ = 0.4 if 'surprise_const' in agent: structureZ = agent['surprise_const'] structureR = 0.6 if 'reliablility_const' in agent: structureR = agent['reliability_const'] structureM = 0.05 if 'newnode_const' in agent: structureM = agent['newnode_const'] policyParameter = 0.7 if 'policyParameter' in agent: policyParameter = agent['policyParameter'] position = (0,0) if 'position' in agent: position = agent['position'] #Putting it all together animat = AnimatBrain(nrOfAttributes, nrOfActions, nrOfNeeds, learningRate, discount, structureR, structureZ, structureM, policyParameter, explorationProb, historyMaxLength) world = World(blocks, structure, [animat], [position], [0], [nrOfNeeds], False, sideeffectHandeler) return world
def setUp(self): """ Common setup for running tests """ self.width, self.height = 10, 12 self.world = World(self.width, self.height)
# return sum([i * j for i, j in zip(self._preferences, policy)]) return np.dot(self._preferences, policy) @property def address(self): return self._address @address.setter def address(self, value): self._address = value @property def preferences(self): return self._preferences @preferences.setter def preferences(self, value): self._preferences = value if __name__ == '__main__': myPreferences = [-10, 2, 3] myLocation = 11 myPolicy = [1, 1, 1] myWorld = World.World(3, 1, 3) myAgent = Agent.random(myWorld) print("Agent lives in town {}.".format(myAgent.get_address())) print("Given policy, agent's utility is {}.".format( myAgent.compute_utility(myPolicy)))
def __init__(self, pArgv ): try: lOpts, lArgs = getopt.getopt( pArgv, "hd:sxow:l:b:f:c:i:m:", ["help","debug:=","sound","hex","oct","width=","lines=","bullet_size=","frame=", "colors=", "init_fill_lines=", "max_shot="]) except getopt.GetoptError: self.usage() sys.exit(2) lDebug =False self.cSoundUse = False lModeHex = True; lColumns = 17 lLines = 15 lBulletSize = 40 self.cFrame = 50 lInitFillLines=9 lColors=6 lMaxShot=8 for lOpt, lArg in lOpts: # print "Op:", lOpt , " Arg=", lArg if lOpt in ("-h", "--help"): self.usage() sys.exit() elif lOpt in ("-x", "--hex"): lModeHex = True elif lOpt in ("-s", "--sound"): self.cSoundUse= True elif lOpt in ("-o", "--oct"): lModeHex = False elif lOpt in ("-d", "--debug"): lDebug = int(lArg) elif lOpt in ("-w", "--width"): lColumns = int(lArg) if lColumns < 5 or lColumns > 100 : print "Bad lColumn number ", lColumns sys.exit(2) elif lOpt in ("-l", "--lines"): lLines = int(lArg) if lLines < 5 or lLines > 100 : print "Bad line number ", lLines sys.exit(2) elif lOpt in ("-b", "--bullet_size"): lBulletSize = int(lArg) if lBulletSize < 3 or lBulletSize > 100: print "Bad bullet size ", lBulletSize sys.exit(2) elif lOpt in ("-f", "--frame"): lFrame = int(lArg) if lFrame >= 20 and lFrame <= 100 : self.cFrame = lFrame else: print "Bad Frame rate ", lFrame sys.exit(2) elif lOpt in ("-c", "--colors"): lColors = int(lArg) if lColors< 2 or lColors > 12 : print "Bad colors number ", lColors sys.exit(2) elif lOpt in ("-i", "--init_fill_lines"): lInitFillLines = int(lArg) if lInitFillLines< 2 or lInitFillLines > lLines-2 : print "Bad init fill lines number ", lInitFillLines sys.exit(2) elif lOpt in ("-m", "--max_shot"): lMaxShot = int(lArg) if lMaxShot < 2 or lMaxShot> 12 : print "Bad Max Shot ", lMaxShot sys.exit(2) self.initSound() self.cScreen = pygame.display.set_mode((1024, 768)) self.cClock = pygame.time.Clock() self.cWorld = World.World( self, lDebug, lModeHex, lColumns, lLines, lBulletSize, lColors, lInitFillLines, lMaxShot); self.cRect = self.cScreen.get_rect() self.cBullet = BulletSprite.BulletSprite( random.randint( 1, self.cWorld.MAX_BULLET_TYPE ), self.cWorld ) self.cNextBullet = BulletSprite.BulletSprite( random.randint( 1, self.cWorld.MAX_BULLET_TYPE ), self.cWorld ) self.cBulletGroup = pygame.sprite.RenderPlain(self.cBullet) self.cMemMousePos = (0.0,0.0); self.resetGame()
''' Created on Jul 31, 2015 @author: daqing_yi ''' from World import * from WorldViz import * from PathSamplesGenerator import * if __name__ == '__main__': world01 = World() world01.fromXML("world01.xml") worldViz01 = WorldViz(world01) cont = True while cont == True: cont = worldViz01.update() worldViz01.close() MAP = "map01.png" MAX_RUN_NUM = 5000 SEGMENT = 10 gnr01 = PathSamplesGenerator(worldViz01, MAP, MAX_RUN_NUM, SEGMENT) gnr01.run(20) gnr01.vizDist()
World.R[state] + gamma * World.V[World.next_state(state, other)]) V[state] = state_val World.V = V World.render_cell_value() if __name__ == '__main__': policy = { (0, 0): 'r', (0, 1): 'u', (0, 2): 'u', (1, 0): 'r', (1, 2): 'r', (2, 0): 'r', (2, 1): 'u', (2, 2): 'u', (3, 2): 'l', } # Enabling specific grid World.grid_value_mode() World.create_arrow() t = threading.Thread(target=run) t.daemon = True t.start() World.start_game()
def initGame(self): mixer.init() self.SOUNDS = {} for sound_name in [ 'smb_breakblock', 'smb_bump', 'smb_coin', 'smb_fireball', 'smb_jump-small', 'smb_jump-super', 'smb_kick', 'smb_mariodie', 'smb_pipe', 'smb_powerup', 'smb_powerup_appears', 'smb_stomp', 'smb_warning', 'smb_gameover', 'smb_stage_clear' ]: self.SOUNDS[sound_name] = mixer.Sound(Settings.SOUND_PATH + '{}.wav'.format(sound_name)) self.SOUNDS[sound_name].set_volume(0.2) mixer.music.load('music.ogg') mixer.music.set_volume(0.2) mixer.music.play(-1) self.player_xpos = 700 self.player_ypos = 480 self.gameTimer_tock = 400 self.tock_index = 0 self.lowerTime = True self.level = '1-1' self.slideController = False self.playSlideSound = False self.levelTransition = False self.playedlevelTransition = False self.warningPlayed = False self.coinAmount = 0 self.player = Mario.Mario(self.player_xpos, self.player_ypos) self.world = World.World(1, 1, 1400) self.enemies = sprite.Group() self.goombas = sprite.Group() self.koopas = sprite.Group() self.playerGroup = sprite.Group() self.textGroup = sprite.Group() self.blocks = sprite.Group() self.groundBlocks = sprite.Group() self.QuestionBlocks = sprite.Group() self.normalBlocks = sprite.Group() self.normalPipes = sprite.Group() self.groundUpBlocks = sprite.Group() self.move_steps = sprite.Group() self.long_pipes = sprite.Group() self.flags = sprite.Group() self.flagPoles = sprite.Group() self.castles = sprite.Group() self.instruction_board = sprite.Group() self.brushes = sprite.Group() self.clouds = sprite.Group() self.mountains = sprite.Group() self.unmove_items = sprite.Group() self.fireballs = sprite.Group() self.fireball_amount = 5 self.fireball_timer = 0 self.itemGroup = sprite.Group() self.mushrooms = sprite.Group() self.flowers = sprite.Group() self.coins = sprite.Group() self.score = 0 self.lives = 3 self.spaceDown = False self.newLifeHandle = False self.steadyText = sprite.Group() self.playerGroup.add(self.player) WORLD_MAP.world1_1(game)
class Game(Tk): def __init__(self): Tk.__init__(self) GlobalGame.append(self) self.fps_clock = pg.time.Clock() self.ticks = 0 self.paused = False self.title(Title + " - " + Version) self.iconbitmap(TexturePath + "icon.ico") self.d = KeyBind("d", self, self.loop) self.a = KeyBind("a", self, self.loop) self.mlc = KeyBind("B1-Motion", self, self.loop, release="ButtonRelease-1") self.mrc = KeyBind("B3-Motion", self, self.loop, release="ButtonRelease-3") self.lc = KeyBind("Button-1", self, self.loop, release="ButtonRelease-1") self.rc = KeyBind("Button-3", self, self.loop, release="ButtonRelease-3") self.shift = KeyBind("Shift_L", self, self.loop) self.motion = KeyBind("Motion", self, self.loop, release="KeyRelease-j") self.space = KeyBind("space", self, self.loop) self.resizable(False, False) self.bind("<Escape>", self.pause) self.geometry("1300x800") self.level = World(self) self.pauseMenu = PauseMenu(self) while True: self.loop() def pause(self, event=None): if not self.paused: self.paused = True self.image_original = Image.open(TexturePath + "pbg.png").convert("RGBA") self.image = ImageTk.PhotoImage(self.image_original) self.level.create_image(0, 0, image=self.image) self.level.update() self.pauseMenu.show() else: self.paused = False self.pauseMenu.hide() def loop(self): self.fps_clock.tick(FPS) if self.ticks % 30 == 0: self.title(Title + " - " + Version + " - " + self.level.current_lvl) if self.ticks % 2 == 0 or self.paused: self.update() else: self.update_idletasks() if not self.paused: self.ticks += 1 self.level.update_world(self.ticks) for i in event_queue: i.update(self.ticks)
def inc_Q(s, a, alpha, inc): Q[s][a] += alpha * inc * E[s][a] World.set_cell_score(s, a, Q[s][a])
def inc_Q(s, a, alpha, inc): Q[s][a] *= 1 - alpha Q[s][a] += alpha * inc World.set_cell_score(s, a, Q[s][a])
class Game(QWidget): W = None H = None Ok = False def __init__(self): super().__init__() width, ok = QInputDialog.getInt(self, "Szerokosc swiata", "wprowadz szerokosc", 20, 0, 42, 1) height, ok = QInputDialog.getInt(self, "wysokosc swiata", "wprowadz wysokosc", 20, 0, 32, 1) self.W = World(width, height) self.H = Human(self.W) self.setFocusPolicy(Qt.StrongFocus) self.Start() self.Label = QLabel() saveButton = QPushButton("Zapisz") saveButton.clicked.connect(self.W.Save) loadButton = QPushButton("Wczytaj") loadButton.clicked.connect(self.Load) superButton = QPushButton("Super moc") superButton.clicked.connect(self.H.SuperPower) hbox = QHBoxLayout() hbox.addWidget(saveButton) hbox.addWidget(loadButton) hbox.addWidget(superButton) hbox2 = QHBoxLayout() hbox2.addWidget(self.Label) vbox = QVBoxLayout() vbox.addStretch(1) vbox.addLayout(hbox) vbox.addLayout(hbox2) self.setLayout(vbox) self.resize(1280, 960) self.center() self.setWindowTitle('Michal Krakowiak 165596') self.show() def center(self): screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) def keyPressEvent(self, event): key = event.key() self.Ok = True if key == Qt.Key_Left: self.H.Control(0) self.W.MakeTurn() elif key == Qt.Key_Right: self.H.Control(1) self.W.MakeTurn() elif key == Qt.Key_Up: self.H.Control(2) self.W.MakeTurn() elif key == Qt.Key_Down: self.H.Control(3) self.W.MakeTurn() self.repaint() def mousePressEvent(self, event): p = event.pos() x = p.x() y = p.y() x = x // 30 y = y // 30 if self.W.CheckPoint((x, y)) and self.W.Map[x][y] == WorldField.EMPTY: items = ("Antylopa", "CyberOwca", "Lis", "Owca", "Zolw", "Wilk", "WilczaJagoda", "Trawa", "Guarana", "BarszczSosnowskiego", "Mlecz") item, ok = QInputDialog.getItem(self, "Stworz organizm", "wybierz organizm", items, 0, False) self.ParseTextToOrganism(item, (x, y)) def paintEvent(self, e): self.W.Draw() self.UpdateLabel() qp = QPainter() qp.begin(self) self.Clear(qp) self.DrawOrganisms(qp) qp.end() def Clear(self, qp): for y in range(self.W.Height): for x in range(self.W.Width): qp.eraseRect(x * 30, y * 30, 30, 30) def DrawOrganisms(self, qp): col = QColor(0, 0, 0) col.setNamedColor('#d4d4d4') qp.setPen(col) for y in range(self.W.Height): for x in range(self.W.Width): qp.setBrush(self.ParseSpeciesToColor(self.W.Map[x][y])) qp.drawRect(x * 30, y * 30, 30, 30) def UpdateLabel(self): self.Label.setText("Sila czlowieka: " + str(self.H.Strength) + "; Do ponwnego uzycia mocy: " + str(self.H.SuperPowerCoolDown) + "; Czas trwania mocy: " + str(self.H.SuperPowerTurnsLeft)) def ParseSpeciesToColor(self, species): if species == WorldField.ANTELOPE: return QColor(Qt.cyan) elif species == WorldField.SOW_THISTLE: return QColor(Qt.yellow) elif species == WorldField.SOSNOWSKY_HOGWEED: return QColor(Qt.red) elif species == WorldField.TURTLE: return QColor(Qt.blue) elif species == WorldField.GUARANA: return QColor(Qt.magenta) elif species == WorldField.SHEEP: return QColor(Qt.gray) elif species == WorldField.HUMAN: return QColor(Qt.black) elif species == WorldField.GRASS: return QColor(Qt.green) elif species == WorldField.BELLADONA: return QColor(Qt.darkBlue) elif species == WorldField.WOLF: return QColor(Qt.darkGray) elif species == WorldField.FOX: return QColor(255, 153, 0) # orange elif species == WorldField.CYBER_SHEEP: return QColor(Qt.darkRed) else: return QColor(Qt.white) def ParseTextToOrganism(self, text, point): if text == "Owca": Sheep(self.W, position=point) elif text == "Antylopa": Antelope(self.W, position=point) elif text == "CyberOwca": CyberSheep(self.W, position=point) elif text == "Lis": Fox(self.W, position=point) elif text == "Zolw": Turtle(self.W, position=point) elif text == "Wilk": Wolf(self.W, position=point) elif text == "WilczaJagoda": Belladona(self.W, position=point) elif text == "Trawa": Grass(self.W, position=point) elif text == "Guarana": Guarana(self.W, position=point) elif text == "BarszczSosnowskiego": SosnowskyHogweed(self.W, position=point) elif text == "Mlecz": SowThistle(self.W, position=point) def Start(self): for i in range(4): Sheep(self.W) Wolf(self.W) Antelope(self.W) Turtle(self.W) Fox(self.W) Grass(self.W) SowThistle(self.W) SosnowskyHogweed(self.W) Belladona(self.W) Guarana(self.W) CyberSheep(self.W) def Load(self): self.H = self.W.Load() self.repaint()
# make a jump organism.v_y = 10 def click_handler(event, organism): print "i have been saved!" organism.being_held = True def move_handler(event, organism): organism.x = event.x_root organism.y = event.y_root def release_handler(event, organism): organism.being_held = False print "oh no, out of control again!!" if __name__ == '__main__': # setup the sprite gif_names = ["gifs/bird_right.gif", "gifs/bird_left.gif"] organism = Organism.Organism(update_func, 60, 60, gif_names, click_handler, move_handler, release_handler) organism.frame_interval = 50 # setup and run the world w = World.World() w.add_organism(organism) w.start()
print '' print 'lets get started\n(be patient though the program will take a little time)' if __name__ == '__main__': #if len(sys.argv) < 2: # print 'Sorry you need to enter more arguments!\n The format is: Python raytrace [# of sp' numSphere = int(sys.argv[1]) depth = int(sys.argv[2]) #lay the frame work for my image file image = Image(500,400,'raytrace.ppm') #initialize the world world = World(depth) #create all spheres with a random color for offset in range(numSphere): sphere = Sphere(Point(-6 + (offset* 4), 3.4+ (offset%2), -5+(offset * 5)), 2) sphereColor = ( 1/float(random.randrange(1,5+1)), 1/float(random.randrange(1,5+1)), 1/float(random.randrange(1,5+1)) ) mat = Material(sphereColor) world.add(sphere, mat) #add plane world.add(Plane(), Material((0.1,0.3,0.4)))
# Create a log file myLogger = Logger(parameters['logfilename']) # Create CSV for summary csvfile = open(parameters['csvfilename'], 'w') myLogger.writeCSVHeader(csvfile, parameters) # Loop for multiple runs of the simulation for i in range(parameters['simulation_repetition']): # Clear the logger's cache myLogger.clear() # Seed the random number generator random.seed(i) # Create the world world = World.World(parameters, myLogger) Room.InitRoom(world) # Run for twelve years while world.has_events() and world.day < 365 * 12: world.process() myLogger.appendToCSV(csvfile) sys.stderr.write('Done.\n') myLogger.printSimulationDetail(world) # Explicitly close the log file csvfile.close()
#!/usr/bin/env python ### Simulacion de un ecosistema, en el que existe pasto, conejos y zorros. ### By Gonzalo Odiard, 2006 godiard at gmail.com ### GPL License - http://www.gnu.org/copyleft/gpl.html import gobject, gtk, cairo import math, random import gettext import gtk.glade import World, Animals, Green import glade_util import os print os.path.abspath(__file__) world = World.World() class Tile: def __init__(self, x, y): self.X = x self.Y = y self.STATE = 0 def drawGrid(ctx): ctx.set_line_width(2) ctx.set_source_rgb(0, 0, 0) for n in range(0, World.CANT_TILES): ctx.move_to(World.MARGEN, World.MARGEN + (World.SIZE_TILE * n)) ctx.line_to(World.SIZE_TILE * (World.CANT_TILES - 1) + World.MARGEN,
def inc_Q(s, a, alpha, inc): Q[s][a] *= 1 - alpha Q[s][a] += alpha * inc # print "State::: ",s,"Action ::::",a ,"Q: ", Q[s][a] World.board.delete(World.txt_Ids[str(s[0])+str(s[1])+a]) World.set_cell_score(s, a, Q[s][a])
def main(): world = World() world.run()
color="cyan") obj_2.showText = True obj_1.addChild(obj_2) # ground is the x-y plane # obj_list = [pobj_0] obj_list = [pobj_0, pobj_1, obj_1, obj_2] # obj_list = [pobj_0,pobj_1, obj_1] # obj_list = [pobj_0,pobj_1,pobj_2, obj_1, obj_2] # obj_list = [obj_1, obj_2] n = len(obj_list) torque = np.zeros((n, )) if __name__ == '__main__': dt = 0.01 world = World.World(obj_list) world.set_link_origin(origin) world.set_gravity(g) world.setQ( np.array([0, 0, np.pi / 2 - np.pi / 8, 2 * np.pi / 8], dtype=np.float32)) world.friction = 1.4 # world.setdqdt(np.array([10,0,1,1], dtype=np.float32)) # t_list=[] # e_list=[] # q_list=[] collision = True # collision = False while True: