def project_manage_admin(project_id, user_id, admin, is_add=True): c, p = before_project_service(project_id, admin) if c is not None: return c if p.user_id != admin.id: return code_list.NotProjectOriginator user = User.get_user_by_id(user_id) if user is None: return code_list.UserNotExist if user.id == admin.id: return code_list.OperatorError if not p.has_member(user): return code_list.NotInProject if is_add: p.add_admin(user) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.project_add_admin.name, content=p.name, link=p.link) else: p.remove_admin(user) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.project_remove_admin.name, content=p.name, link=p.link) return code_list.Success
def task_manage_participant(task_id, user, project_id, participant_id, is_add=True): c, p, task = before_task_service(pid=project_id, tid=task_id, user=user) if c is not None: return c participant = User.get_user_by_id(participant_id) if participant is None: return code_list.UserNotExist if not p.has_member(participant): return code_list.NotInProject if is_add: if task.has_participant(participant): return code_list.InParticipant task.add_participant(participant) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.task_add_participant.name, content=participant.username, link=task.link) else: if not task.has_participant(participant): return code_list.NotInParticipant task.remove_participant(participant) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.task_remove_participant.name, content=participant.username, link=task.link) return code_list.Success
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
def new_project(name, user): p = Project.new(name, user) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.project_create.name, content=name, link=p.link) return code_list.Success, {"id": p.id}
def schedule_delete(sid, pid, user): e, p, s = before_schedule_service(pid=pid, user=user, sid=sid) if e is not None: return e s.delete() Action.new(user_id=user.id, project_id=p.id, type_name=action_type.schedule_delete.name, content=s.content, link=s.link) return code_list.Success
def task_delete(task_id, user, project_id): c, p, task = before_task_service(pid=project_id, tid=task_id, user=user) if c is not None: return c task.delete() Action.new(user_id=user.id, project_id=p.id, type_name=action_type.task_delete.name, content=task.name, link=task.link) return code_list.Success
def project_delete(project_id, user): c, p = before_project_service(project_id, user) if c is not None: return c if p.user_id != user.id: return code_list.NotProjectOriginator p.delete() Action.new(user_id=user.id, project_id=p.id, type_name=action_type.project_delete.name, content=p.name, link=p.link) return code_list.Success
def act_defender(self, me: Robot, rules: Rules, game: Game, action: Action): self.defender = me gate_center = rules.arena.width / 2.0 gate_z_target = rules.arena.depth + game.ball.radius * 2 ball_curr_x = game.ball.x ball_curr_z = game.ball.z gate_center_direction = Vector2D(gate_center - ball_curr_x, gate_z_target - ball_curr_z).normalize() tiks_pass = 0 for point in self.last_prediction[:40]: if point.z < -20 and me.z < point.z: ball_to_center_point = Vector3D( point.x - gate_center_direction.x * game.ball.radius, point.z - gate_center_direction.z * game.ball.radius, point.y) delta_pos = ball_to_center_point - me need_speed = ROBOT_MAX_GROUND_SPEED target_velocity = delta_pos.normalize() * need_speed poses = self.predict_move(me, target_velocity, tiks=tiks_pass + 1) if (poses[tiks_pass] - point).len() <= self.game.ball.radius + me.radius: jump_predict = self.predict_jump( me, tiks=min(tiks_pass + 1, 15), target_vel=target_velocity) jump = False for i in range(0, min(tiks_pass + 1, 15)): jp = jump_predict[i] bp = self.last_prediction[i] dist_to_ball = ((jp.x - bp.x)**2 + (jp.y - bp.y)**2 + (jp.z - bp.z)**2)**0.5 jump = (dist_to_ball <= BALL_RADIUS + ROBOT_MAX_RADIUS and jp.z < game.ball.z - game.ball.radius) if jump: break action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 action.use_nitro = False return tiks_pass += 1 target_pos = Vector2D(0.0, -(rules.arena.depth / 2.0)) target_velocity = Vector2D( target_pos.x - me.x, target_pos.z - me.z) * ROBOT_MAX_GROUND_SPEED action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z
def project_member_manage(project_id, account, admin, is_add=True, account_type="id"): c, p = before_project_service(pid=project_id, user=admin) if c is not None: return c if account_type == "email": user = User.get_user_by_email(account) elif account_type == "phone": user = User.get_user_by_phone(account) elif account_type == "id": user = User.get_user_by_id(account) else: return code_list.ParamsWrong.with_message("未开放类型") if user is None: return code_list.UserNotExist if user.id == admin.id: return code_list.OperatorError g = Group.query.filter_by(project_id=project_id, is_all=True).first() if is_add: if p.has_member(user): return code_list.InProject p.add_member(user) g.add(user) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.project_join.name, content=p.name, link=p.link) else: if not p.has_member(user): return code_list.NotInProject p.remove_member(user) g.remove(user) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.project_leave.name, content=p.name, link=p.link) return code_list.Success
def schedule_update(sid, pid, user, content, remarks, t_set, label): e, p, s = before_schedule_service(pid=pid, user=user, sid=sid) if e is not None: return e if len(label) > 5: if not all([len(la) <= 5 for la in label.split(' ')]): return code_list.LabelTooLong s.update(content=content, remarks=remarks, t_set=t_set, label=label) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.schedule_update.name, content=s.content, link=s.link) return code_list.Success
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 task_update(task_id, user, project_id, name, remarks, t_begin, t_end, priority, label, finish): c, p, task = before_task_service(pid=project_id, tid=task_id, user=user) if c is not None: return c task.update(name=name, remarks=remarks, t_begin=t_begin, t_end=t_end, priority=priority, label=label, finish=finish) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.task_update.name, content=name, link=task.link) return code_list.Success
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())
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
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
def delete(self): req = request.get_json() action_type = int(req.get('a', 1)) object_id = req.get('object_id', None) action = Action.objects(user=g.user, action_type=action_type, object_id=object_id, is_del=False).first() if not action: return Ans(-1, msg='不存在该记录') action.is_del = True action.save() return Ans(0)
def task_create(project_id, user, name, remarks, t_begin, t_end, priority, label): c, p = before_project_service(pid=project_id, user=user) if c is not None: return c if len(label) > 5: if not all([len(la) <= 5 for la in label.split(' ')]): return code_list.LabelTooLong task = Task.new(name, p.id, user.id, remarks=remarks, t_begin=t_begin, t_end=t_end, priority=priority, label=label) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.task_create.name, content=name, link=task.link) return code_list.Success
def schedule_create(pid, user, content, remarks, t_set, t_remind, label): e, p = before_project_service(pid, user) if e is not None: return e, None if len(label) > 5: if not all([len(la) <= 5 for la in label.split(' ')]): return code_list.LabelTooLong if t_remind is None: t_remind = t_set s = Schedule.new(content, p.id, user.id, remarks=remarks, t_set=t_set, t_remind=t_remind, label=label) Action.new(user_id=user.id, project_id=p.id, type_name=action_type.schedule_create.name, content=s.content, link=s.link) return code_list.Success
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)
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)
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
#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
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")
def act(self, me: Robot, rules: Rules, game: Game, action: Action): # Наша стратегия умеет играть только на земле # Поэтому, если мы не касаемся земли, будет использовать нитро # чтобы как можно быстрее попасть обратно на землю if not me.touch: action.target_velocity_x = 0.0 action.target_velocity_y = -MAX_ENTITY_SPEED action.target_velocity_z = 0.0 action.jump_speed = 0.0 action.use_nitro = True return dist_to_ball = ((me.x - game.ball.x)**2 + (me.y - game.ball.y)**2 + (me.z - game.ball.z)**2)**0.5 # Если при прыжке произойдет столкновение с мячом, и мы находимся # с той же стороны от мяча, что и наши ворота, прыгнем, тем самым # ударив по мячу сильнее в сторону противника jump = (dist_to_ball < BALL_RADIUS + ROBOT_MAX_RADIUS and me.z < game.ball.z) # Так как роботов несколько, определим нашу роль - защитник, или нападающий # Нападающим будем в том случае, если есть дружественный робот, # находящийся ближе к нашим воротам is_attacker = len(game.robots) == 2 for robot in game.robots: robot: Robot = robot if robot.is_teammate and robot.id != me.id: if robot.z < me.z: is_attacker = True if is_attacker: # Стратегия нападающего: # Просимулирем примерное положение мяча в следующие 10 секунд, с точностью 0.1 секунда for i in range(1, 101): t = i * 0.1 ball_x = game.ball.x ball_z = game.ball.z ball_vel_x = game.ball.velocity_x ball_vel_z = game.ball.velocity_z ball_pos = Vector2D(ball_x, ball_z) + \ Vector2D(ball_vel_x, ball_vel_z) * t # Если мяч не вылетит за пределы арены # (произойдет столкновение со стеной, которое мы не рассматриваем), # и при этом мяч будет находится ближе к вражеским воротам, чем робот, if ball_pos.z > me.z \ and abs(ball_pos.x) < (rules.arena.width / 2.0) \ and abs(ball_pos.z) < (rules.arena.depth / 2.0): # Посчитаем, с какой скоростью робот должен бежать, # Чтобы прийти туда же, где будет мяч, в то же самое время delta_pos = Vector2D(ball_pos.x, ball_pos.z) - Vector2D( me.x, me.z) need_speed = delta_pos.len() / t # Если эта скорость лежит в допустимом отрезке if 0.5 * ROBOT_MAX_GROUND_SPEED < need_speed \ and need_speed < ROBOT_MAX_GROUND_SPEED: # То это и будет наше текущее действие target_velocity = delta_pos.normalize() * need_speed action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 action.use_nitro = False return # Стратегия защитника (или атакующего, не нашедшего хорошего момента для удара): # Будем стоять посередине наших ворот target_pos = Vector2D( 0.0, -(rules.arena.depth / 2.0) + rules.arena.bottom_radius) # Причем, если мяч движется в сторону наших ворот if game.ball.velocity_z < -EPS: # Найдем время и место, в котором мяч пересечет линию ворот t = (target_pos.z - game.ball.z) / game.ball.velocity_z x = game.ball.x + game.ball.velocity_x * t # Если это место - внутри ворот if abs(x) < rules.arena.goal_width / 2.0: # То пойдем защищать его target_pos.x = x # Установка нужных полей для желаемого действия target_velocity = Vector2D( target_pos.x - me.x, target_pos.z - me.z) * ROBOT_MAX_GROUND_SPEED action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 action.use_nitro = False
def act(self, me: Robot, rules: Rules, game: Game, action: Action): GOAL = rules.arena.goal_width / 2.0 - rules.arena.goal_side_radius if not me.touch: action.target_velocity_x = 0.0 action.target_velocity_y = -MAX_ENTITY_SPEED action.target_velocity_z = 0.0 action.jump_speed = 0.0 action.use_nitro = True return #dist = me to ball dist = ((me.x - game.ball.x)**2 + (me.z - game.ball.z)**2)**0.5 #jump to ball jump = (dist <= BALL_RADIUS + ROBOT_MAX_RADIUS + JUMP_DIST) and (me.z < game.ball.z) #set robot for attacker is_attacker = len(game.robots) == 2 for robot in game.robots: robot: Robot = robot if robot.is_teammate and (robot.id != me.id): dist2 = ((robot.x - game.ball.x)**2 + (robot.z - game.ball.z)**2)**0.5 if dist2 > dist: is_attacker = True elif robot.z < me.z: is_attacker = True #ATTACK if is_attacker: for i in range(1,101): t = i * 0.1 ball_x = game.ball.x ball_z = game.ball.z ball_vel_x = game.ball.velocity_x ball_vel_z = game.ball.velocity_z ball_pos = Vector2D(ball_x, ball_z) + Vector2D(ball_vel_x, ball_vel_z) * t if (ball_z > me.z) and (abs(ball_pos.x) < rules.arena.width / 2.0) and (abs(ball_pos.z) <= rules.arena.depth / 2.0): to_ball = Vector2D(ball_pos.x, ball_pos.z) - Vector2D(me.x, me.z) speed = to_ball.len() / t if (0.5 * ROBOT_MAX_GROUND_SPEED < speed) and (speed < ROBOT_MAX_GROUND_SPEED): target_velocity = to_ball.normalize() * speed action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 action.use_nitro = False return #DEFEND jump = 0.0 t = 1 def_pos = Vector2D(0.0, -rules.arena.depth / 2.0) if game.ball.velocity_z < -EPS: t = (def_pos.z - game.ball.z) / game.ball.velocity_z def_pos.x = game.ball.x + game.ball.velocity_x * t if def_pos.x < -GOAL: def_pos.x = -GOAL elif GOAL < def_pos.x: def_pos.x = GOAL to_pos = Vector2D(def_pos.x - me.x, def_pos.z - me.z) speed = min(to_pos.len() / t, ROBOT_MAX_GROUND_SPEED) def_velocity = to_pos.normalize() * speed if (game.ball.z + game.ball.velocity_z * t <= -rules.arena.depth / 2.0) and (me.z == def_pos.z): if game.ball.y + game.ball.velocity_y * t > 0: jump = ROBOT_MAX_JUMP_SPEED if game.ball.z <= -rules.arena.depth / 4.0: for i in range(1,101): t = i * 0.1 ball_x = game.ball.x ball_z = game.ball.z ball_vel_x = game.ball.velocity_x ball_vel_z = game.ball.velocity_z ball_pos = Vector2D(ball_x, ball_z) + Vector2D(ball_vel_x, ball_vel_z) * t to_ball = Vector2D(ball_pos.x, ball_pos.z) - Vector2D(me.x, me.z) speed = to_ball.len() / t target_velocity = to_ball.normalize() * speed action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 action.jump_speed = 0.0 action.use_nitro = False return action.target_velocity_x = def_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = def_velocity.z action.jump_speed = jump action.use_nitro = False
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()
def act_attacker(self, me: Robot, rules: Rules, game: Game, action: Action): self.attacker = me gate_center = rules.arena.width / 2.0 gate_z_target = rules.arena.depth + game.ball.radius * 2 if game.ball.z - self.game.ball.radius * 3 > me.z: self.should_hit = True elif game.ball.z < me.z: self.should_hit = False if self.should_hit: if (Vector2D(game.ball.x, game.ball.z) - Vector2D( me.x, me.z)).len() < ROBOT_MAX_GROUND_SPEED * 0.75: tiks_pass = 0 for point in self.last_prediction[:45]: gate_center_direction = Vector2D(gate_center - point.x, gate_z_target - point.z).normalize() ball_to_center_point = Vector3D( point.x - gate_center_direction.x * game.ball.radius, point.z - gate_center_direction.z * game.ball.radius, 1) delta_pos = ball_to_center_point - me target_velocity = delta_pos.normalize( ) * ROBOT_MAX_GROUND_SPEED poses = self.predict_move(me, target_velocity, tiks=tiks_pass + 1) if (poses[tiks_pass].D2() - point.D2() ).len() <= self.game.ball.radius + me.radius: jump_predict = self.predict_jump( me, tiks=min(tiks_pass + 1, 10), target_vel=target_velocity) jump = False for i in range(0, min(tiks_pass + 1, 10)): jp = jump_predict[i] bp = self.last_prediction[i] dist_to_ball = (jp - bp).len() jump = ( dist_to_ball <= BALL_RADIUS + ROBOT_MAX_RADIUS and jp.z < game.ball.z - game.ball.radius) if jump: break action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 action.use_nitro = False #print('predicted') return tiks_pass += 1 point = self.last_prediction[0] gate_center_direction = Vector2D( gate_center - point.x, gate_z_target - point.z).normalize() ball_to_center_point = Vector3D( point.x - gate_center_direction.x * game.ball.radius, point.z - gate_center_direction.z * game.ball.radius, 1) delta_pos = ball_to_center_point - me target_velocity = delta_pos.normalize() * ROBOT_MAX_GROUND_SPEED action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z jump_predict = self.predict_jump(me) jump = False for i in range(1, 15): jp = jump_predict[i] bp = self.last_prediction[i] dist_to_ball = ((jp.x - bp.x)**2 + (jp.y - bp.y)**2 + (jp.z - bp.z)**2)**0.5 jump = (dist_to_ball <= BALL_RADIUS + ROBOT_MAX_RADIUS and jp.z < game.ball.z - game.ball.radius) if jump: break action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 action.use_nitro = False #print('blind') return else: # Run to take place between our gate and ball tiks_pass = 0 for point in self.last_prediction: tiks_pass += 1 if point.y > self.game.ball.radius * 5: continue target_x = point.x #if target_x - me.x < 0: # target_x += game.ball.radius * 2 #else: # target_x -= game.ball.radius * 2 jump_predict = self.predict_jump(me) jump = False for i in range(1, 15): jp = jump_predict[i] bp = self.last_prediction[i] dist_to_ball = ((jp.x - bp.x)**2 + (jp.y - bp.y)**2 + (jp.z - bp.z)**2)**0.5 jump = (dist_to_ball <= BALL_RADIUS + ROBOT_MAX_RADIUS and jp.z < game.ball.z - game.ball.radius) if jump: break target_z = point.z - game.ball.radius * 3 target = Vector3D(target_x, target_z, 1) delta_pos = target - Vector3D(me.x, me.z, me.y) need_speed = ROBOT_MAX_GROUND_SPEED target_velocity = delta_pos.normalize() * need_speed action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 self.ataker_target = target return return
def act(self, me: Robot, rules: Rules, game: Game, action: Action): # Наша стратегия умеет играть только на земле # Поэтому, если мы не касаемся земли, будет использовать нитро # чтобы как можно быстрее попасть обратно на землю if not me.touch: action.target_velocity_x = 0.0 action.target_velocity_y = -MAX_ENTITY_SPEED action.target_velocity_z = 0.0 action.jump_speed = 0.0 action.use_nitro = True return # Найдем расстояние между мячом и роботом dist_to_ball = ((me.x - game.ball.x) ** 2 + (me.y - game.ball.y) ** 2 + (me.z - game.ball.z) ** 2 ) ** 0.5 # Найдем расстояние в плоскости xz (горизонтальной) dist_to_ball_xz = ((me.x-game.ball.x)**2 + (me.z-game.ball.z)**2)**0.5 # Если при прыжке произойдет столкновение с мячом, и мы находимся # с той же стороны от мяча, что и наши ворота, прыгнем, тем самым # ударив по мячу сильнее в сторону противника jump = (dist_to_ball < BALL_RADIUS +ROBOT_MAX_RADIUS and me.z < game.ball.z) # Далее описываются действия нападающего, который может иметь id либо 2, либо 4 if me.id==2 or me.id==4: # Если роботы вылетают за пределы горизонтального участка, # придаем скорость, которая вернет их назад if me.z < -rules.arena.depth/2.0+rules.arena.bottom_radius: action.target_velocity_z = ROBOT_MAX_GROUND_SPEED return if me.x > rules.arena.width/2.0: action.target_velocity_x = -ROBOT_MAX_GROUND_SPEED return if me.x < -rules.arena.width/2.0: action.target_velocity_x = ROBOT_MAX_GROUND_SPEED return e = 0.001 # Если мяч не вылетит за пределы арены # (произойдет столкновение со стеной, которое мы не рассматриваем), # и при этом мяч будет находится ближе к вражеским воротам, чем робот, if game.ball.z > me.z and abs(game.ball.x) < (rules.arena.width / 2.0) \ and abs(game.ball.z) < (rules.arena.depth / 2.0): # Посчитаем, с какой скоростью робот должен бежать, # Чтобы прийти туда же, где будет мяч, в то же самое время target_pos = Vector2D(0.0, (rules.arena.depth / 2.0) + rules.arena.bottom_radius) ball_pos = Vector2D(game.ball.x,game.ball.z) a = target_pos - ball_pos b = target_pos - Vector2D(me.x,me.z) c = ball_pos - Vector2D(me.x,me.z) cosine_a_b = cosine(a,b) cos_y = cosine(a,c) delta_pos = Vector2D(ball_pos.x, ball_pos.z) - Vector2D(me.x, me.z) # Если вектор скорости робота не сонаправлен с вектором, по которому требуется # ударить, чтобы мяч попал в центр ворот, то стремимся двигаться в сторону # увеличения cosine_a_b if abs(cosine_a_b) < 1 - e: #print(cos_y) sin_y = (1-cos_y**2)**0.5 #print(cos_y,a.x,a.z,a.len(),c.x,c.z,c.len()) if cos_y > 1: time.sleep(30) assert(cos_y < 1) if c.x > 0: x_d = c.x*cos_y+sin_y*c.z z_d = -c.x*sin_y+cos_y*c.z else: x_d = c.x*cos_y-sin_y*c.z z_d = c.x*sin_y+cos_y*c.z d = Vector2D(x_d,z_d) # print(d.x,d.z) # d.z = d.z if game.ball.y < 3 * BALL_RADIUS else -d.z target_velocity = d.normalize()*ROBOT_MAX_GROUND_SPEED # В противном случае бежим на мяч else: ball_pos = Vector2D(game.ball.x,game.ball.z) me_pos = Vector2D(me.x,me.z) delta_to_ball = ball_pos - me_pos target_velocity = delta_to_ball.normalize()*ROBOT_MAX_GROUND_SPEED # Если мяч летит в воздухе, надо научиться прыгать ровно в место встречи if game.ball.y > 2 * BALL_RADIUS and dist_to_ball_xz < 2 * BALL_RADIUS: # Для этого надо понять, через какое время мяч вернется на землю v0 = game.ball.velocity_y R = 2 * BALL_RADIUS h = game.ball.y g = 30 D = 4 * v0 * v0 - 4 * g * (2 * R - 2 * h) t = v0 / g + (D**0.5) / (2 * g) ball_pos_z = game.ball.z + game.ball.velocity_z*t*60 ball_pos_x = game.ball.x + game.ball.velocity_x*t*60 ball_pos = Vector2D(ball_pos_x,ball_pos_z) delta_dist_z = ball_pos_z - me.z velocity_z = delta_dist_z / (0.5*t+0.01) delta_dist_x = ball_pos_x - me.x velocity_x = delta_dist_x / (0.5*t+0.01) target_velocity = Vector2D(velocity_x,velocity_z) # Установим итоговую скорость action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 # Теперь разберемся, нужно ли прыгать, если при текущих скоростях, шар и робот # встретятся в воздухе ball_pos_x = game.ball.x ball_pos_y = game.ball.y ball_pos_z = game.ball.z speed_y_ball = game.ball.velocity_y delta_time = 2 / 60 / 100 speed_y = ROBOT_MAX_JUMP_SPEED me_y = 1 me_x = me.x me_z = me.z # Произведем небольшое моделирование ситуации for i in range(40*50): if game.ball.z < me.z: break ball_pos_x += game.ball.velocity_x*delta_time ball_pos_y += speed_y_ball*delta_time ball_pos_z += game.ball.velocity_z*delta_time ball_pos_y -= 15*delta_time*delta_time speed_y_ball -= 30*delta_time me_y += speed_y*delta_time me_y -= 15*delta_time*delta_time speed_y -= 30*delta_time if ball_pos_y < 2: speed_y_ball -= (1.7)*speed_y_ball me_x += me.velocity_x*delta_time me_z += me.velocity_z*delta_time dist_ball = ((me_x - ball_pos_x) ** 2 + (me_y - ball_pos_y) ** 2 + (me_z - ball_pos_z) ** 2 ) ** 0.5 gen_velocity = (speed_y ** 2+ me.velocity_x ** 2 + me.velocity_z ** 2) **0.5 # Если робот и шар пересекаются if dist_ball < (0.5*BALL_RADIUS +ROBOT_MAX_RADIUS) and abs(me_y-ball_pos_y) < 1 and i < 7000 and\ speed_y / gen_velocity < 0.5 and cos_y >0.81 or jump: # Тогда надо прыгать прямо сейчас # В полете робот неуправляем, поэтому решение о прыжке - довольно ответственно action.jump_speed = ROBOT_MAX_JUMP_SPEED break if jump: action.jump_speed = ROBOT_MAX_JUMP_SPEED action.use_nitro = False return # Если ничего не реализовалось, просто бежим на стартовую позицию target_pos = Vector2D(0.0, -(rules.arena.depth / 2.0) + rules.arena.bottom_radius) target_velocity = Vector2D( target_pos.x - me.x, target_pos.z - me.z) * ROBOT_MAX_GROUND_SPEED action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z return # Стратегия защитника: # Будем стоять посередине наших ворот radius = rules.arena.bottom_radius target_pos= Vector2D(0.0, -(rules.arena.depth / 2.0)) target_velocity = Vector2D((target_pos.x - me.x), (target_pos.z - me.z))*\ ROBOT_MAX_GROUND_SPEED t = 1 ball_pos_x = game.ball.x ball_pos_y = game.ball.y ball_pos_z = game.ball.z speed_y_ball = game.ball.velocity_y delta_time = 1 / 60 / 100 speed_y = ROBOT_MAX_JUMP_SPEED me_y = 1 me_x = me.x me_z = me.z # Произведем моделирование ситуации i = 0 for i in range(70*100): # Чтобы не тратить драгоценное время, если шар на чужой половине поля # не будем моделировать. На практике это не приводит к пропущенным мячам if game.ball.z > 0: break ball_pos_x += game.ball.velocity_x*delta_time ball_pos_y += speed_y_ball*delta_time ball_pos_z += game.ball.velocity_z*delta_time ball_pos_y -= 15*delta_time*delta_time speed_y_ball -= 30*delta_time target_z = -(rules.arena.depth / 2.0) + rules.arena.bottom_radius me_y += speed_y * delta_time me_y -= 15 * delta_time*delta_time speed_y -= 30 * delta_time me_x += me.velocity_x*delta_time me_z += me.velocity_z*delta_time dist_ball = ((me_x - ball_pos_x)**2+(me_y-ball_pos_y)**2+ (me_z-ball_pos_z)**2)**0.5 gen_velocity = (speed_y ** 2+ me.velocity_x ** 2 + me.velocity_z ** 2) **0.5 t = int(i/100) delta_dist_z = ball_pos_z - me.z velocity_z = delta_dist_z / (t+0.01) delta_dist_x = ball_pos_x - me.x velocity_x = delta_dist_x / (t+0.01) h = ball_pos_y - me_y # Если ожидаем столкновение с мячом в воздухе - прыгаем if dist_ball <(BALL_RADIUS+ROBOT_MAX_RADIUS) and (ball_pos_y > me_y): action.jump_speed = ROBOT_MAX_JUMP_SPEED # Если мяч должен прилететь в зону ворот, бежим на мяч if (ball_pos_z < -(rules.arena.depth / 2.0) + rules.arena.bottom_radius+10) and \ (abs(ball_pos_x) < rules.arena.goal_width / 2.0) and ball_pos_y < 2*BALL_RADIUS and\ me_z < ball_pos_z and h / dist_ball < 0.5: target_velocity = Vector2D(velocity_x,velocity_z)*60 self.x = target_velocity.x self.z = target_velocity.z break # Выставляем команды action.target_velocity_x = target_velocity.x action.target_velocity_y = 0 action.target_velocity_z = target_velocity.z action.use_nitro = False if jump: action.jump_speed = ROBOT_MAX_JUMP_SPEED
def act(self, me: Robot, rules: Rules, game: Game, action: Action): if not me.touch: action.target_velocity_x = 0.0 action.target_velocity_y = -MAX_ENTITY_SPEED action.target_velocity_z = 0.0 action.jump_speed = 0.0 action.use_nitro = True return #dist = me to ball dist = ((me.x - game.ball.x)**2 + (me.y - game.ball.y)**2 + (me.z - game.ball.z)**2)**0.5 #jump to ball jump = (dist <= BALL_RADIUS + ROBOT_MAX_RADIUS + JUMP_DIST) and ( me.z < game.ball.z) #set robot for attacker is_attacker = True for robot in game.robots: robot: Robot = robot if robot.is_teammate and (robot.id != me.id): if robot.z >= me.z: is_attacker = False #ATTACK if is_attacker: for i in range(1, 21): t = i * 0.1 ball_x = game.ball.x ball_z = game.ball.z ball_vel_x = game.ball.velocity_x ball_vel_z = game.ball.velocity_z ball_pos = Vector2D( ball_x, ball_z) + Vector2D(ball_vel_x, ball_vel_z) * t to_ball = Vector2D(ball_pos.x, ball_pos.z) - Vector2D( me.x, me.z) speed = to_ball.len() / t target_velocity = to_ball.normalize() * speed action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 action.use_nitro = False return #DEFEND if game.ball.z <= -5: for i in range(1, 101): t = i * 0.1 ball_x = game.ball.x ball_z = game.ball.z ball_vel_x = game.ball.velocity_x ball_vel_z = game.ball.velocity_z ball_pos = Vector2D( ball_x, ball_z) + Vector2D(ball_vel_x, ball_vel_z) * t if (ball_z > me.z) and (abs( ball_pos.x) < rules.arena.width / 2.0) and (abs( ball_pos.z) <= rules.arena.depth / 2.0): to_ball = Vector2D(ball_pos.x, ball_pos.z) - Vector2D( me.x, me.z) speed = to_ball.len() / t if (0.5 * ROBOT_MAX_GROUND_SPEED < speed) and (speed < ROBOT_MAX_GROUND_SPEED): target_velocity = to_ball.normalize() * speed action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 action.use_nitro = False return #defender stand in the mid of goal target_pos = Vector2D(game.ball.x, -rules.arena.depth / 2.0) if (game.ball.x < -14): target_pos = Vector2D(-14, -rules.arena.depth / 2.0) elif (14 < game.ball.x): target_pos = Vector2D(14, -rules.arena.depth / 2.0) target_velocity = Vector2D( target_pos.x - me.x, target_pos.z - me.z) * ROBOT_MAX_GROUND_SPEED action.target_velocity_x = target_velocity.x action.target_velocity_y = 0.0 action.target_velocity_z = target_velocity.z action.jump_speed = ROBOT_MAX_JUMP_SPEED if jump else 0.0 action.use_nitro = False
def get_action_list_by_project(user, pid): e, p = before_project_service(pid, user) if e is not None: return e, None l = Action.get_list_by_project(p.id) return code_list.Success, l