Example #1
0
    def __init__(self, directory, run_id, plot_every, restrict_energy,
                 num_iterations, len_preamble, n_bits, n_hidden, stepsize,
                 lambda_p, initial_logstd, k, noise_power):
        # System Parameters
        self.num_iterations = num_iterations
        self.preamble = util.generate_preamble(len_preamble, n_bits)
        self.restrict_energy = restrict_energy

        # Transmitter Parameters
        groundtruth = util.schemes[n_bits]
        t_args = [
            self.preamble, restrict_energy, groundtruth, n_bits, n_hidden,
            lambda_p, initial_logstd
        ]
        r_args = [self.preamble, k]

        # Receiver Parameters
        self.agent_one = actor.Actor(t_args, r_args, stepsize,
                                     directory + 'agent_1/')
        self.agent_two = actor.Actor(t_args, r_args, stepsize,
                                     directory + 'agent_2/')

        # Parameters to write in the plotted diagrams
        p_args_names = 'run_id total_iters len_preamble stepsize lambda_p initial_logstd noise_power restrict_energy'.split(
        )
        p_args_params = [
            run_id, num_iterations, len_preamble, stepsize, lambda_p,
            initial_logstd, noise_power, restrict_energy
        ]
        self.p_args = dict(zip(p_args_names, p_args_params))

        self.channel = Channel(noise_power)
Example #2
0
    def __init__(self, env, sess):
        self.env = env
        self.sess = sess
        self.experience = collections.deque(maxlen=gf.experienceLength)

        # seed random number
        random.seed()

        # create placeholders for input action and state
        with tf.name_scope('InputPlaceHolders'):
            self.inputState = tf.placeholder(
                dtype=tf.float32,
                shape=(None, self.env.observation_space.shape[0]),
                name='inputState')
            self.inputAction = tf.placeholder(
                dtype=tf.float32,
                shape=(None, self.env.action_space.shape[0]),
                name='inputAction')

        # create critic and target critic
        self.critic = cr.Critic(sess, env, 'critic', self.inputState,
                                self.inputAction, True)
        self.targetCritic = cr.Critic(sess, env, 'targetCritic',
                                      self.inputState, self.inputAction, False)

        # create actor and target actor
        self.actor = ac.Actor(sess, env, 'actor', self.inputState,
                              self.inputAction, self.critic, True)
        self.targetActor = ac.Actor(sess, env, 'targetActor', self.inputState,
                                    self.inputAction, self.targetCritic, False)

        # create weight update operations
        with tf.name_scope('weightedCopy'):
            self.tau = tf.placeholder(dtype=tf.float32, shape=(), name='tau')
            self.update_target_actor = [
                tf.assign(
                    self.targetActor.weights[i],
                    (tf.multiply(self.actor.weights[i], self.tau) +
                     tf.multiply(self.targetActor.weights[i], 1. - self.tau)))
                for i in range(len(self.targetActor.weights))
            ]
            self.update_target_critic = [
                tf.assign(
                    self.targetCritic.weights[i],
                    (tf.multiply(self.critic.weights[i], self.tau) +
                     tf.multiply(self.targetCritic.weights[i], 1. - self.tau)))
                for i in range(len(self.targetCritic.weights))
            ]

        # create data logs holder variables
        self.rewardPerEpisode = tf.placeholder(
            dtype=tf.float32, shape=(), name='rewardPerEpisodePlaceHolder')
        self.rpe_summary = tf.summary.scalar('rewardPerEpisode',
                                             self.rewardPerEpisode)

        # create a fileWriter (only after construction phase is over)
        self.fileWriter = tf.summary.FileWriter(gf.logdir,
                                                tf.get_default_graph())
Example #3
0
 def setup(self):
     import actor
     import lightSource as light
     self.player = actor.Actor(const.mapWidth / 2, const.mapHeight / 2)
     self.curMap = Map()
     self.player.ID_ = "player"
     x = actor.Actor(4, 5, '*')
     y = light.LightSource()
     x.addComponent(y)
     x.register()
Example #4
0
def _LoginNewClient(client):
    """
  A client logs in.  assign it an actor id and send
  that in a login acknowldegement.  Add a new actor
  message for each current actor for the new client,
  and tell all current clients about the new actor
  that logged in. store the new actor in a mapping
  from client to actor instance for future use.
  """
    global g_lastActorId
    global g_actorDict

    newActor = actor.Actor(g_lastActorId)
    g_lastActorId += 1
    data = struct.pack("<BB", MSG_TYPE_LOGIN_ACK, newActor.GetId())
    for priorClient, priorActor in g_actorDict.items():
        p, m, a = priorActor.GetAllStateIds()
        data += struct.pack("<BBBBB", MSG_TYPE_NEW_ACTOR, priorActor.GetId(),
                            p, m, a)  # their current states
        p, m, a = newActor.GetAllStateIds()
        priorClient.send(
            struct.pack("<BBBBB", MSG_TYPE_NEW_ACTOR, newActor.GetId(), p, m,
                        a))  # others about this new actor
    g_actorDict[client] = newActor  # store the new actor
    print g_programName + 'new actor [%s] logged in and created' % newActor.GetId(
    )
    _PrintActorList()
    return data
Example #5
0
    def __init__(self, screen):
        self.screen = screen
        self.accept_input = True
        self.animation = None  # current playing animation
        self.state = ACTIVE  # state that the game starts with. change to experience various features

        self.pallet_town_map = map.Map(
            pygame.image.load(os.path.join('maps', 'pallet_town.png')),
            (-64 * 5, 0))

        self.mc = actor.Actor(
            pygame.image.load(os.path.join('actors', 'mc_final.png')),
            64 * 4 + 4, 64 * 4)
        self.actor_group = pygame.sprite.Group(self.mc)

        # Initialize a screen transition
        self.trans = transition.Transition(screen)
        self.trans.order_swirl()

        # Initialize a text manager
        self.txtmgr = textmanager.Textmanager(screen)

        # Do this only if DIALOGUE is the initial game state
        if self.state == DIALOGUE:
            self.txtmgr.set_string('Boogah boogah boogah!')

        # Initiate a battle manager
        self.btlmgr = battlemanager.BattleManager(screen)
Example #6
0
 def __init__(self):
     """
     Base class for typers.
     """
     pygame.init()
     self.font = pygame.font.Font('fonts/determinationmono.ttf', 32)
     self.antialias = False
     self.color = pygame.Color('white')
     self.text = ''
     self.actor = actor.Actor()
     self.scan_cursor = 0
     self.delay = 0.05
     self.background = pygame.Color('black')
     self.symbols = []
     self.display_symbols = []
     self.letter_spacing = 0
     self.line_spacing = 0
     self.column = 0
     self.line = 0
     self.delay_next = None
     self.delay_skipped_step = False
     self.surface = pygame.Surface((1, 1))
     self.on_symbol = lambda: None
     self.to_on_run_loop = None
     self.on_run_loop = lambda s, o: None
     self.can_skip = True
     self.choice_mode = False
     self.choice = 0
     self.pause = False
Example #7
0
 def addActor(self):
     newActor = actor.Actor(defaults['actor'], defaults['actorName'])
     self.script.addActor(newActor)
     newActor.state.position = defaults['positions'][len(self.script.actors)
                                                     - 2]
     newActor.changeBodyPosition()
     self.buildFocusSelecter(newActor)
     self.script.scriptChanged()
Example #8
0
def part1():
    # Input File
    # filename = "./day15/input.txt"

    # Sample Input
    filename = "./day15/sample1.txt"
    # filename = "./day15/sample2.txt"
    # filename = "./day15/sample3.txt"
    # filename = "./day15/sample4.txt"
    # filename = "./day15/sample5.txt"
    # filename = "./day15/sample6.txt"

    # Cave system
    cave = []

    # Read the file line by line
    with open(filename, "r") as infile:
        for line in infile:
            cave.append([ch for ch in line.rstrip()])

    # Find all the goblins and elves
    actors = []
    for y in range(len(cave)):
        for x in range(len(cave[y])):
            if cave[y][x] in "GE":
                actors.append(actor.Actor(x, y, cave[y][x]))

    # Sort everything in reading order (first by x, then by y)
    actors.sort(key=lambda char: char.x)
    actors.sort(key=lambda char: char.y)

    # Now find what is in everyone's range to start
    for char in actors:
        char.calc_in_range(cave)

    # OK, let's start - starting with round 0
    round = 0

    # Get the initial count of goblins and elves
    goblins = sum([1 for char in actors if char.actor_type == "G"])
    elves = sum([1 for char in actors if char.actor_type == "E"])

    # While there is still something to do
    while goblins > 0 and elves > 0:

        for char in actors:

            # I can only move if I'm not in someone's range
            if not char.in_someones_range:

                # We need the shortest path to an enemy
                nearest_enemies = find_nearest(char, actors, cave)

    # Add the HP for the everyone left
    total_hp = sum([char.HP for char in actors if char.actor_type != "."])
    print(
        f"Part 1: Total is {round} rounds and {total_hp} HP for {total_hp * round}."
    )
Example #9
0
    def _give(self, val):
        match = parens_match.match(val)
        if match:
            new_actor = actor.Actor(match.group('id'), match.group('name'),
                                    self.scene)
            # new_actor = self.scene.new_actor(match.group('name'), match.group('id'))
        else:
            next_identifier = 1
            while self.scene.actors.has_key("%s_%d" %
                                            (actor_name, next_identifier)):
                next_identifier += 1
            identifier = "%s_%d" % (actor_name, next_identifier)

            new_actor = actor.Actor(next_identifier, val, self.scene)

        self.scene.ui.inventory.put_item(new_actor)
        pyglet.resource.media('sound/give.wav').play()
        return True
Example #10
0
 def pause(self, show_sprites=True):
     self.paused = True
     if show_sprites:
         self.play_sound("pause")
         self.new_actor = actor.Actor("paused", "paused", self)
         self.new_actor.sprite.x = self.actors["main"].sprite.x
         self.new_actor.sprite.y = 600
         self.add_actor(self.new_actor)
         self.new_actor = actor.Actor("continue", "paused", self, None,
                                      {"start_state": "continue"})
         self.new_actor.sprite.x = self.actors["main"].sprite.x
         self.new_actor.sprite.y = 450
         self.add_actor(self.new_actor)
         self.new_actor = actor.Actor("exit", "paused", self, None,
                                      {"start_state": "exit"})
         self.new_actor.sprite.x = self.actors["main"].sprite.x
         self.new_actor.sprite.y = 350
         self.add_actor(self.new_actor)
         print "%s is paused." % self.name
Example #11
0
    def __init__(self):
        pyxel.init(255, 255)
        self.x = 0
        self.time_begin = 1555749269.0

        self.icon = {}
        # ImageLoaderを利用したアイコンの登録
        self.icon["mihon"] = actor.Actor(20, 80)
        self.icon["mihon"].imageload("images/search1_8.png")
        self.icon["mihon2"] = actor.Actor(40, 80)
        self.icon["mihon2"].imageload("images/search2_8.png")
        #self.icon["mihon"].imageload("images/mihon.png")
        self.icon["arrow"] = actor.Actor(20, 40)
        self.icon["arrow"].imageload("images/arrow1_up_8.png")
        self.icon["arrow2"] = actor.Actor(40, 40)
        self.icon["arrow2"].imageload("images/arrow2_up_8.png")

        pyxel.mouse(True)

        pyxel.run(self.update, self.draw)
Example #12
0
 def new_actor(self, actor_name, identifier=None, **kwargs):
     if identifier is None:
         next_identifier = 1
         while self.actors.has_key("%s_%d" % (actor_name, next_identifier)):
             next_identifier += 1
         identifier = "%s_%d" % (actor_name, next_identifier)
     new_actor = actor.Actor(identifier, actor_name, self, **kwargs)
     if kwargs.has_key('walkpath_point'):
         new_actor.walkpath_point = kwargs['walkpath_point']
         new_actor.sprite.position = self.walkpath.points[
             new_actor.walkpath_point]
     self.actors[identifier] = new_actor
     self.zenforcer.init_groups()
     return new_actor
Example #13
0
def Recv_NewActor(data):
    """
  A new client logged into the server. Add it to
  our actor lookup and set the initial states to those
  specified on the server
  """
    global g_actorDict
    newActorId, p, m, a = struct.unpack("<BBBB", data[0:4])
    print g_programName + 'new actor id is %s' % (newActorId, )
    newActor = actor.Actor()
    newActor.SetAllStateIds([p, m, a])
    g_actorDict[newActorId] = newActor
    print g_inputPrompt
    return data[4:]
Example #14
0
def Recv_LoginAck(data):
    """
  Login acknowledgement from server.  Assign
  the local actor id to the value passed in
  the message and create the actor instance.
  The instance is stored for subsequent use
  """
    global g_actorId
    global g_actorDict
    (g_actorId, ) = struct.unpack("<B", data[0])
    print g_programName + 'Login ok, local actor id is %s' % (g_actorId, )
    print g_inputPrompt
    g_actorDict[g_actorId] = actor.Actor()
    return data[1:]
Example #15
0
 def addCrewByName(self, name, role):
     db = DatabaseConnector.DataBase()
     nconst = db.get_person_id_by_name(name)
     avgrating = db.get_averagerating_by_id(nconst[0])
     if nconst[0] is None:
         print("Actor not found!")
         return
     else:
         ordering = len(self.actors) + 1
         if ordering > 10:
             print("Too many Actors in Movie " + self.title)
         else:
             actordata = [nconst[0], ordering, role, avgrating]
             self.actors.append(actor.Actor(actordata))
     db.closeConnection()
Example #16
0
    def load_actors(self):
        """Initialize actors and update them with any values specified in the info dict"""
        for identifier, attrs in self.info['actors'].viewitems():
            # Initialize and store
            new_actor = actor.Actor(name=attrs['name'],
                                    identifier=identifier,
                                    scene=self,
                                    attrs=attrs)

            # Obey walk paths
            if attrs.has_key('walkpath_point'):
                new_actor.walkpath_point = attrs['walkpath_point']
                new_actor.sprite.position = self.walkpath.points[
                    new_actor.walkpath_point]
            self.add_actor(new_actor, reset_shadows=False)
        self.update_shadows()
Example #17
0
    def __init__(self, numChans, states, numSteps):
        self.actions = np.zeros((numChans + 1, numChans))
        for k in range(0, numChans):
            self.actions[k + 1, k] = 1
        self.numChans = numChans
        self.numActions = np.shape(self.actions)[0]
        self.actionTally = np.zeros(numChans + 1)
        self.actionHist = np.zeros((numSteps, numChans))
        self.actionHistInd = np.zeros(numSteps)

        self.goodChans = np.ones(numChans)

        self.states = states
        self.numStates = np.shape(states)[0]

        self.stateHist = np.zeros((numSteps, numChans))
        self.stateTally = np.zeros(self.numStates)

        self.rewardHist = np.zeros(numSteps)
        self.rewardTally = np.zeros(numChans + 1)
        self.cumulativeReward = np.zeros(numSteps)
        self.rewardTrans = np.zeros(
            (self.numActions, self.numStates, self.numStates))

        self.exploreHist = []

        self.type = "ac"
        self.hyperType = "learning"

        self.policy = np.zeros(numChans)

        self.n_actions = numChans + 1
        self.n_features = numChans

        sess = tf.Session()

        self.actor_ = actor.Actor(self,
                                  sess,
                                  self.n_features,
                                  self.n_actions,
                                  lr=0.001)
        self.critic_ = critic.Critic(self, sess, self.n_features, lr=0.01)

        sess.run(tf.global_variables_initializer())
Example #18
0
 def __init__(self):
     self.episodes = 1000
     self.gamma = 0.99
     self.actor = actor.Actor(4)
     self.critic = critic.Critic()
     actor_learning_rate = 1e-6
     critic_learning_rate = 1e-8
     self.actor_opt = Adam()
     self.critic_opt = Adam()
     current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
     actor_log_dir = 'logs/gradient_tape/' + current_time + '/actor'
     critic_log_dir = 'logs/gradient_tape/' + current_time + '/critic'
     reward_log_dir = 'logs/gradient_tape/' + current_time + '/reward'
     self.actor_summary_writer = tf.summary.create_file_writer(
         actor_log_dir)
     self.critic_summary_writer = tf.summary.create_file_writer(
         critic_log_dir)
     self.reward_summary_writer = tf.summary.create_file_writer(
         reward_log_dir)
     self.actor_save_dir = 'saved_models/' + current_time + '/actor'
     self.critic_save_dir = 'saved_models/' + current_time + '/critic'
Example #19
0
def main(args):
    with open(args.config, 'r') as f:
        config = json.load(f)

    market = asset.Market()
    assets = [asset.gen_asset() for _ in xrange(config['assets'])]
    actors = [actor.Actor(i) for i in xrange(config['actors'])]
    for a in assets:
        movement_mean = random.uniform(-1.0, 1.0)
        movement_std_dev = random.uniform(0.1, 2.0)
        for _ in xrange(config['memory']):
            for _ in xrange(0, random.randint(0, MAX_TRANSACTIONS)):
                buyer, seller = random.sample(range(config['actors']), 2)
                change = random.normalvariate(movement_mean, movement_std_dev)
                settle_price = (1 + change / 100.) * a.price
                if a.symbol not in actors[seller].positions or actors[
                        seller].positions[a.symbol].quantity == 0:
                    quantity = random.randint(0, a.outstanding)
                    a.outstanding -= quantity
                    actors[buyer].buy(a, quantity, settle_price, [market])
                elif actors[seller].positions[a.symbol].quantity > 0:
                    shares = a.outstanding + actors[seller].positions[
                        a.symbol].quantity
                    quantity = random.randint(0, shares)
                    if quantity > actors[seller].positions[a.symbol].quantity:
                        quantity_from_seller = actors[seller].positions[
                            a.symbol].quantity
                    else:
                        quantity_from_seller = quantity
                    a.outstanding -= (quantity - quantity_from_seller)
                    a.price = settle_price
                    actors[buyer].buy(a, quantity, settle_price,
                                      [actors[seller], market])
                    actors[seller].sell(a, quantity_from_seller, settle_price,
                                        actors[buyer])
                a.price = settle_price
        print a

    for a in actors:
        print a
Example #20
0
    def construct(self):
        """ Initialize physics world """
        self.player = actor.Actor(self, self.game)
        self.game.register_actor(self.player)
        self.game.display.main_player = self.player
        #self.game.register_actor(wall.Wall(self, self.game))
        #self.game.register_actor(wall.Wall(self, self.game, (200, 200), (400, 200)))
        #self.game.register_actor(wall.Wall(self, self.game, (400, 300), (500, 300)))
        #self.game.register_actor(wall.Wall(self, self.game, (10, 10), (1000, 10)))
        #self.game.register_actor(wall.Wall(self, self.game, (1000, 10), (1000, 1000)))
        #self.game.register_actor(wall.Wall(self, self.game, (10, 10), (10, 1000)))
        #self.game.register_actor(mob.Mob(self, self.game, random.randint(15,700), random.randint(15, 1000)))
        #self.game.register_actor(mob.Mob(self, self.game, random.randint(15,700), random.randint(15, 1000)))
        #self.game.register_actor(mob.Mob(self, self.game, random.randint(15,700), random.randint(15, 1000)))

        #self.game.register_actor(wall.Wall(self, self.game, (-10000, 10), (10000, 10)))

        self.generate_sector((0, 0))
        self.generate_sector((1, 0))
        self.generate_sector((-1, 0))
        self.generate_sector((0, 1))
        self.generate_sector((0, -1))
        self.generate_sector((1, 1))
        self.generate_sector((1, -1))
        self.generate_sector((-1, 1))
        self.generate_sector((-1, -1))

        def platform_collision_presolve(arbiter, space, data):
            #if arbiter.contact_point_set.normal[1] > .5:
            #    return False
            #elif arbiter.contact_point_set.normal[1] < -.5:
            #    keys = pygame.key.get_pressed()
            #    if keys[K_s]:
            #        return False
            #    return True
            return True
            
        platform_handler = self.space.add_collision_handler(1, 2)
        platform_handler.pre_solve = platform_collision_presolve
Example #21
0
if __name__ == "__main__":
	""" 
	Simple standalone test routine for Leaner class
	"""
	import json
	import actor

	with open('parameters.json', 'r') as f:
		params = json.load(f)
	params['actor']['T'] = 2000
	params['actor']['wait_shared_memory_clear'] = False

	param_set_id = db_initializer.initialize(params)

	mp_manager = mp.Manager()
	status_dict = mp_manager.dict()
	shared_state = mp_manager.dict()
	shared_mem = mp_manager.Queue()

	status_dict['quit'] = False
	status_dict['Q_state_dict_stored'] = False
	status_dict['request_quit'] = False

	l = Learner(params, param_set_id, status_dict, shared_state, shared_mem)

	actor = actor.Actor(params, param_set_id, 0, status_dict, shared_state, shared_mem)
	actor.run()

	l.learn()
Example #22
0
 def spawn(
     cls, location: Location, ai_cls: Optional[Type[AI]] = None
 ) -> actor.Actor:
     self = cls()
     return actor.Actor(location, self, ai_cls or cls.DEFAULT_AI)
Example #23
0
ToDo:
  -p   Run on specific port

"""

MAINPR = processor.MainProcessor
SETFILE = "settings.json"

if __name__ == '__main__':
    try:
        with open(SETFILE, "r") as f:
            settings = json.loads(f.read())
        if sys.argv[1] == 'client':
            sole_actor = actor.Actor(targetProcessor=MAINPR,
                                     threads=settings['clientThreads'],
                                     bind_ip=settings['clientIP'],
                                     bind_port=settings['clientPort'],
                                     address_book=settings['addressBook'])
            signal.pause()
        elif sys.argv[1] == 'server':
            if '-r' in sys.argv[2:]:
                command = ' '.join(sys.argv[(sys.argv.index('-r') + 1):])
                console = actor.Console(targetProcessor=MAINPR,
                                        cmd=command,
                                        threads=settings['serverThreads'],
                                        bind_ip=settings['serverIP'],
                                        bind_port=settings['serverPort'],
                                        address_book=settings['addressBook'])
            else:
                console = actor.Console(targetProcessor=MAINPR,
                                        threads=settings['serverThreads'],
Example #24
0
def main():
    random.seed()
    pygame.init()
    pygame.display.set_caption("hello world")
    pygame.font.init()

    surface_reg = graphics.SurfaceRegistry()

    game = Game()

    tile_types = {
        '#': TileType(False, '#', 'A hard stone wall.'),
        '.': TileType(True, '.', 'A simple stone floor.'),
    }
    game.tile_grid = TileGridFromString(tile_types,
                                        SILLY_STARTING_MAP_FOR_TESTING)

    PLAYER = 0
    player = actor.Actor(PLAYER, 'player')
    player.UpdatePairs(
        (('pos', (5, 5)), ('image', '@'), ('desc', "A very simple dood.")), )
    player.PickUp(
        Item('human feet', '', 'One right, one left.', [IntAdd('MOV', 4)]))
    game.entities.append(player)

    SPIDER = 1
    spider = actor.Actor(PLAYER, 'spider')
    spider.UpdatePairs(
        (('pos', (10, 5)), ('image', 'S'), ('desc', "Creepy and crawly.")), )
    spider.PickUp(
        Item('small health potion', '!', 'Don\'t drop it!',
             [FractionAdd('HP', 15, 'smells nice')]))
    spider.PickUp(Item('gold', '0', 'Shiny', []))
    game.entities.append(spider)

    # Spawn a random item to play with.
    for _ in range(5):
        valid_tiles = ValidTiles(game.tile_grid, game.entities)
        valid_pos = random.choice(valid_tiles)
        random_item = random.choice(item_compendium)
        game.entities.append(SpawnItem(random_item, 1, valid_pos))

    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

    info_surface = screen.subsurface(
        (graphics.TILE_SIZE * 41, graphics.TILE_SIZE * 2,
         graphics.TILE_SIZE * 10, graphics.TILE_SIZE * 40))

    running = True

    map_frame = graphics.Frame(
        surface_reg, screen,
        (0, 0, graphics.TILE_SIZE * 40, graphics.TILE_SIZE * 40))

    selector = RegisterMarkerSurface(surface_reg, [0, 100, 100, 10])
    MoveAction.MARKER_SURFACE = RegisterMarkerSurface(surface_reg,
                                                      [100, 0, 100, 10])
    GetAction.MARKER_SURFACE = RegisterMarkerSurface(surface_reg,
                                                     [50, 50, 100, 10])
    MeleAction.MARKER_SURFACE = RegisterMarkerSurface(surface_reg,
                                                      [200, 50, 50, 10])

    actions = None

    previous_mouse_grid_pos = None
    desc = None

    clock = pygame.time.Clock()

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEMOTION:
                game.mouse_pos = pygame.mouse.get_pos()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                game.left_mouse = True

        if game.KillPending():
            # This is probably not necessary in the long run, but for the moment it
            # prevents the "attack" marker from appearing after killing an entity.
            actions = None

        if not actions:
            actions = GenerateActions(game, player)

        time_delta = clock.tick()

        screen_center = map_frame.Dimensions() / 2
        center_to_player = Vec2d(
            player.pos[0] * graphics.TILE_SIZE,
            player.pos[1] * graphics.TILE_SIZE) - screen_center
        camera_offset_diff = center_to_player - map_frame.camera_offset
        if (Distance(map_frame.camera_offset, center_to_player) >
                graphics.TILE_SIZE * 0.5):
            map_frame.camera_offset = Lerp(map_frame.camera_offset,
                                           center_to_player,
                                           1.0 / 400 * time_delta)

        grid_mouse_pos = graphics.GridPos(map_frame.camera_offset,
                                          game.mouse_pos)

        if game.left_mouse:
            decided_action = None
            for a in actions or []:
                if a.Pos() == grid_mouse_pos:
                    decided_action = a

            if decided_action:
                decided_action.Run(game, player)
                actions = None
            else:
                # TODO: Eventually, there should be an ingame log and this'll show up
                # there.
                print('Nothing to do, there.')

        game.left_mouse = False

        GRID = 0
        ACTOR = 1
        OVERLAY = 2

        # Render the screen: tiles, entities, UI elements.
        for pos, type in game.tile_grid.Iterate():
            map_frame.AddTask(graphics.TiledPos(pos), GRID,
                              type.surface_handle())

        for e in game.entities:
            image = e.GetOr('image')
            pos = e.GetOr('pos')
            if not (image and pos): continue
            map_frame.AddTask(graphics.TiledPos(pos), ACTOR, image)

        map_frame.AddTask(graphics.TiledPos(grid_mouse_pos),
                          OVERLAY,
                          selector,
                          rgb_add=True)

        for a in actions or []:
            for m in a.Markers():
                if not (m.pos and m.surface): continue
                map_frame.AddTask(graphics.TiledPos(m.pos),
                                  OVERLAY,
                                  m.surface,
                                  rgb_add=True)

        if not game.tile_grid.HasTile(grid_mouse_pos):
            desc = None
        else:
            desc = f'{grid_mouse_pos}:\n{game.tile_grid.Get(grid_mouse_pos).desc()}'
            for e in game.entities:
                pos = e.GetOr('pos')
                if pos and pos == grid_mouse_pos:
                    desc = f'{grid_mouse_pos}:\n{str(e)}'
                    break

        previous_mouse_grid_pos = grid_mouse_pos

        if desc:
            graphics.BlitText(surface_reg, info_surface, desc)

        map_frame.Render()

        pygame.display.flip()
        screen.fill((0, 0, 0))
Example #25
0
def populate_movies():
    """Populates a list of movies."""

    world_war_z = media.Movie({
        "film_id":
        "tt0816711",
        "film_title":
        "World War Z",
        "film_synopsis":
        "A epidemiologist struggles to find the cure for the zombie virus "
        "battling against time",
        "film_poster_url":
        "https://upload.wikimedia.org/wikipedia/en/d/dc/World_War_Z_poster"
        ".jpg",
        "film_trailer_url":
        "https://www.youtube.com/watch?v=M5Y_nOkFvbY",
        "film_actors": [actor.Actor("Brad", "Pitt")],
        "film_year":
        2013
    })

    zombieland = media.Movie({
        "film_id":
        "tt127834",
        "film_title":
        "Zombieland",
        "film_synopsis":
        "A zombie comedy about a band of zombie apocalypse survivors "
        "looking for a safe haven in the United States.",
        "film_poster_url":
        "https://upload.wikimedia.org/wikipedia/en/a/a3/"
        "Zombieland-poster.jpg",
        "film_trailer_url":
        "https://www.youtube.com/watch?v=8m9EVP8X7N8",
        "film_actors": [
            actor.Actor("Woody", "Harrelson"),
            actor.Actor("Jesse", "Eisenberg"),
            actor.Actor("Emma", "Stone")
        ],
        "film_year":
        2009
    })

    shaun_of_the_dead = media.Movie({
        "film_id":
        "tt0365748",
        "film_title":
        "Shaun of the Dead",
        "film_synopsis":
        "Friends fight their way through zombies in hilarious fashion.",
        "film_poster_url":
        "http://landmarktheatre.org/wp-content/uploads/"
        "2014/10/Shaun-of-the-Dead-Poster.jpg",
        "film_trailer_url":
        "https://www.youtube.com/watch?v=yfDUv3ZjH2k",
        "film_actors":
        [actor.Actor("Simon", "Pegg"),
         actor.Actor("Nick", "Frost")],
        "film_year":
        2004
    })

    twenty_eight_days_later = media.Movie({
        "film_id":
        "tt0289043",
        "film_title":
        "28 Days Later",
        "film_synopsis":
        "A coma patient awakens to discover that infected "
        "cannibals have taken over London, and maybe the world.",
        "film_poster_url":
        "http://www.movierulz.to/wp-content/uploads/2013/"
        "07/28-Days-Later.jpg",
        "film_trailer_url":
        "https://www.youtube.com/watch?v=c7ynwAgQlDQ",
        "film_actors": [actor.Actor("Cillian", "Murphy")],
        "film_year":
        2002
    })

    dawn_of_the_dead_remake = media.Movie({
        "film_id":
        "tt0363547",
        "film_title":
        "Dawn of the Dead",
        "film_synopsis":
        "A group of survivors takes refuge in a mall.",
        "film_poster_url":
        "https://upload.wikimedia.org/wikipedia/en/1/16/"
        "Dawn_of_the_Dead_2004_movie.jpg",
        "film_trailer_url":
        "https://www.youtube.com/watch?v=rhsutNfvuAY",
        "film_actors":
        [actor.Actor("Sarah", "Polley"),
         actor.Actor("Ving", "Rhames")],
        "film_year":
        2004
    })

    dead_snow = media.Movie({
        "film_id":
        "tt127834",
        "film_title":
        "Dead Snow",
        "film_synopsis":
        "A group of Norweigan friends combats Nazi zombies.",
        "film_poster_url":
        "https://upload.wikimedia.org/wikipedia/en/1/11/"
        "Dodsno.jpg",
        "film_trailer_url":
        "https://www.youtube.com/watch?v=lEQwEmeWnyI",
        "film_actors":
        [actor.Actor("Vegar", "Hoel"),
         actor.Actor("Charlotte", "Frogner")],
        "film_year":
        2009
    })

    # Return the list of the movies to be rendered on the webpage
    return [
        world_war_z, zombieland, shaun_of_the_dead, twenty_eight_days_later,
        dawn_of_the_dead_remake, dead_snow
    ]
Example #26
0
        li, = ax.plot(index_list, reward_list, '-')
        # draw and show it
        fig.canvas.draw()
        plt.show(block=False)
    epsilon = 0.6
    #initialize gym environment
    env = gym.make("CartPole-v0")
    observation = env.reset()
    print observation.shape
    rewardList = []

    # Monitor Env
    #env.monitor.start('cartpole-hill/', force=True)

    #Initialize Actor
    actor = actor.Actor(4, 2)
    actor.createModel()
    #Initialize Critic
    critic = critic.Critic(4)
    critic.createModel()
    #for n policies
    for i in range(NUM_EPOCHS):
        #epsilon=epsilon-0.4*(float(i)/NUM_EPOCHS)
        if epsilon > 0.1:
            epsilon = epsilon - 0.001
        #for each rollout <s,a,r>
        observation_old = env.reset()
        T = []
        tot_reward = 0
        for k in range(1000):
            #env.render()
Example #27
0
vacation = movie.Movie(
    "National Lampoon's Christmas Vacation",
    "http://upload.wikimedia.org/wikipedia/en/5/53/NationalLampoonsChristmasVacationPoster.JPG",
    "www.youtube.com/watch?v=NBTTipJX-h4")

dumb = movie.Movie(
    "Dumb & Dumber",
    "http://upload.wikimedia.org/wikipedia/en/6/64/Dumbanddumber.jpg",
    "www.youtube.com/watch?v=2fvoau0ekWk")

###########################
# Actors :
###########################
leonardo = actor.Actor(
    "Leonardo Dicaprio",
    "https://pbs.twimg.com/profile_images/344513261567840137/c253a2c039a701b65d5b2e92fc1735cc_normal.jpeg",
    "http://en.wikipedia.org/wiki/Leonardo_DiCaprio")

duchess = actor.Actor(
    "Margot Robbie",
    "https://pbs.twimg.com/profile_images/425523950341218305/DSrCtA3Y_normal.jpeg",
    "http://en.wikipedia.org/wiki/Margot_Robbie")

donnie = actor.Actor(
    "Jonah Hill",
    "https://gp3.googleusercontent.com/-IezDMxxplG8/AAAAAAAAAAI/AAAAAAAAAB8/Tr6-JLpNISE/s48-c-k-no/photo.jpg",
    "http://en.wikipedia.org/wiki/Jonah_Hill")

travolta = actor.Actor(
    "John Travolta",
    "https://gp3.googleusercontent.com/-OgFiKlkXz48/AAAAAAAAAAI/AAAAAAAAACg/JCLtS6y72NQ/s48-c-k-no/photo.jpg",
    def train_step(self, progress):
        """
        Update policy through the following 4 steps:
            1. Generate a batch of episodes
            2. Define Q through Critic
            3. Define V by minimizing the dual
            4. Define a new policy by fitting an actor

        Updates:
            self.q_critic
            self.v_critic
            self.actor

        Calls:
            generate_episode
            q_critic.Q_Critic
            v_critic.V_Critic
            actor.Actor

        :return: None
        """

        prev_time = time.clock()
        for i in range(0, NUMBER_OF_BATCHES):
            self.generate_episode()
        print("---Generated Episodes in ", int(time.clock() - prev_time),
              " Seconds---")

        n = 0.0
        reward_sum = 0.0
        for i in range(0, NUMBER_OF_BATCHES):
            rollout = self.rollouts[0]
            for j in range(0, rollout.length):
                reward_sum += rollout.rewards[j]
                n += 1
        average_reward = reward_sum / n

        print("---------------------")
        print("----Average Reward: ", average_reward, "----")
        print("---------------------")

        prev_time = time.clock()
        self.q_critic = q_critic.QCritic(self.rollouts)
        print("---------------------")
        print("---Q-Critic fitted in ", int(time.clock() - prev_time),
              " Seconds---")
        print("---------------------")

        prev_time = time.clock()
        self.v_critic = v_critic.VCritic(self.rollouts, self.q_critic)
        print("---------------------")
        print("---V-Critic fitted in ", int(time.clock() - prev_time),
              " Seconds---")
        print("---------------------")

        prev_time = time.clock()
        self.actor = ac.Actor(self.rollouts, self.q_critic, self.v_critic,
                              self.actor, progress)
        print("---------------------")
        print("---Policy fitted in ", int(time.clock() - prev_time),
              " Seconds---")
        print("---------------------")

        self.rollouts = ()
        self.average_rewards += (average_reward, )
Example #29
0
    while not count:
        count = input("Enter an integer wordcount greater than 1000: "
                      )  # TODO: verify `count` is over 1000
        try:
            count = int(count)
            break
        except ValueError:
            print("%s isn’t an integer…" % count)
            count = None

    output = codecs.open(
        os.path.split(current_file_path)[0] + "/output/output.html", "w",
        "utf-8")

    tng_actors = {
        member: actor.Actor(all_tng_text, member, cast, 3)
        for member in cast
    }
    html = "<html lang='en'>\n    <head>\n        <title>B-9 Indifference</title>\n        " + \
           "<meta charset='UTF-8'>\n        " + \
           "<link href='styles.css' rel='stylesheet'/>\n    </head>\n    <body>"

    word_count = count
    script = script.Script(1000, tng_actors)
    while word_count > 0:
        episode_text = script.generate_episode()
        episode_length = len(
            list(
                filter(None,
                       re.split(r'\s+', re.sub(r'<(.*?)>+', '',
                                               episode_text)))))
Example #30
0
    print()
    checkname(actor)
    checkalign(actor)
    print("Strength =", actor.get_str(), "Intelligence =", actor.get_int())
    print("Vitality =", actor.get_vit(), "Dexterity =", actor.get_dex())
    print("Charisma =", actor.get_chr(), "Wisdom =", actor.get_wis())
    print("Current level is ",
          actor.get_level(),
          ", HP is ",
          actor.get_hp(),
          "/",
          actor.get_maxhp(),
          sep="")
    print("Current experience is ", actor.get_exp(), ", ", end='', sep='')
    checknextlvl(Hero)
    print()


Hero = actor.Actor()
Hero.set_name(strings.defaultname)
Hero.set_alignment(0)
rollme(Hero)
checkstats(Hero)

while True:
    Hero.damage(Hero.attack(dice.rollprint(Hero), Hero), Hero)
    checkstats(Hero)
    if Hero.get_hp() < 1:
        break
    keyboard.wait(" ")
    # time.sleep(5)