示例#1
0
    // Start is called before the first frame update
    void Start()
    {
        agent       = GetComponent <NavMeshAgent>();
        agent.speed = stats.Speed;

        childAtkRadiusObject = GetComponentInChildren <ARO>().gameObject;

        Rigidbody rb = GetComponent <Rigidbody>();

        rb.isKinematic = true;
        rb.useGravity  = false;

        HP = stats.MaxHealth;

        cooldown  = false;
        pursue    = false;
        hasTarget = false;

        target       = null;
        MotherTarget = null;

        unitDead = new UnitEvent();
        unitDead.AddListener(AIController.Instance.UnRegisterUnit);
        AIController.Instance.RegisterUnit(this);
    }
示例#2
0
 public void SendUnitSkillPointerEvent(UnitEvent e, Units tu, Skill skill, Vector3 targetPos)
 {
     tu.SetSkillContext(skill);
     tu.SetPosContext(targetPos);
     this.SendUnitStateEvent(e, tu, null, null);
     tu.ClearSkillContext();
 }
示例#3
0
 private static void TriggerRegisterUnitEvent(UnitTrigger trigger, UnitEvent e, int u_id)
 {
     trigger.trigger_event = (int)e;
     trigger.trigger_type  = 2;
     trigger.unit_id       = u_id;
     TriggerManager.AddUnitEvent(trigger);
 }
示例#4
0
 // Use this for initialization
 protected virtual void Awake()
 {
     //The unit is automatically selected when it spawns
     selectionState = UnitSelectionState.Selected;
     //It hasn't moved, but it has interacted (i.e. it cannot act on its first turn)
     HasMoved      = false;
     HasInteracted = true;
     //The unit is removed on death
     OnDeath = RemoveUnit;
     //the standard OnActionSelect is to calculate the attack and move range of the unit. The standard ability is the attack - this
     //part of the function sets all associated functions to be called by the correct delegates.
     OnActionSelect      += CalculateAttackMoveRange;
     RemoveAbilityRange   = RemoveAttackRange;
     OnAttack             = UnitResolveAttack;
     OnAttackSelect       = UnitHasSelectedAttack;
     OnAttackSelected     = UnitSelectedForAttack;
     OnAttackUndo         = UndoAttackSelection;
     OnAttackSelectedUndo = UndoAttackSelected;
     OnMove          = UnitResolveMove;
     OnMoveUndo      = UnitUndoMoveSelection;
     OnMoveSelect    = UnitHasSelectedMove;
     OnInsertUndo    = RemoveUnit;
     OnSpecialSelect = SpecialSelection;
     OnSpecialUndo   = UndoSpecialSelection;
 }
示例#5
0
        public Task HandleOneAsync()
        {
            var evt = new UnitEvent(_identity, Codes.BurningEvent,
                                    UnitEvent.UnitEventData.Create());

            return(Claptrap.HandleEventAsync(evt));
        }
示例#6
0
    public void ProcessEvent(UnitEvent evt)
    {
        _smList[0].ProcessEvent(evt);
        //先执行栈顶的状态机,根据状态返回的信息,决定下一个状态。
        switch (_smList[0].change)
        {
        case StateChange.Enter:    //加入新的栈顶元素
            //新状态一直是放到栈顶,
            _smList.Insert(0, _smStateDict[_smList[0].state]);
            _smList[0].Enter();
            break;

        case StateChange.Switch:                         //替换栈顶元素
            //即先退出当前状态,再进入目标状态
            _smList[0].Exit();                           //栈顶元素退出
            _smList[0] = _smStateDict[_smList[0].state]; //替换栈顶元素
            _smList[0].Enter();                          //栈顶元素进入
            break;

        case StateChange.Exit:    //栈顶元素退出
            _smList[0].Exit();    //栈顶元素退出
            _smList.RemoveAt(0);  //移除栈顶元素
            break;
        }

        if (0 == _smList.Count)
        {
            //状态机空了
            Debug.LogError("state machine is empty");
        }
    }
示例#7
0
 private static void TriggerRegisterUnitEvent(UnitTrigger trigger, UnitEvent e, int teamtype, string u_tag)
 {
     trigger.trigger_event = (int)e;
     trigger.trigger_type  = 2;
     trigger.teamtype      = teamtype;
     trigger.unit_tag      = u_tag;
     TriggerManager.AddUnitEvent(trigger);
 }
示例#8
0
        public static Unit UnitEventToUnit(UnitEvent unit, int pos, GameHistory game)
        {
            Vector2 vec  = MoveService.RotatePoint(new Vector2(unit.x, unit.y), center, -45);
            float   newx = 0;

            // postition 1-3 => 4-6 and 4-6 => 1-3 ...
            if (pos > 3)
            {
                newx = ((vec.X - 62.946175f) / 2);
            }
            else if (pos <= 3)
            {
                newx = ((vec.X - 177.49748f) / 2);
            }

            float newy = vec.Y - 107.686295f;

            // Team2
            // Ymax: 131,72792 => Battlefield.YMax
            // Ymin: 107,686295 => 0

            // Xmax: 78,502525 => 10
            // Xmin: 62,946175 => 0

            // Fix Names
            if (unit.Name.EndsWith("Lightweight"))
            {
                unit.Name = unit.Name.Replace("Lightweight", "");
            }

            if (unit.Name.EndsWith("Starlight"))
            {
                unit.Name = unit.Name.Replace("Starlight", "");
            }

            Unit punit  = null;
            Unit myunit = UnitPool.Units.SingleOrDefault(x => x.Name == unit.Name);

            if (myunit == null)
            {
                myunit      = UnitPool.Units.SingleOrDefault(x => x.Name == "NA").DeepCopy();
                myunit.Name = unit.Name;
            }

            if (myunit != null)
            {
                punit    = myunit.DeepCopy();
                punit.ID = game.GetUnitID();

                newx = MathF.Round((MathF.Round(newx * 2, MidpointRounding.AwayFromZero) / 2), 1);
                newy = MathF.Round((MathF.Round(newy * 2, MidpointRounding.AwayFromZero) / 2), 1);

                punit.PlacePos = new Vector2(newy, newx);
                punit.Owner    = pos;
            }

            return(punit);
        }
    public UnitDestroy(Unit unit, UnitEvent destroy, UnitEvent statsChange)
    {
        m_Owner = unit;

        m_DestroyEvent     = destroy;
        m_StatsChangeEvent = statsChange;

        Register();
    }
示例#10
0
        public async Task MultipleSent(int count)
        {
            var minionLocator = new TestMinionLocator();

            using var host = QuickSetupTestHelper.BuildHost(
                      DatabaseType.SQLite,
                      RelationLocatorStrategy.SharedTable,
                      AppsettingsFilenames,
                      builder =>
            {
                builder.RegisterInstance(minionLocator)
                .As <IMinionLocator>()
                .SingleInstance();
            }, builder =>
                      builder.UseRabbitMQ(rabbitmq => rabbitmq.AsEventCenter())
                      );
            var container         = host.Services;
            var subscriberManager = container.GetRequiredService <IMQSubscriberManager>();
            await subscriberManager.StartAsync();

            var claptrapFactory = (ClaptrapFactory)container.GetRequiredService <IClaptrapFactory>();
            var id = new ClaptrapIdentity("1", Codes.Account);

            await using var scope = claptrapFactory.BuildClaptrapLifetimeScope(id);
            var eventCenter = scope.Resolve <IEventCenter>();
            var task        = Enumerable.Range(0, count)
                              .ToObservable()
                              .Select(version =>
            {
                var unitEvent     = UnitEvent.Create(id);
                unitEvent.Version = version;
                return(unitEvent);
            })
                              .Select(e => Observable.FromAsync(() => eventCenter.SendToMinionsAsync(id, e)))
                              .Merge(100)
                              .ToTask();
            await task;
            await Task.Delay(TimeSpan.FromSeconds(5));

            await subscriberManager.CloseAsync();

            await container.GetRequiredService <IMQSenderManager>().CloseAsync();

            await host.StopAsync();

            var receivedItems = minionLocator.Queue.ToArray();
            var itemGroup     = receivedItems
                                .GroupBy(x => x.Identity);

            foreach (var grouping in itemGroup)
            {
                grouping
                .Select(x => x.Event.Version)
                .Should()
                .BeEquivalentTo(Enumerable.Range(0, count));
            }
        }
示例#11
0
    public static VTrigger CreateUnitEventTrigger(UnitEvent e, TriggerCondition condition, TriggerAction action, int u_id)
    {
        UnitTrigger unitTrigger = (UnitTrigger)TriggerManager.CreateTrigger(TriggerType.UnitTrigger);

        TriggerManager.TriggerRegisterUnitEvent(unitTrigger, e, u_id);
        TriggerManager.TriggerAddCondition(unitTrigger, condition);
        TriggerManager.TriggerAddAction(unitTrigger, action);
        return(unitTrigger);
    }
示例#12
0
        public async Task InitAsync()
        {
            _logger.LogInformation("Start to init async");
            if (_options.Value.SetupLocalDatabase)
            {
                var databaseType = _options.Value.DatabaseType;
                await _dataBaseService.StartAsync(databaseType, 30);

                _logger.LogInformation("Database setup completed.");
            }

            var optionsValue = _options.Value;

            accounts = new IEventSaver[optionsValue.ActorCount];
            _scopes  = new ILifetimeScope[optionsValue.ActorCount];
            var scopes = Enumerable.Range(0, optionsValue.ActorCount)
                         .Select((i, x) =>
            {
                var re = new
                {
                    Scope = _claptrapFactory.BuildClaptrapLifetimeScope(new ClaptrapIdentity(x.ToString(),
                                                                                             Codes.Account)),
                    ClaptrapIdentity = new ClaptrapIdentity(x.ToString(),
                                                            Codes.Account),
                };
                _scopes[i] = re.Scope;
                return(re);
            })
                         .ToArray();

            _logger.LogInformation("Scopes created.");
            for (var i = 0; i < optionsValue.ActorCount; i++)
            {
                accounts[i] = scopes[i].Scope.Resolve <IEventSaver>();
            }

            _logger.LogInformation("Accounts created.");
            events = new UnitEvent[optionsValue.ActorCount];
            for (var i = 0; i < optionsValue.ActorCount; i++)
            {
                events[i] = UnitEvent.Create(scopes[i].ClaptrapIdentity);
            }

            _logger.LogInformation("Events created.");
            versions = new int[optionsValue.ActorCount];

            var id = new ClaptrapIdentity("1", Codes.Account);

            await using var scope = _claptrapFactory.BuildClaptrapLifetimeScope(id);
            var eventSaverMigration = scope.Resolve <IEventSaverMigration>();
            await eventSaverMigration.MigrateAsync();

            _logger.LogInformation("Database migration done.");
        }
示例#13
0
        // [TestCase(1000, 10, false)]
        public async Task SaveEventAsync(int actorCount, int count, bool validateByLoader)
        {
            using var lifetimeScope = BuildService().CreateScope();
            var logger  = lifetimeScope.ServiceProvider.GetRequiredService <ILogger <QuickSetupTestBase> >();
            var factory = (ClaptrapFactory)lifetimeScope.ServiceProvider.GetRequiredService <IClaptrapFactory>();

            var showTimeIndex = actorCount / 10;

            showTimeIndex = showTimeIndex == 0 ? 1 : showTimeIndex;
            var round = 1;
            var tasks = Enumerable.Range(0, actorCount)
                        .Select(async actorId =>
            {
                var index             = Interlocked.Increment(ref round);
                var accountId         = $"acc_{actorId}_{actorCount}_{count}_{index}";
                var id                = new ClaptrapIdentity(accountId, Codes.Account);
                await using var scope = factory.BuildClaptrapLifetimeScope(id);
                var saver             = scope.Resolve <IEventSaver>();
                var sourceEvent       = UnitEvent.Create(id);
                var unitEvents        = Enumerable.Range(Defaults.EventStartingVersion, count)
                                        .Select(x => sourceEvent with {
                    Version = x
                })
                                        .ToArray();
                var sw = Stopwatch.StartNew();
                foreach (var unitEvent in unitEvents)
                {
                    await saver.SaveEventAsync(unitEvent);
                }

                sw.Stop();
                if (actorId / showTimeIndex == 0)
                {
                    Console.WriteLine($"cost {sw.ElapsedMilliseconds} ms to save event");
                }

                if (validateByLoader)
                {
                    var loader = scope.Resolve <IEventLoader>();
                    const int eventBeginVersion = Defaults.StateStartingVersion + 1;
                    var eventEndVersion         = eventBeginVersion + count;
                    var events   = await loader.GetEventsAsync(eventBeginVersion, eventEndVersion);
                    var versions = events.Select(x => x.Version);
                    logger.LogInformation("version from event loader : {version}", versions);
                    versions.Should().BeInAscendingOrder()
                    .And.OnlyHaveUniqueItems()
                    .And.ContainInOrder(Enumerable.Range(Defaults.EventStartingVersion, count));
                }
            });
示例#14
0
    public void SendUnitStateEvent(UnitEvent e, Units tu, Units tt = null, BuffVo buff = null)
    {
        object obj = TriggerManager.unitLockObject;

        lock (obj)
        {
            if (TriggerManager.character_callbacks.ContainsKey((int)e))
            {
                List <UnitTrigger> list = TriggerManager.character_callbacks[(int)e];
                if (list != null)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        UnitTrigger unitTrigger = list[i];
                        if (unitTrigger != null && tu != null)
                        {
                            TriggerManager.m_unit_trigger = unitTrigger;
                            TriggerManager.m_trigger_unit = tu;
                            TriggerManager.m_target_unit  = tt;
                            if (unitTrigger.unit_id == tu.unique_id)
                            {
                                this.doTriggerAction(unitTrigger);
                            }
                            else if (unitTrigger.unit_id == 0)
                            {
                                if (unitTrigger.unit_tag != null && unitTrigger.unit_tag.Equals(tu.tag) && unitTrigger.teamtype == tu.teamType)
                                {
                                    this.doTriggerAction(unitTrigger);
                                }
                                else if (unitTrigger.unit_tag == null && unitTrigger.teamtype == tu.teamType)
                                {
                                    this.doTriggerAction(unitTrigger);
                                }
                                else if (unitTrigger.unit_tag != null && unitTrigger.unit_tag.Equals(tu.tag) && unitTrigger.teamtype == -1)
                                {
                                    this.doTriggerAction(unitTrigger);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
示例#15
0
    public void ProcessEvent(UnitEvent evt)
    {
        state  = UnitState.None;
        change = StateChange.None;

        if (evt == UnitEvent.Update)
        {
            if (_deltaTime >= _checkTime)
            {
                _deltaTime = 0;
                evt        = UnitEvent.UpdateFixTime;
            }
            else
            {
                _deltaTime += Time.deltaTime;
            }
        }

        DoProcess(evt);
    }
示例#16
0
        private async Task RunCoreAsync()
        {
            await MigrateAsync();

            var totalCount = _options.Value.TotalCount;
            var batchSize  = _options.Value.BatchSize;
            var batchCount = totalCount / batchSize;
            var totalW     = Stopwatch.StartNew();
            var endSign    = new int[_options.Value.WorkerCount];
            var tcs        = new TaskCompletionSource <int>();
            var timeBag    = new ConcurrentBag <List <long> >();

            Parallel.For(0, _options.Value.WorkerCount, async workerId =>
            {
                var id = new ClaptrapIdentity(workerId.ToString(), Codes.Account);
                await using var scope = _claptrapFactory.BuildClaptrapLifetimeScope(id);
                var saver             = scope.Resolve <IEventEntitySaver <EventEntity> >();
                var mapper            = scope.Resolve <IEventEntityMapper <EventEntity> >();

                var timeList  = new List <long>();
                var unitEvent = UnitEvent.Create(id);
                var entity    = mapper.Map(unitEvent);

                for (var i = 0; i < batchCount; i++)
                {
                    var versionStart = i * batchSize;
                    var events       = Enumerable.Range(versionStart, batchSize)
                                       .Select(version => entity with {
                        Version = version
                    });

                    var sw = Stopwatch.StartNew();
                    await saver.SaveManyAsync(events);
                    sw.Stop();
                    timeList.Add(sw.ElapsedMilliseconds);
                    _logger.LogTrace("batch {i} {percent:00.00}%: {total}", i, i * 1.0 / batchCount * 100,
                                     sw.Elapsed.Humanize(maxUnit: TimeUnit.Millisecond));
                }
示例#17
0
 protected virtual void DoProcess(UnitEvent evt)
 {
 }
示例#18
0
 public void SendUnitSkillStateEvent(UnitEvent e, Units tu, Skill skill)
 {
     tu.SetSkillContext(skill);
     this.SendUnitStateEvent(e, tu, null, null);
     tu.ClearSkillContext();
 }
示例#19
0
 public static UnitEvent ConvertUnitEvent(int i)
 {
     return(UnitEvent.GetUnitEvent(i));
 }