public override IAccountStateDelta Execute(IActionContext ctx) { var states = ctx.PreviousStates; var rankingAddress = RankingState.Address; if (ctx.Rehearsal) { states = states.SetState(rankingAddress, MarkChanged); return(states.SetState(_address, MarkChanged)); } states.TryGetState(_address, out Bencodex.Types.Integer currentCount); var nextCount = Math.Max(currentCount - _count, 0); Debug.Log($"decrease_count: CurrentCount: {currentCount}, NextCount: {nextCount}"); RankingState rankingState; if (states.TryGetState(rankingAddress, out Bencodex.Types.Dictionary bdict)) { rankingState = new RankingState(bdict); } else { rankingState = new RankingState(); } rankingState.Update(_address, nextCount); states = states.SetState(rankingAddress, rankingState.Serialize()); return(states.SetState(_address, (Bencodex.Types.Integer)nextCount)); }
public StateQuery() { Name = "StateQuery"; Field <AvatarStateType>( name: "avatar", arguments: new QueryArguments(new QueryArgument <AddressType> { Name = "address", }), resolve: context => { var address = context.GetArgument <Address>("address"); return(new AvatarState((Dictionary)context.Source.GetState(address))); }); Field <RankingMapStateType>( name: "rankingMap", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <IntGraphType> > { Name = "index", }), resolve: context => { var index = context.GetArgument <int>("index"); return(new RankingMapState((Dictionary)context.Source.GetState(RankingState.Derive(index)))); }); }
public async Task HackAndSlash( Address avatarAddress, int worldId, int stageId, Address rankingMapAddress, List <Guid> costumeIds, List <Guid> equipmentIds, List <Guid> consumableIds ) { var playerPrivateKey = new PrivateKey(); var ranking = new RankingState(); for (var i = 0; i < RankingState.RankingMapCapacity; i++) { ranking.RankingMap[RankingState.Derive(i)] = new HashSet <Address>().ToImmutableHashSet(); } var queryArgs = $"avatarAddress: \"{avatarAddress}\", worldId: {worldId}, stageId: {stageId}, rankingMapAddress: \"{rankingMapAddress}\""; if (costumeIds.Any()) { queryArgs += $", costumeIds: [{string.Join(",", costumeIds.Select(r => string.Format($"\"{r}\"")))}]"; } if (equipmentIds.Any()) { queryArgs += $", equipmentIds: [{string.Join(",", equipmentIds.Select(r => string.Format($"\"{r}\"")))}]"; } if (consumableIds.Any()) { queryArgs += $", consumableIds: [{string.Join(",", consumableIds.Select(r => string.Format($"\"{r}\"")))}]"; } var query = @$ "mutation {{ action {{ hackAndSlash({queryArgs}) }} }}"; ExecutionResult result = await ExecuteQueryAsync(query); Assert.Null(result.Errors); var txIds = BlockChain.GetStagedTransactionIds(); Assert.Single(txIds); var tx = BlockChain.GetTransaction(txIds.First()); var expected = new Dictionary <string, object> { ["action"] = new Dictionary <string, object> { ["hackAndSlash"] = tx.Id.ToString(), } }; Assert.Equal(expected, result.Data); Assert.Single(tx.Actions); var action = (HackAndSlash)tx.Actions.First().InnerAction; Assert.Equal(avatarAddress, action.avatarAddress); Assert.Equal(worldId, action.worldId); Assert.Equal(stageId, action.stageId); Assert.Equal(costumeIds, action.costumes); Assert.Equal(equipmentIds, action.equipments); Assert.Equal(consumableIds, action.foods); Assert.Equal(1, action.playCount); }
private void RegisterAliases() { var states = Game.instance.States; for (int i = 0; i < 3; ++i) { if (states.AvatarStates.ContainsKey(i)) { stateProxy.RegisterAlias($"avatar{i}", states.AvatarStates[i].address); } } stateProxy.RegisterAlias("agent", states.AgentState.address); stateProxy.RegisterAlias("shop", states.ShopState.address); for (int i = 0; i < RankingState.RankingMapCapacity; ++i) { stateProxy.RegisterAlias("ranking", RankingState.Derive(i)); } stateProxy.RegisterAlias("gameConfig", GameConfigState.Address); stateProxy.RegisterAlias("redeemCode", RedeemCodeState.Address); if (!(states.CurrentAvatarState is null)) { stateProxy.RegisterAlias("me", states.CurrentAvatarState.address); } }
private bool MatchNext(RankingState rankingState, double ionMz, MatchedFragmentIon match, bool filter, int end, int start, double startMz, ref RankedMI rankedMI) { // Unless trying to match everything, stop looking outside the instrument range if (!rankingState.matchAll && !HasLosses && ionMz > MaxMz) { return(false); } // Check filter properties, if appropriate if ((rankingState.matchAll || ionMz >= MinMz) && Math.Abs(ionMz - rankedMI.ObservedMz) < Libraries.IonMatchTolerance) { // Make sure each m/z value is only used for the most intense peak // that is within the tolerance range. if (rankingState.IsSeen(ionMz)) { return(true); // Keep looking } rankingState.Seen(ionMz); // If this m/z already matched a different ion, just remember the second ion. if (rankedMI.MatchedIons != null) { // If first type was excluded from causing a ranking, but second does, then make it the first // Otherwise, this can cause very mysterious failures to rank transitions that appear in the // document. if (rankedMI.Rank == 0 && ApplyRanking(rankingState, ionMz, match, filter, start, end, startMz, ref rankedMI)) { rankedMI = rankedMI.ChangeMatchedIons(rankedMI.MatchedIons.Prepend(match)); } else { rankedMI = rankedMI.ChangeMatchedIons(rankedMI.MatchedIons.Append(match)); } if (rankedMI.MatchedIons.Count < MAX_MATCH) { return(true); } rankingState.matched = true; return(false); } double predictedMz = match.PredictedMz; // Avoid using the same predicted m/z on two different peaks if (predictedMz == ionMz || !rankingState.IsSeen(predictedMz)) { rankingState.Seen(predictedMz); ApplyRanking(rankingState, ionMz, match, filter, start, end, startMz, ref rankedMI); rankedMI = rankedMI.ChangeMatchedIons(ImmutableList.Singleton(match)); rankingState.matched = !rankingState.matchAll; return(rankingState.matchAll); } } // Stop looking once the mass has been passed, unless there are losses to consider if (HasLosses) { return(true); } return(ionMz <= rankedMI.ObservedMz); }
private IEnumerator UpdateRankingBoard(RankingState rankingState) { foreach (Transform child in rankingBoard.content.transform) { Destroy(child.gameObject); } yield return(new WaitForEndOfFrame()); rankingRow.gameObject.SetActive(true); var ranking = rankingState.GetRanking().ToList(); for (var i = 0; i < ranking.Count; i++) { var rankingInfo = ranking[i]; var go = Instantiate(rankingRow, rankingBoard.content.transform); var row = go.GetComponent <RankingRow>(); var rank = i + 1; row.Set(rank, rankingInfo); if (rankingInfo.Address == AgentController.Agent.Address) { rankingText.text = $"My Ranking: {rank}"; } } rankingRow.gameObject.SetActive(false); yield return(null); }
private bool ApplyRanking(RankingState rankingState, double ionMz, MatchedFragmentIon match, bool filter, int start, int end, double startMz, ref RankedMI rankedMI) { // Avoid ranking precursor ions without losses, if the precursor isotopes will // not be taken from product ions if (!ExcludePrecursorIsotopes || match.IonType != IonType.precursor || match.Losses != null) { int offset = OrdinalToOffset(match.IonType, match.Ordinal); var type = match.IonType; if (filter) { if (TargetInfoObj.LookupMods == null || !TargetInfoObj.LookupMods.HasCrosslinks) { if (!TransitionSettings.Accept(Sequence, MoleculeMassesObj.precursorMz, type, offset, ionMz, start, end, startMz)) { return(false); } } } if (rankingState.matchAll) { if (MinMz > ionMz || ionMz > MaxMz) { return(false); } if (!RankTypes.Contains(type)) { return(false); } if (RankLimit.HasValue && rankingState.Ranked >= RankLimit) { return(false); } if (type != IonType.precursor) { // CONSIDER(bspratt) we may eventually want adduct-level control for small molecules, not just abs charge if (!RankCharges.Contains(Math.Abs(match.Charge.AdductCharge))) { return(false); } } } rankedMI = rankedMI.ChangeRank(rankingState.RankNext()); return(true); } return(false); }
public void Serialize() { var state = new RankingState(); var avatarAddress = new PrivateKey().ToAddress(); state.UpdateRankingMap(avatarAddress); var serialized = state.Serialize(); var des = new RankingState((Dictionary)serialized); Assert.Equal(Addresses.Ranking, des.address); Assert.Contains(des.RankingMap, m => m.Value.Contains(avatarAddress)); }
public void Execute() { var action = new CreateAvatar() { avatarAddress = _avatarAddress, index = 0, hair = 0, ear = 0, lens = 0, tail = 0, name = "test", }; var gold = new GoldCurrencyState(new Currency("NCG", 2, minter: null)); var ranking = new RankingState(); for (var i = 0; i < RankingState.RankingMapCapacity; i++) { ranking.RankingMap[RankingState.Derive(i)] = new HashSet <Address>().ToImmutableHashSet(); } var sheets = TableSheetsImporter.ImportSheets(); var state = new State() .SetState(GoldCurrencyState.Address, gold.Serialize()) .SetState( Addresses.GoldDistribution, GoldDistributionTest.Fixture.Select(v => v.Serialize()).Serialize() ) .SetState( Addresses.GameConfig, new GameConfigState(sheets[nameof(GameConfigSheet)]).Serialize() ) .SetState(Addresses.Ranking, ranking.Serialize()) .MintAsset(GoldCurrencyState.Address, gold.Currency * 100000000000); foreach (var(key, value) in sheets) { state = state.SetState(Addresses.TableSheet.Derive(key), value.Serialize()); } var nextState = action.Execute(new ActionContext() { PreviousStates = state, Signer = _agentAddress, BlockIndex = 0, }); Assert.Equal( 0, nextState.GetBalance(default, gold.Currency).MajorUnit
protected override void LoadPlainValueInternal(IImmutableDictionary <string, IValue> plainValue) { RankingState = new RankingState((Bencodex.Types.Dictionary)plainValue["ranking_state"]); ShopState = new ShopState((Bencodex.Types.Dictionary)plainValue["shop_state"]); TableSheetsState = new TableSheetsState((Bencodex.Types.Dictionary)plainValue["table_sheets_state"]); GameConfigState = new GameConfigState((Bencodex.Types.Dictionary)plainValue["game_config_state"]); RedeemCodeState = new RedeemCodeState((Bencodex.Types.Dictionary)plainValue["redeem_code_state"]); AdminAddressState = new AdminState((Bencodex.Types.Dictionary)plainValue["admin_address_state"]); ActivatedAccountsState = new ActivatedAccountsState( (Bencodex.Types.Dictionary)plainValue["activated_accounts_state"] ); GoldCurrencyState = new GoldCurrencyState( (Bencodex.Types.Dictionary)plainValue["gold_currency_state"] ); }
public override void Render(IActionContext ctx, IAccountStateDelta nextStates) { var agent = Agent.instance; var count = (long)((Integer)nextStates.GetState(ctx.Signer)); var rankingState = new RankingState( (Bencodex.Types.Dictionary)nextStates.GetState(RankingState.Address) ); agent.RunOnMainThread(() => { Game.OnCountUpdated.Invoke(count); }); agent.RunOnMainThread(() => { Game.OnRankUpdated.Invoke(rankingState); }); }
public void UpdateFromQuestRewardDeterministic() { var rankingState = new RankingState(); Address avatarAddress = new PrivateKey().ToAddress(); Address agentAddress = new PrivateKey().ToAddress(); var avatarState = new AvatarState( avatarAddress, agentAddress, 0, _tableSheets.GetAvatarSheets(), new GameConfigState(), rankingState.UpdateRankingMap(avatarAddress)); var itemIds = avatarState.questList.OfType <ItemTypeCollectQuest>().First().ItemIds; var map = new Dictionary <int, int>() { [400000] = 1, [302002] = 1, [302003] = 1, [302001] = 1, [306023] = 1, [302000] = 1, }; var serialized = (Dictionary)avatarState.questList.OfType <WorldQuest>().First().Serialize(); serialized = serialized.SetItem("reward", new Nekoyume.Model.Quest.QuestReward(map).Serialize()); var quest = new WorldQuest(serialized); avatarState.UpdateFromQuestReward(quest, _tableSheets.MaterialItemSheet); Assert.Equal( avatarState.questList.OfType <ItemTypeCollectQuest>().First().ItemIds, new List <int>() { 302000, 302001, 302002, 302003, 306023, } ); }
public async Task CreateAvatar(string name, int index, int hair, int lens, int ear, int tail) { var playerPrivateKey = new PrivateKey(); var ranking = new RankingState(); for (var i = 0; i < RankingState.RankingMapCapacity; i++) { ranking.RankingMap[RankingState.Derive(i)] = new HashSet <Address>().ToImmutableHashSet(); } var query = $@"mutation {{ action {{ createAvatar(avatarName: ""{name}"", avatarIndex: {index}, hairIndex: {hair}, lensIndex: {lens}, earIndex: {ear}, tailIndex: {tail}) }} }}"; ExecutionResult result = await ExecuteQueryAsync(query); Assert.Null(result.Errors); var txIds = BlockChain.GetStagedTransactionIds(); Assert.Single(txIds); var tx = BlockChain.GetTransaction(txIds.First()); var expected = new Dictionary <string, object> { ["action"] = new Dictionary <string, object> { ["createAvatar"] = tx.Id.ToString(), } }; Assert.Equal(expected, result.Data); Assert.Single(tx.Actions); var action = (CreateAvatar2)tx.Actions.First().InnerAction; Assert.Equal(name, action.name); Assert.Equal(index, action.index); Assert.Equal(hair, action.hair); Assert.Equal(lens, action.lens); Assert.Equal(ear, action.ear); Assert.Equal(tail, action.tail); }
public override IAccountStateDelta Execute(IActionContext context) { IActionContext ctx = context; var states = ctx.PreviousStates; var weeklyArenaState = new WeeklyArenaState(0); if (ctx.Rehearsal) { states = states.SetState(RankingState.Address, MarkChanged); states = states.SetState(ShopState.Address, MarkChanged); states = states.SetState(TableSheetsState.Address, MarkChanged); states = states.SetState(weeklyArenaState.address, MarkChanged); states = states.SetState(GameConfigState.Address, MarkChanged); states = states.SetState(RedeemCodeState.Address, MarkChanged); states = states.SetState(AdminState.Address, MarkChanged); states = states.SetState(ActivatedAccountsState.Address, MarkChanged); states = states.SetState(GoldCurrencyState.Address, MarkChanged); states = states.SetState(Addresses.GoldDistribution, MarkChanged); return(states); } if (ctx.BlockIndex != 0) { return(states); } states = states .SetState(weeklyArenaState.address, weeklyArenaState.Serialize()) .SetState(RankingState.Address, RankingState.Serialize()) .SetState(ShopState.Address, ShopState.Serialize()) .SetState(TableSheetsState.Address, TableSheetsState.Serialize()) .SetState(GameConfigState.Address, GameConfigState.Serialize()) .SetState(RedeemCodeState.Address, RedeemCodeState.Serialize()) .SetState(AdminState.Address, AdminAddressState.Serialize()) .SetState(ActivatedAccountsState.Address, ActivatedAccountsState.Serialize()) .SetState(GoldCurrencyState.Address, GoldCurrencyState.Serialize()) .SetState(Addresses.GoldDistribution, GoldDistributions.Select(v => v.Serialize()).Serialize()); states = states.MintAsset(GoldCurrencyState.Address, GoldCurrencyState.Currency, 1000000000); return(states); }
public void Deterministic_Between_SerializeV1_And_SerializeV1_With_Deterministic_Problem() { var state = new RankingState(); for (var i = 0; i < 1000; i++) { state.UpdateRankingMap(new PrivateKey().ToAddress()); } var serializedV1 = state.Serialize(); var serializedV1WithDeterministicProblem = SerializeV1_With_Deterministic_Problem(state); Assert.Equal(serializedV1WithDeterministicProblem, serializedV1); var deserialized = new RankingState((Bencodex.Types.Dictionary)serializedV1); var deserializedV1 = new RankingState((Bencodex.Types.Dictionary)serializedV1WithDeterministicProblem); serializedV1 = deserialized.Serialize(); serializedV1WithDeterministicProblem = deserializedV1.Serialize(); Assert.Equal(serializedV1WithDeterministicProblem, serializedV1); }
public InitializeStates( RankingState rankingState, ShopState shopState, Dictionary <string, string> tableSheets, GameConfigState gameConfigState, RedeemCodeState redeemCodeState, AdminState adminAddressState, ActivatedAccountsState activatedAccountsState, GoldCurrencyState goldCurrencyState, GoldDistribution[] goldDistributions, PendingActivationState[] pendingActivationStates, AuthorizedMinersState authorizedMinersState = null, CreditsState creditsState = null) { Ranking = (Bencodex.Types.Dictionary)rankingState.Serialize(); Shop = (Bencodex.Types.Dictionary)shopState.Serialize(); TableSheets = tableSheets; GameConfig = (Bencodex.Types.Dictionary)gameConfigState.Serialize(); RedeemCode = (Bencodex.Types.Dictionary)redeemCodeState.Serialize(); AdminAddress = (Bencodex.Types.Dictionary)adminAddressState.Serialize(); ActivatedAccounts = (Bencodex.Types.Dictionary)activatedAccountsState.Serialize(); GoldCurrency = (Bencodex.Types.Dictionary)goldCurrencyState.Serialize(); GoldDistributions = new Bencodex.Types.List( goldDistributions.Select(d => d.Serialize()).Cast <Bencodex.Types.IValue>() ); PendingActivations = new Bencodex.Types.List(pendingActivationStates.Select(p => p.Serialize())); if (!(authorizedMinersState is null)) { AuthorizedMiners = (Bencodex.Types.Dictionary)authorizedMinersState.Serialize(); } if (!(creditsState is null)) { Credits = (Bencodex.Types.Dictionary)creditsState.Serialize(); } }
public async Task DailyReward() { var playerPrivateKey = new PrivateKey(); var ranking = new RankingState(); for (var i = 0; i < RankingState.RankingMapCapacity; i++) { ranking.RankingMap[RankingState.Derive(i)] = new HashSet <Address>().ToImmutableHashSet(); } var avatarAddress = new Address(); var query = $@"mutation {{ action {{ dailyReward(avatarAddress: ""{avatarAddress}"") }} }}"; ExecutionResult result = await ExecuteQueryAsync(query); Assert.Null(result.Errors); var txIds = BlockChain.GetStagedTransactionIds(); Assert.Single(txIds); var tx = BlockChain.GetTransaction(txIds.First()); var expected = new Dictionary <string, object> { ["action"] = new Dictionary <string, object> { ["dailyReward"] = tx.Id.ToString(), } }; Assert.Equal(expected, result.Data); Assert.Single(tx.Actions); var action = (DailyReward)tx.Actions.First().InnerAction; Assert.Equal(avatarAddress, action.avatarAddress); }
public override IAccountStateDelta Execute(IActionContext ctx) { var states = ctx.PreviousStates; var rankingAddress = RankingState.Address; states.TryGetState(ctx.Signer, out Bencodex.Types.Integer currentCount); var nextCount = currentCount + _count; Debug.Log($"store_count: CurrentCount: {currentCount}, NextCount: {nextCount}"); RankingState rankingState; if (states.TryGetState(rankingAddress, out Bencodex.Types.Dictionary bdict)) { rankingState = new RankingState(bdict); } else { rankingState = new RankingState(); } rankingState.Update(ctx.Signer, nextCount); states = states.SetState(rankingAddress, rankingState.Serialize()); return(states.SetState(ctx.Signer, (Bencodex.Types.Integer)nextCount)); }
public override IAccountStateDelta Execute(IActionContext context) { IActionContext ctx = context; var states = ctx.PreviousStates; var weeklyArenaState = new WeeklyArenaState(0); var rankingState = new RankingState(Ranking); if (ctx.Rehearsal) { states = states.SetState(RankingState.Address, MarkChanged); states = states.SetState(ShopState.Address, MarkChanged); #pragma warning disable LAA1002 states = TableSheets .Aggregate(states, (current, pair) => current.SetState(Addresses.TableSheet.Derive(pair.Key), MarkChanged)); states = rankingState.RankingMap .Aggregate(states, (current, pair) => current.SetState(pair.Key, MarkChanged)); #pragma warning restore LAA1002 states = states.SetState(weeklyArenaState.address, MarkChanged); states = states.SetState(GameConfigState.Address, MarkChanged); states = states.SetState(RedeemCodeState.Address, MarkChanged); states = states.SetState(AdminState.Address, MarkChanged); states = states.SetState(ActivatedAccountsState.Address, MarkChanged); states = states.SetState(GoldCurrencyState.Address, MarkChanged); states = states.SetState(Addresses.GoldDistribution, MarkChanged); foreach (var rawPending in PendingActivations) { states = states.SetState( new PendingActivationState((Bencodex.Types.Dictionary)rawPending).address, MarkChanged ); } states = states.SetState(AuthorizedMinersState.Address, MarkChanged); states = states.SetState(CreditsState.Address, MarkChanged); return(states); } if (ctx.BlockIndex != 0) { return(states); } #pragma warning disable LAA1002 states = TableSheets .Aggregate(states, (current, pair) => current.SetState(Addresses.TableSheet.Derive(pair.Key), pair.Value.Serialize())); states = rankingState.RankingMap .Aggregate(states, (current, pair) => current.SetState(pair.Key, new RankingMapState(pair.Key).Serialize())); #pragma warning restore LAA1002 states = states .SetState(weeklyArenaState.address, weeklyArenaState.Serialize()) .SetState(RankingState.Address, Ranking) .SetState(ShopState.Address, Shop) .SetState(GameConfigState.Address, GameConfig) .SetState(RedeemCodeState.Address, RedeemCode) .SetState(AdminState.Address, AdminAddress) .SetState(ActivatedAccountsState.Address, ActivatedAccounts) .SetState(GoldCurrencyState.Address, GoldCurrency) .SetState(Addresses.GoldDistribution, GoldDistributions); if (!(AuthorizedMiners is null)) { states = states.SetState( AuthorizedMinersState.Address, AuthorizedMiners ); } foreach (var rawPeding in PendingActivations) { states = states.SetState( new PendingActivationState((Bencodex.Types.Dictionary)rawPeding).address, rawPeding ); } if (!(Credits is null)) { states = states.SetState(CreditsState.Address, Credits); } var currency = new GoldCurrencyState(GoldCurrency).Currency; states = states.MintAsset(GoldCurrencyState.Address, currency * 1000000000); return(states); }
public static MakeInitialStateResult MakeInitialState() { var goldCurrencyState = new GoldCurrencyState(new Currency("NCG", 2, minter: null)); var ranking = new RankingState(); for (var i = 0; i < RankingState.RankingMapCapacity; i++) { ranking.RankingMap[RankingState.Derive(i)] = new HashSet <Address>().ToImmutableHashSet(); } var sheets = TableSheetsImporter.ImportSheets(); var initialState = new Tests.Action.State() .SetState(GoldCurrencyState.Address, goldCurrencyState.Serialize()) .SetState( Addresses.GoldDistribution, GoldDistributionTest.Fixture.Select(v => v.Serialize()).Serialize() ) .SetState( Addresses.GameConfig, new GameConfigState(sheets[nameof(GameConfigSheet)]).Serialize() ) .SetState(Addresses.Ranking, ranking.Serialize()); foreach (var(key, value) in sheets) { initialState = initialState.SetState(Addresses.TableSheet.Derive(key), value.Serialize()); } var tableSheets = new TableSheets(sheets); var rankingMapAddress = new PrivateKey().ToAddress(); var agentAddress = new PrivateKey().ToAddress(); var agentState = new AgentState(agentAddress); var avatarAddress = new PrivateKey().ToAddress(); var avatarState = new AvatarState( avatarAddress, agentAddress, 0, tableSheets.GetAvatarSheets(), new GameConfigState(), rankingMapAddress) { worldInformation = new WorldInformation( 0, tableSheets.WorldSheet, GameConfig.RequireClearedStageLevel.ActionsInShop), }; agentState.avatarAddresses[0] = avatarAddress; var initCurrencyGold = goldCurrencyState.Currency * 100000000000; var agentCurrencyGold = goldCurrencyState.Currency * 1000; var remainCurrencyGold = initCurrencyGold - agentCurrencyGold; initialState = initialState .SetState(GoldCurrencyState.Address, goldCurrencyState.Serialize()) .SetState(agentAddress, agentState.Serialize()) .SetState(avatarAddress, avatarState.Serialize()) .SetState(Addresses.Shop, new ShopState().Serialize()) .MintAsset(GoldCurrencyState.Address, initCurrencyGold) .TransferAsset(Addresses.GoldCurrency, agentAddress, agentCurrencyGold); var action = new CreateTestbed(); var nextState = action.Execute(new ActionContext() { BlockIndex = 0, PreviousStates = initialState, Random = new TestRandom(), Rehearsal = false, }); return(new MakeInitialStateResult( nextState, action, agentState, avatarState, goldCurrencyState, rankingMapAddress, tableSheets, remainCurrencyGold, agentCurrencyGold)); }
public void UpdateRankingMap() { var state = new RankingState(); state.UpdateRankingMap(default);
private IEnumerator CoJoin(Action <bool> callback) { Task t = Task.Run(async() => { await _hub.JoinAsync(); }); yield return(new WaitUntil(() => t.IsCompleted)); if (t.IsFaulted) { callback?.Invoke(false); yield break; } Connected = true; // 에이전트의 상태를 한 번 동기화 한다. Currency goldCurrency = new GoldCurrencyState( (Dictionary)GetState(GoldCurrencyState.Address) ).Currency; States.Instance.SetAgentState( GetState(Address) is Bencodex.Types.Dictionary agentDict ? new AgentState(agentDict) : new AgentState(Address)); States.Instance.SetGoldBalanceState( new GoldBalanceState(Address, GetBalance(Address, goldCurrency))); // 랭킹의 상태를 한 번 동기화 한다. for (var i = 0; i < RankingState.RankingMapCapacity; ++i) { var address = RankingState.Derive(i); var mapState = GetState(address) is Bencodex.Types.Dictionary serialized ? new RankingMapState(serialized) : new RankingMapState(address); States.Instance.SetRankingMapStates(mapState); } // 상점의 상태를 한 번 동기화 한다. States.Instance.SetShopState( GetState(ShopState.Address) is Bencodex.Types.Dictionary shopDict ? new ShopState(shopDict) : new ShopState()); if (GetState(GameConfigState.Address) is Dictionary configDict) { States.Instance.SetGameConfigState(new GameConfigState(configDict)); } else { throw new FailedToInstantiateStateException <GameConfigState>(); } if (ArenaHelper.TryGetThisWeekState(BlockIndex, out var weeklyArenaState)) { States.Instance.SetWeeklyArenaState(weeklyArenaState); } else { throw new FailedToInstantiateStateException <WeeklyArenaState>(); } ActionRenderHandler.Instance.GoldCurrency = goldCurrency; // 그리고 모든 액션에 대한 랜더와 언랜더를 핸들링하기 시작한다. BlockRenderHandler.Instance.Start(BlockRenderer); ActionRenderHandler.Instance.Start(ActionRenderer); ActionUnrenderHandler.Instance.Start(ActionRenderer); UpdateSubscribeAddresses(); callback?.Invoke(true); }
public void Derive(int index, string expected) { Assert.Equal(new Address(expected), RankingState.Derive(index)); }
public override IAccountStateDelta Execute(IActionContext context) { IActionContext ctx = context; var states = ctx.PreviousStates; if (ctx.Rehearsal) { states = states.SetState(RankingState.Address, MarkChanged); states = states.SetState(avatarAddress, MarkChanged); states = states.SetState(WeeklyArenaAddress, MarkChanged); return(states.SetState(ctx.Signer, MarkChanged)); } var sw = new Stopwatch(); sw.Start(); var started = DateTimeOffset.UtcNow; Log.Debug("HAS exec started."); if (!states.TryGetAgentAvatarStates( ctx.Signer, avatarAddress, out AgentState agentState, out AvatarState avatarState)) { return(LogError( context, "Aborted as the avatar state of the signer was failed to load.")); } sw.Stop(); Log.Debug("HAS Get AgentAvatarStates: {Elapsed}", sw.Elapsed); sw.Restart(); var tableSheetState = TableSheetsState.FromActionContext(ctx); sw.Stop(); Log.Debug("HAS Get TableSheetsState: {Elapsed}", sw.Elapsed); sw.Restart(); var tableSheets = TableSheets.FromTableSheetsState(tableSheetState); sw.Stop(); Log.Debug("HAS Initialize TableSheets: {Elapsed}", sw.Elapsed); // worldId와 stageId가 유효한지 확인합니다. if (!tableSheets.WorldSheet.TryGetValue(worldId, out var worldRow)) { return(LogError( context, "Not fount {WorldId} in TableSheets.WorldSheet.", worldId )); } if (stageId < worldRow.StageBegin || stageId > worldRow.StageEnd) { return(LogError( context, "{WorldId} world is not contains {StageId} stage: {StageBegin}-{StageEnd}", stageId, worldRow.Id, worldRow.StageBegin, worldRow.StageEnd )); } if (!tableSheets.StageSheet.TryGetValue(stageId, out var stageRow)) { return(LogError( context, "Not fount stage id in TableSheets.StageSheet: {StageId}", stageId )); } var worldInformation = avatarState.worldInformation; if (!worldInformation.TryGetWorld(worldId, out var world)) { // NOTE: 이 경우는 아바타 생성 시에는 WorldSheet에 없던 worldId가 새로 추가된 경우로 볼 수 있습니다. if (!worldInformation.TryAddWorld(worldRow, out world)) { return(LogError(context, "Failed to add {WorldId} world to WorldInformation.", worldId)); } } if (!world.IsUnlocked) { return(LogError(context, "Aborted as the world {WorldId} is locked.", worldId)); } if (world.StageBegin != worldRow.StageBegin || world.StageEnd != worldRow.StageEnd) { // NOTE: 이 경우는 아바타 생성 이후에 worldId가 포함하는 stageId의 범위가 바뀐 경우로 볼 수 있습니다. if (!worldInformation.TryUpdateWorld(worldRow, out world)) { return(LogError(context, "Failed to update {WorldId} world in WorldInformation.", worldId)); } if (world.StageBegin != worldRow.StageBegin || world.StageEnd != worldRow.StageEnd) { return(LogError(context, "Failed to update {WorldId} world in WorldInformation.", worldId)); } } if (world.IsStageCleared && stageId > world.StageClearedId + 1 || !world.IsStageCleared && stageId != world.StageBegin) { return(LogError( context, "Aborted as the stage ({WorldId}/{StageId}) is not cleared; cleared stage: {StageClearedId}", worldId, stageId, world.StageClearedId )); } // 장비가 유효한지 검사한다. if (!avatarState.ValidateEquipments(equipments, context.BlockIndex)) { // 장비가 유효하지 않은 에러. return(LogError(context, "Aborted as the equipment is invalid.")); } sw.Restart(); if (avatarState.actionPoint < stageRow.CostAP) { return(LogError( context, "Aborted due to insufficient action point: {ActionPointBalance} < {ActionCost}", avatarState.actionPoint, stageRow.CostAP )); } avatarState.actionPoint -= stageRow.CostAP; avatarState.EquipCostumes(costumes); avatarState.EquipEquipments(equipments); sw.Stop(); Log.Debug("HAS Unequip items: {Elapsed}", sw.Elapsed); sw.Restart(); var simulator = new StageSimulator( ctx.Random, avatarState, foods, worldId, stageId, tableSheets ); sw.Stop(); Log.Debug("HAS Initialize Simulator: {Elapsed}", sw.Elapsed); sw.Restart(); simulator.Simulate(); sw.Stop(); Log.Debug("HAS Simulator.Simulate(): {Elapsed}", sw.Elapsed); Log.Debug( "Execute HackAndSlash({AvatarAddress}); worldId: {WorldId}, stageId: {StageId}, result: {Result}, " + "clearWave: {ClearWave}, totalWave: {TotalWave}", avatarAddress, worldId, stageId, simulator.Log.result, simulator.Log.clearedWaveNumber, simulator.Log.waveCount ); sw.Restart(); if (simulator.Log.IsClear) { try { simulator.Player.worldInformation.ClearStage( worldId, stageId, ctx.BlockIndex, tableSheets.WorldSheet, tableSheets.WorldUnlockSheet ); } catch (FailedToUnlockWorldException e) { Log.Error(e.Message); throw; } } sw.Stop(); Log.Debug("HAS ClearStage: {Elapsed}", sw.Elapsed); sw.Restart(); avatarState.Update(simulator); avatarState.UpdateQuestRewards(ctx); avatarState.updatedAt = DateTimeOffset.UtcNow; states = states.SetState(avatarAddress, avatarState.Serialize()); sw.Stop(); Log.Debug("HAS Set AvatarState: {Elapsed}", sw.Elapsed); sw.Restart(); if (states.TryGetState(RankingState.Address, out Dictionary d) && simulator.Log.IsClear) { var ranking = new RankingState(d); ranking.Update(avatarState); sw.Stop(); Log.Debug("HAS Update RankingState: {Elapsed}", sw.Elapsed); sw.Restart(); var serialized = ranking.Serialize(); sw.Stop(); Log.Debug("HAS Serialize RankingState: {Elapsed}", sw.Elapsed); sw.Restart(); states = states.SetState(RankingState.Address, serialized); } sw.Stop(); Log.Debug("HAS Set RankingState: {Elapsed}", sw.Elapsed); sw.Restart(); if (states.TryGetState(WeeklyArenaAddress, out Dictionary weeklyDict)) { var weekly = new WeeklyArenaState(weeklyDict); if (!weekly.Ended) { if (weekly.ContainsKey(avatarAddress)) { var info = weekly[avatarAddress]; info.Update(avatarState, tableSheets.CharacterSheet); weekly.Update(info); } else { weekly.Set(avatarState, tableSheets.CharacterSheet); } sw.Stop(); Log.Debug("HAS Update WeeklyArenaState: {Elapsed}", sw.Elapsed); sw.Restart(); var weeklySerialized = weekly.Serialize(); sw.Stop(); Log.Debug("HAS Serialize RankingState: {Elapsed}", sw.Elapsed); states = states.SetState(weekly.address, weeklySerialized); } } Result = simulator.Log; var ended = DateTimeOffset.UtcNow; Log.Debug("HAS Total Executed Time: {Elapsed}", ended - started); return(states.SetState(ctx.Signer, agentState.Serialize())); }
private RankedMI CalculateRank(RankingState rankingState, RankedMI rankedMI) { // Rank based on filtered range, if the settings use it in picking bool filter = (Pick == TransitionLibraryPick.filter); var knownFragments = MoleculeMassesObj.MatchIonMasses.KnownFragments; if (knownFragments != null) { // Small molecule work - we only know about the fragments we're given, we can't predict others foreach (IonType type in Types) { if (Transition.IsPrecursor(type)) { var matchedFragmentIon = MakeMatchedFragmentIon(type, 0, PrecursorAdduct, null, out double matchMz); if (!MatchNext(rankingState, matchMz, matchedFragmentIon, filter, 0, 0, 0, ref rankedMI)) { // If matched return. Otherwise look for other ion types. if (rankingState.matched) { rankingState.Clean(); return(rankedMI); } } } else { for (var i = 0; i < knownFragments.Count; i++) { var fragment = knownFragments[i]; double matchMz = MoleculeMassesObj.PredictIonMasses.KnownFragments[i].PredictedMz; if (!MatchNext(rankingState, matchMz, fragment, filter, 0, 0, fragment.PredictedMz, ref rankedMI)) { // If matched return. Otherwise look for other ion types. if (rankingState.matched) { rankingState.Clean(); return(rankedMI); } } } } } return(rankedMI); } // Look for a predicted match within the acceptable tolerance int len = MoleculeMassesObj.MatchIonMasses.FragmentMasses.GetLength(1); foreach (IonType type in Types) { if (Transition.IsPrecursor(type)) { foreach (var losses in TransitionGroup.CalcTransitionLosses(type, 0, MassType, PotentialLosses)) { var matchedFragmentIon = MakeMatchedFragmentIon(type, 0, PrecursorAdduct, losses, out double matchMz); if (!MatchNext(rankingState, matchMz, matchedFragmentIon, filter, len, len, 0, ref rankedMI)) { // If matched return. Otherwise look for other ion types. if (rankingState.matched) { rankingState.Clean(); return(rankedMI); } } } continue; } foreach (var adduct in Adducts) { // Precursor charge can never be lower than product ion charge. if (Math.Abs(PrecursorAdduct.AdductCharge) < Math.Abs(adduct.AdductCharge)) { continue; } int start = 0, end = 0; double startMz = 0; if (filter) { start = TransitionSettings.Filter.FragmentRangeFirst.FindStartFragment( MoleculeMassesObj.MatchIonMasses.FragmentMasses, type, adduct, MoleculeMassesObj.precursorMz, TransitionSettings.Filter.PrecursorMzWindow, out startMz); end = TransitionSettings.Filter.FragmentRangeLast.FindEndFragment(type, start, len); if (Transition.IsCTerminal(type)) { Helpers.Swap(ref start, ref end); } } // These inner loops are performance bottlenecks, and the following // code duplication proved the fastest implementation under a // profiler. Apparently .NET failed to inline an attempt to put // the loop contents in a function. if (Transition.IsCTerminal(type)) { for (int i = len - 1; i >= 0; i--) { foreach (var losses in TransitionGroup.CalcTransitionLosses(type, i, MassType, PotentialLosses)) { var matchedFragmentIon = MakeMatchedFragmentIon(type, i, adduct, losses, out double matchMz); if (!MatchNext(rankingState, matchMz, matchedFragmentIon, filter, end, start, startMz, ref rankedMI)) { if (rankingState.matched) { rankingState.Clean(); return(rankedMI); } i = -1; // Terminate loop on i break; } } } } else { for (int i = 0; i < len; i++) { foreach (var losses in TransitionGroup.CalcTransitionLosses(type, i, MassType, PotentialLosses)) { var matchedFragmentIon = MakeMatchedFragmentIon(type, i, adduct, losses, out double matchMz); if (!MatchNext(rankingState, matchMz, matchedFragmentIon, filter, end, start, startMz, ref rankedMI)) { if (rankingState.matched) { rankingState.Clean(); return(rankedMI); } i = len; // Terminate loop on i break; } } } } } } return(rankedMI); }
public override IAccountStateDelta Execute(IActionContext context) { IActionContext ctx = context; var states = ctx.PreviousStates; var avatarAddress = ctx.Signer.Derive( string.Format( CultureInfo.InvariantCulture, DeriveFormat, index ) ); var inventoryAddress = avatarAddress.Derive(LegacyInventoryKey); var worldInformationAddress = avatarAddress.Derive(LegacyWorldInformationKey); var questListAddress = avatarAddress.Derive(LegacyQuestListKey); if (ctx.Rehearsal) { states = states.SetState(ctx.Signer, MarkChanged); for (var i = 0; i < AvatarState.CombinationSlotCapacity; i++) { var slotAddress = avatarAddress.Derive( string.Format( CultureInfo.InvariantCulture, CombinationSlotState.DeriveFormat, i ) ); states = states.SetState(slotAddress, MarkChanged); } return(states .SetState(avatarAddress, MarkChanged) .SetState(Addresses.Ranking, MarkChanged) .SetState(inventoryAddress, MarkChanged) .SetState(worldInformationAddress, MarkChanged) .SetState(questListAddress, MarkChanged) .MarkBalanceChanged(GoldCurrencyMock, GoldCurrencyState.Address, context.Signer)); } var addressesHex = GetSignerAndOtherAddressesHex(context, avatarAddress); if (!Regex.IsMatch(name, GameConfig.AvatarNickNamePattern)) { throw new InvalidNamePatternException( $"{addressesHex}Aborted as the input name {name} does not follow the allowed name pattern."); } var sw = new Stopwatch(); sw.Start(); var started = DateTimeOffset.UtcNow; Log.Verbose("{AddressesHex}CreateAvatar exec started", addressesHex); AgentState existingAgentState = states.GetAgentState(ctx.Signer); var agentState = existingAgentState ?? new AgentState(ctx.Signer); var avatarState = states.GetAvatarState(avatarAddress); if (!(avatarState is null)) { throw new InvalidAddressException( $"{addressesHex}Aborted as there is already an avatar at {avatarAddress}."); } if (!(0 <= index && index < GameConfig.SlotCount)) { throw new AvatarIndexOutOfRangeException( $"{addressesHex}Aborted as the index is out of range #{index}."); } if (agentState.avatarAddresses.ContainsKey(index)) { throw new AvatarIndexAlreadyUsedException( $"{addressesHex}Aborted as the signer already has an avatar at index #{index}."); } sw.Stop(); Log.Verbose("{AddressesHex}CreateAvatar Get AgentAvatarStates: {Elapsed}", addressesHex, sw.Elapsed); sw.Restart(); Log.Verbose("{AddressesHex}Execute CreateAvatar; player: {AvatarAddress}", addressesHex, avatarAddress); agentState.avatarAddresses.Add(index, avatarAddress); // Avoid NullReferenceException in test var materialItemSheet = ctx.PreviousStates.GetSheet <MaterialItemSheet>(); RankingState rankingState = ctx.PreviousStates.GetRankingState(); var rankingMapAddress = rankingState.UpdateRankingMap(avatarAddress); avatarState = CreateAvatar0.CreateAvatarState(name, avatarAddress, ctx, materialItemSheet, rankingMapAddress); if (hair < 0) { hair = 0; } if (lens < 0) { lens = 0; } if (ear < 0) { ear = 0; } if (tail < 0) { tail = 0; } avatarState.Customize(hair, lens, ear, tail); foreach (var address in avatarState.combinationSlotAddresses) { var slotState = new CombinationSlotState(address, GameConfig.RequireClearedStageLevel.CombinationEquipmentAction); states = states.SetState(address, slotState.Serialize()); } avatarState.UpdateQuestRewards(materialItemSheet); sw.Stop(); Log.Verbose("{AddressesHex}CreateAvatar CreateAvatarState: {Elapsed}", addressesHex, sw.Elapsed); var ended = DateTimeOffset.UtcNow; Log.Verbose("{AddressesHex}CreateAvatar Total Executed Time: {Elapsed}", addressesHex, ended - started); return(states .SetState(ctx.Signer, agentState.Serialize()) .SetState(Addresses.Ranking, rankingState.Serialize()) .SetState(inventoryAddress, avatarState.inventory.Serialize()) .SetState(worldInformationAddress, avatarState.worldInformation.Serialize()) .SetState(questListAddress, avatarState.questList.Serialize()) .SetState(avatarAddress, avatarState.SerializeV2())); }
public LibraryRankedSpectrumInfo RankSpectrum(SpectrumPeaksInfo info, int minPeaks, double?score) { var ionsToReturn = FragmentFilterObj.FragmentMatchCount; RankingState rankingState = new RankingState() { matchAll = MatchAll, }; // Get the library spectrum mass-intensity pairs IList <SpectrumPeaksInfo.MI> listMI = info.Peaks; // Because sorting and matching observed ions with predicted // ions appear as bottlenecks in a profiler, a minimum number // of peaks may be supplied to allow the use of a 2-phase linear // filter that can significantly reduce the number of peaks // needing the O(n*log(n)) sorting and the O(n*m) matching. int len = listMI.Count; float intensityCutoff = 0; if (minPeaks != -1) { // Start searching for good cut-off at mean intensity. double totalIntensity = info.Intensities.Sum(); FindIntensityCutoff(listMI, 0, (float)(totalIntensity / len) * 2, minPeaks, 1, ref intensityCutoff, ref len); } // Create filtered peak array storing original index for m/z ordering // to avoid needing to sort to return to this order. RankedMI[] arrayRMI = new RankedMI[len]; // Detect when m/z values are out of order, and use the expensive sort // by m/z to correct this. double lastMz = double.MinValue; bool sortMz = false; for (int i = 0, j = 0, lenOrig = listMI.Count; i < lenOrig; i++) { SpectrumPeaksInfo.MI mi = listMI[i]; if (mi.Intensity >= intensityCutoff || intensityCutoff == 0) { arrayRMI[j] = new RankedMI(mi, j); j++; } if (!ionsToReturn.HasValue) { if (mi.Mz < lastMz) { sortMz = true; } lastMz = mi.Mz; } } // The one expensive sort is used to determine rank order // by intensity, or m/z in case of a tie. Array.Sort(arrayRMI, OrderIntensityDesc); RankedMI[] arrayResult = new RankedMI[ionsToReturn.HasValue ? ionsToReturn.Value : arrayRMI.Length]; foreach (RankedMI rmi in arrayRMI) { var rankedRmi = CalculateRank(rankingState, rmi); // If not filtering for only the highest ionMatchCount ranks if (!ionsToReturn.HasValue) { // Put the ranked record back where it started in the // m/z ordering to avoid a second sort. arrayResult[rmi.IndexMz] = rankedRmi; } // Otherwise, if this ion was ranked, add it to the result array else if (rankedRmi.Rank > 0) { int countRanks = rankedRmi.Rank; arrayResult[countRanks - 1] = rankedRmi; // And stop when the array is full if (countRanks == ionsToReturn.Value) { break; } } } // Is this a theoretical library with no intensity variation? If so it can't be ranked. // If it has any interesting peak annotations, pass those through if (rankingState.Ranked == 0 && arrayRMI.All(rmi => rmi.Intensity == arrayRMI[0].Intensity)) { // Only do this if we have been asked to limit the ions matched, and there are any annotations if (ionsToReturn.HasValue && arrayRMI.Any(rmi => rmi.HasAnnotations)) { // Pass through anything with an annotation as being of probable interest arrayResult = arrayRMI.Where(rmi => rmi.HasAnnotations).ToArray(); ionsToReturn = null; } } // If not enough ranked ions were found, fill the rest of the results array if (ionsToReturn.HasValue) { for (int i = rankingState.Ranked; i < ionsToReturn.Value; i++) { arrayResult[i] = RankedMI.EMPTY; } } // If all ions are to be included, and some were found out of order, then // the expensive full sort by m/z is necessary. else if (sortMz) { Array.Sort(arrayResult, OrderMz); } double?spectrumScore; if (score == null && GroupDocNode.HasLibInfo && GroupDocNode.LibInfo is BiblioSpecSpectrumHeaderInfo libInfo) { spectrumScore = libInfo.Score; } else { spectrumScore = score; } return(new LibraryRankedSpectrumInfo(PredictLabelType, Libraries.IonMatchTolerance, arrayResult, spectrumScore)); }