Example #1
0
    def getActions(self):
        """
        Retoune une liste d'Action (objet) possible pour ce tour.
        """
        # Génération des actions movePawns
        actions = list()
        if self.state[0] < 3:
            for [x, y] in self.pawns[self.current_player]:
                # si le pion a la balle

                if [x, y] in self.balls:
                    continue

                for [x_d, y_d] in [1, 0], [0, 1], [-1, 0], [0, -1]:
                    # Si la destination est hors zone
                    if not ((0 <= x + x_d < WIDTH) and
                            (0 <= y + y_d < HEIGHT)):
                        continue

                    # Si il y a un autre pion à la destination
                    if [x + x_d, y + y_d] in self.pawns[0] or [
                            x + x_d, y + y_d
                    ] in self.pawns[1]:
                        continue

                    actions.append(
                        Action(self, x, y, x + x_d, y + y_d, dtype="movePawn"))

        if self.state[0] < 3:
            x_ball, y_ball = self.balls[self.current_player]
            for [x, y] in self.pawns[self.current_player]:
                # Si je suis le pion osef
                if [x, y] == [x_ball, y_ball]:
                    continue
                # Deux cas de figure, diagonal ou linear
                coef_x = (x - x_ball)
                coef_y = (y - y_ball)

                if coef_x != 0 and coef_y != 0 and abs(coef_x) != abs(coef_y):
                    continue

                if coef_x != 0: coef_x /= abs((x - x_ball))
                if coef_y != 0: coef_y /= abs((y - y_ball))
                collided = False
                for i in range(max(abs(y - y_ball), abs(x - x_ball)) - 1):
                    if [x_ball + (i + 1) * coef_x, y_ball +
                        (i + 1) * coef_y] in self.pawns[0] or [
                            x_ball + (i + 1) * coef_x, y_ball +
                            (i + 1) * coef_y
                        ] in self.pawns[1]:
                        collided = True
                        break

                if not collided:
                    actions.append(
                        Action(self, x_ball, y_ball, x, y, dtype="moveBall"))

        return actions
Example #2
0
 def generate_atk_action(self, input):
     parsed_str = input.split(',')
     target_position = Vec2d(int(parsed_str[0]), int(parsed_str[1]))
     self.queue_action(
         Action(ActionTag.DamagePosition, {
             'absolute': target_position,
             'attacker_id': 1,
             'cost': 4
         }))
     self.reset_input_tree()
	def handle_action(self, action):
		actions = []
		if action.type == ActionTag.DamagePosition:
			attacker = self.manager.get_entity_by_id(action.data['attacker_id'])
			position = None
			
			if 'relative' in action.data:
				position = attacker.get_attribute(AttributeTag.WorldPosition).data['value'] + action.data['relative']
			else:
				position = action.data['absolute']

			world_data_for_position = self.manager.get_world_data_for_position(position)

			for entity in filter(lambda ent: not is_owned_memory(attacker.id, ent), world_data_for_position['entities']):
				#really need introspection here to break the behavior out :/
				if is_program_main_segment(entity):
					#get and try to delete a random zeroed memory segment, if zeroed already, remove it
					#if not, zero a random memory segment
					owned_segments = entity.get_attribute(AttributeTag.OwnedMemory).data['segments']
					if len(owned_segments) == 0:
						actions.append(Action(ActionTag.ProgramMemoryRemove, 
							{'parent_id': entity.id, 'position': position}))
					else:
						owned_zeroed_segments = filter(lambda ent: ent.get_attribute(AttributeTag.Zeroed), owned_segments)
						if len(owned_zeroed_segments) == 0:
							segment = owned_segments[libtcod.random_get_int(0, 0, len(owned_segments) - 1)]
							segment.add_attribute(Attribute(AttributeTag.Zeroed))
						else:
							actions.append(Action(ActionTag.ProgramMemoryRemove, 
								{'parent_id': entity.id, 'position': position}))

				elif entity.get_attribute(AttributeTag.ProgramMemory):
					if not entity.get_attribute(AttributeTag.Zeroed):
						entity.add_attribute(Attribute(AttributeTag.Zeroed))
					else:
						actions.append(Action(ActionTag.ProgramMemoryRemove, 
							{'parent_id': entity.get_attribute(AttributeTag.ProgramMemory).data['parent_id'], 'position': position}))
				else:
					#???
					pass

		return actions
Example #4
0
    def __init__(self,
                 num_of_actions: int = 1,
                 alfa: float = 0.1,
                 lambd: float = None,
                 epsilon=0.1,
                 g_init: float = 0,
                 n_init: float = 0):

        self.actions = []
        for _ in range(num_of_actions):
            a = Action(alfa=alfa,
                       lambd=lambd,
                       epsilon=epsilon,
                       g_init=g_init,
                       n_init=n_init)
            self.actions.append(a)
Example #5
0
    def create_actions(self):
        for junction in self.junctions:
            for way in junction.arms.keys():
                if way.oneway and str(way.starting_point.id) == str(
                        junction.id):
                    continue
                actions = []
                for possible_exit_for_given_way in junction.arms.keys():
                    if (possible_exit_for_given_way.oneway and str(
                            possible_exit_for_given_way.starting_point.id) != str(junction.id)) \
                            or str(possible_exit_for_given_way.id) == str(way.id):
                        continue
                    action = Action(0, possible_exit_for_given_way, set())
                    actions.append(action)
                junction.arms[way] = set(actions)

                if way.oneway:
                    delete_from_set_of_actions(way, way, junction)
Example #6
0
    def post(self):
        req = request.get_json()
        object_id = req.get('object_id', None)

        if object_id:
            if not House.objects.with_id(object_id) and not Merchant.objects.with_id(object_id):
                return Ans(-1, msg='对象不存在')

        if Action.objects(user=g.user, action_type=req.get('action_type', None), object_id=object_id, is_del=False).first():
            return Ans(-1, msg='记录已存在')

        action = Action(
            user=g.user,
            action_type=req.get('action_type', None),
            object_id=object_id,

            addition=req.get('addition', None),
        ).save()
        return Ans(0, data=action.to_json())
Example #7
0
    def generate_actions(self):
        events = []

        for id, entity in filter(
                lambda ent: ent[1].get_attribute(AttributeTag.HostileProgram),
                self.manager.entities.iteritems()):
            #TODO: pull an RNG out into entity manager so I can properly save and control rng generation for the purposes of being a roguelike
            new_position = Vec2d(libtcod.random_get_int(0, -1, 1),
                                 libtcod.random_get_int(0, -1, 1))
            #mildly biases horizontal movement
            if new_position[0] != 0:
                new_position[1] = 0
            events.append(
                Action(ActionTag.ProgramMovement, {
                    'target_id': entity.id,
                    'value': new_position
                }))

        return events
Example #8
0
def parse(file_path):
    doc = xml.parse(file_path)
    events = doc.getElementsByTagName("event")
    all_actions = []
    for event in events:
        action_index = events.index(event)
        action_type = event.getAttribute("type")
        action_time = get_text(
            event.getElementsByTagName("time")[0].childNodes)
        action_text = get_text(
            event.getElementsByTagName("text")[0].childNodes)
        action_position = int(
            get_text(event.getElementsByTagName("pos")[0].childNodes))

        my_action = Action(action_index, action_type, action_time, action_text,
                           action_position)
        all_actions.append(my_action)

        my_action.to_cli()
    return all_actions
Example #9
0
#currently pending refactoring into its own structure of some kind, whether that be a class or in-place somewhere above
global_input_tree = {
    'exit': MenuGame.flag_for_exit,
    'quit': MenuGame.flag_for_exit,
    'o': MenuGame.save_current_state,
    'p': MenuGame.save_action_history,
    'f': MenuGame.dump_entities,
    'g': MenuGame.dump_entity_manager_state,
    'h': MenuGame.snapshot_performance
}

innates_input_tree = {
    chr(24):
    Action(ActionTag.ProgramMovement, {
        'value': Vec2d(0, -1),
        'cost': 1
    }),
    chr(25):
    Action(ActionTag.ProgramMovement, {
        'value': Vec2d(0, 1),
        'cost': 1
    }),
    chr(26):
    Action(ActionTag.ProgramMovement, {
        'value': Vec2d(1, 0),
        'cost': 1
    }),
    chr(27):
    Action(ActionTag.ProgramMovement, {
        'value': Vec2d(-1, 0),
        'cost': 1
Example #10
0
from model.action import Action
from model.account import Account
from model import modulesManager

login = '******'
password = '******'

modulesMan = modulesManager.moduleManager()
modulesMan.loadModules(["mention"])
hydrModule = modulesMan.getModule("mention")

act = Action(Account(login, password, True), hydrModule,
             {"CONFID": "1168310503269787"})

act.Run()
input("s")
Example #11
0
def post_tweet(api, action, tweet_text, user_id, in_reply_to_tweet_id):
    print ("post_tweet: {0}".format(tweet_text))
    tweet = api.PostUpdate(tweet_text, in_reply_to_status_id=in_reply_to_tweet_id)
    db.session.add(Action(user_id, tweet.id, in_reply_to_tweet_id, action.name))
    db.session.commit()
Example #12
0
def main(level, player_img='block', draw_labels=True):

    saved_tiles_file = "../groundcollapse/chunks/%s/chunk_0_0" % level
    saved_tile_cols = read_pickle(saved_tiles_file)  # list of lists (each list represents 1 tile row)

    id_metatile_map_file = "level_saved_files_%s/id_metatile_maps/%s.pickle" % (player_img, level)
    id_metatile_map = read_pickle(id_metatile_map_file)

    num_cols = len(saved_tile_cols)
    num_rows = len(saved_tile_cols[0])

    coord_id_map = {}
    for x in range(num_cols):
        for y in range(num_rows):
            coord = (x * TILE_DIM, y * TILE_DIM)
            id = saved_tile_cols[x][y]
            coord_id_map[coord] = id

    coord_metatile_map = {}
    for coord, id in coord_id_map.items():
        if id == '':
            coord_metatile_map[coord] = None
        else:
            metatile = Metatile.from_str(id_metatile_map.get(id))
            coord_metatile_map[coord] = metatile

    # Background
    FPS = 40  # frame rate
    level_w = num_cols * TILE_DIM
    level_h = num_rows * TILE_DIM
    WORLD_X = min(level_w, MAX_WIDTH)
    WORLD_Y = min(level_h, MAX_HEIGHT)
    clock = pygame.time.Clock()
    pygame.init()
    world = pygame.display.set_mode([WORLD_X, WORLD_Y])
    BACKGROUND_COLOR = (23, 23, 23)

    platform_coords = []
    goal_coords = []
    start_coord = None
    blank_coord = None
    tiles_list = pygame.sprite.Group()

    for coord, metatile in coord_metatile_map.items():
        if metatile is not None:
            if start_coord is None and metatile.type == 'start':
                start_coord = coord
            if blank_coord is None and metatile.type == 'blank':
                blank_coord = coord
            if metatile.type == 'block':
                platform_coords.append(coord)
            if metatile.type == 'goal':
                goal_coords.append(coord)
            tile_img = TYPE_IMG_MAP.get(metatile.type)
        else:
            tile_img = "none.png"
        tiles_list.add(Tile(coord[0], coord[1], tile_img))  # get tile sprites

    if start_coord:
        player_start_coord = start_coord
    elif blank_coord:
        player_start_coord = blank_coord
    else:
        player_start_coord = (0, 0)

    player_model = PlayerModel(player_img, player_start_coord)
    player_view = PlayerView(player_img)
    player_list = pygame.sprite.Group()
    player_list.add(player_view)  # get player sprite

    camera = Camera(Camera.camera_function, level_w, level_h, WORLD_X, WORLD_Y)  # setup camera

    # Setup drawing metatile labels
    if draw_labels:
        metatile_labels, font_color, label_padding = get_metatile_labels(coord_id_map, coord_metatile_map)

    # Main Loop
    main = True

    key_left = False
    key_right = False
    key_jump = False

    while main:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                main = False

            if event.type == pygame.KEYDOWN:
                if event.key == ord('q'):
                    pygame.quit()
                    main = False
                    sys.exit()
                elif event.key == ord('r'):
                    player_model.reset()
                elif event.key in [pygame.K_LEFT, ord('a')]:
                    key_left = True
                elif event.key in [pygame.K_RIGHT, ord('d')]:
                    key_right = True
                elif event.key in [pygame.K_SPACE, pygame.K_UP, ord('w')]:
                    key_jump = True

            if event.type == pygame.KEYUP:
                if event.key in [pygame.K_LEFT, ord('a')]:
                    key_left = False
                elif event.key in [pygame.K_RIGHT, ord('d')]:
                    key_right = False

        world.fill(BACKGROUND_COLOR)
        camera.update(player_view)  # set camera to track player
        player_model.update(Action(key_left, key_right, key_jump), platform_coords, goal_coords)
        player_view.update(player_model.state.x, player_model.state.y,
                           player_model.half_player_w, player_model.half_player_h)
        key_jump = False

        entities_to_draw = []
        entities_to_draw += list(tiles_list)  # draw tiles
        entities_to_draw += list(player_list)  # draw player

        for e in entities_to_draw:
            world.blit(e.image, camera.apply(e))

        if draw_labels:
            for coord in list(coord_metatile_map.keys()):  # draw metatile border outlines
                tile_rect = pygame.Rect(coord[0], coord[1], TILE_DIM, TILE_DIM)
                tile_rect = camera.apply_to_rect(tile_rect)  # adjust based on camera
                pygame.draw.rect(world, font_color, tile_rect, 1)

            for label in metatile_labels:  # draw metatile labels
                surface, label_x, label_y = label
                label_x, label_y = camera.apply_to_coord((label_x, label_y))
                world.blit(surface, (label_x + label_padding[0], label_y + label_padding[1]))

        pygame.display.flip()
        clock.tick(FPS)
    def handle_action(self, action):
        actions = []
        if action.type == ActionTag.ProgramMovement:
            program = self.manager.get_entity_by_id(action.data['target_id'])
            old_position = program.get_attribute(
                AttributeTag.WorldPosition).data['value']
            position_delta = action.data['value']
            new_position = old_position + position_delta

            existing_memory = program.get_attribute(
                AttributeTag.OwnedMemory).data['segments']
            new_position_world_data = self.manager.get_world_data_for_position(
                new_position)

            if position_delta[0] < -1 or position_delta[
                    0] > 1 or position_delta[1] < -1 or position_delta[
                        1] > 1 or (position_delta[0] != 0
                                   and position_delta[1] != 0):
                raise ValueError(
                    'Attempted to process a ProgramMovement action with invalid movement parameters '
                    + str(position_delta))

            #print new_position_world_data['entities']
            if not entities_occupy_position(
                    program.id,
                    new_position_world_data) and position_delta != Vec2d(0, 0):
                # -1 here because the program itself counts for purposes of max memory size
                if len(
                        filter(lambda ent: is_owned_memory(program.id, ent),
                               new_position_world_data['entities'])) > 0:
                    actions.append(
                        Action(ActionTag.ProgramMemoryRemove, {
                            'parent_id': program.id,
                            'position': new_position
                        }))
                elif len(existing_memory) >= program.get_attribute(
                        AttributeTag.MaxProgramSize).data['value'] - 1:
                    existing_memory.sort(
                        lambda ent, other: cmp(ent.id, other.id))
                    actions.append(
                        Action(
                            ActionTag.ProgramMemoryRemove, {
                                'parent_id':
                                program.id,
                                'position':
                                existing_memory[0].get_attribute(
                                    AttributeTag.WorldPosition).data['value']
                            }))

                actions.append(
                    Action(
                        ActionTag.ProgramMemoryAdd, {
                            'parent_id':
                            program.id,
                            'position':
                            program.get_attribute(
                                AttributeTag.WorldPosition).data['value']
                        }))

                # update the manager's world tile data to consistency with the move we're doing
                self.manager.world_tiles[old_position[0]][
                    old_position[1]]['entities'].remove(program)
                self.manager.world_tiles[new_position[0]][
                    new_position[1]]['entities'].append(program)

                program.get_attribute(
                    AttributeTag.WorldPosition).data['value'] = new_position
        return actions