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))));
     });
 }
Beispiel #2
0
        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);
        }
Beispiel #3
0
        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);
            }
        }
Beispiel #4
0
        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
Beispiel #5
0
        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);
        }
Beispiel #6
0
        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);
        }
Beispiel #7
0
 public void Derive(int index, string expected)
 {
     Assert.Equal(new Address(expected), RankingState.Derive(index));
 }
Beispiel #8
0
        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);
        }
Beispiel #9
0
        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));
        }