示例#1
0
文件: HighRollTurn.cs 项目: Corne/VOC
        public void AfterExecute(GameCommand command)
        {
            if (!CanExecute(command)) return;

            Result = dice.Current.Result;
            Ended?.Invoke(this, EventArgs.Empty);
        }
示例#2
0
        public void AfterExecute(GameCommand command)
        {
            if (command != GameCommand.Monopoly)
                return;

            turn.NextFlowState();
        }
示例#3
0
        public void ExpectNothingToHappenIfCommandNotYearofPlenty(GameCommand command)
        {
            var turn = new Mock<IGameTurn>();
            var state = new YearOfPlentyState(turn.Object);

            state.AfterExecute(command);
            turn.Verify(t => t.NextFlowState(), Times.Never);
        }
示例#4
0
文件: TurnTest.cs 项目: Corne/VOC
        public void ExpectCanExecuteAlwaysFalseIfIfTurnNotStarted(GameCommand command)
        {
            var player = new Mock<IPlayer>();
            var provider = new Mock<IStateProvider>();

            var turn = new Turn(player.Object, provider.Object);
            Assert.False(turn.CanExecute(command));
        }
示例#5
0
文件: BuildState.cs 项目: Corne/VOC
 public void AfterExecute(GameCommand command)
 {
     if (command == GameCommand.NextState)
     {
         Completed = true;
         turn.NextFlowState();
     }
 }
示例#6
0
文件: Move.cs 项目: wx3/galacdecks
 public override void HandleCommand(GameCommand command)
 {
     base.HandleCommand(command);
     if (command is MoveCommand)
     {
         IsSatisfied = true;
     }
 }
示例#7
0
        public void ExpectNothingFromOtherCommands(GameCommand command1, GameCommand command2)
        {
            var turn = new Mock<IGameTurn>();
            var state = new RoadBuildingState(turn.Object);

            state.AfterExecute(command1);
            state.AfterExecute(command2);

            turn.Verify(t => t.NextFlowState(), Times.Never);
        }
示例#8
0
        public void ExpectNothingToHappenIfCommandNotNextState(GameCommand command)
        {
            var turn = new Mock<IGameTurn>();
            var state = new BuildState(turn.Object);

            state.AfterExecute(command);

            turn.Verify(t => t.NextFlowState(), Times.Never);
            Assert.False(state.Completed);
        }
示例#9
0
        public void AfterExecute(GameCommand command)
        {
            if (command != GameCommand.BuildRoad)
                return;

            buildCounter++;

            if (buildCounter == 2)
                turn.NextFlowState();
        }
示例#10
0
        public void ExpectNothingToHappenIfCommandNotMoveRobber(GameCommand command)
        {
            var turn = new Mock<IGameTurn>();
            var robber = CreateRobber();

            var state = new MoveRobberState(turn.Object, robber);
            state.AfterExecute(command);

            turn.Verify(t => t.SetState<RobberStealState>(), Times.Never);
        }
示例#11
0
文件: RollState.cs 项目: Corne/VOC
        public void AfterExecute(GameCommand command)
        {
            //todo DevelopmentCard?
            if (command != GameCommand.RollDice)
                return;

            Completed = true;
            if (dice.Current.Result == 7)
                turn.SetState<RobberDiscardState>();
            else
                turn.NextFlowState();
        }
示例#12
0
        public void ExpectNothingToHappenIfCommandNotRollDice(GameCommand command)
        {
            var player = new Mock<IPlayer>();
            var dice = new Mock<IDice>();
            dice.Setup(d => d.Current).Returns(new DiceRoll(new int[] { 3, 4 }));

            var turn = new HighRollTurn(player.Object, dice.Object);
            bool ended = false;
            turn.Ended += (sender, args) => { ended = true; };

            turn.AfterExecute(command);

            Assert.Equal(0, turn.Result);
            Assert.False(ended);
        }
示例#13
0
文件: TurnTest.cs 项目: Corne/VOC
        public void CanExecuteIfCurrentStateHasCommand(GameCommand command, IEnumerable<GameCommand> stateCommands, bool expected)
        {
            var player = new Mock<IPlayer>();
            var state = new Mock<ITurnState>();
            state.Setup(s => s.Commands).Returns(stateCommands);
            var provider = new Mock<IStateProvider>();
            provider.Setup(p => p.HasNext()).Returns(true);
            provider.Setup(p => p.GetNext()).Returns(state.Object);

            var turn = new Turn(player.Object, provider.Object);
            turn.NextFlowState();

            bool result = turn.CanExecute(command);

            Assert.Equal(expected, result);
        }
示例#14
0
 public override void ExecuteCommand(GameCommand command) {
     if(command == GameCommand.None) {
         if(cargo.Count > 0) {
             StartDelivery();
         } else if(!atHub) {
             ReceiveCommand(new CommandPacket {
                 command = GameCommand.Return,
                 dataVector = hubStation.position,
                 dataString = hubStation.name
             });
         }
     } else {
         shipController.SetDestination(destinationTarget);
         distTicks++;
     }
 }
示例#15
0
        public void AfterExecute(GameCommand command)
        {
            if (command != GameCommand.DiscardResources)
                return;

            var removeList = new List<IPlayer>();
            foreach (var player in desiredInventorySizes)
            {
                if (player.Key.Inventory.Count() <= player.Value)
                    removeList.Add(player.Key);
            }
            foreach (var player in removeList)
            {
                desiredInventorySizes.Remove(player);
            }
            CheckStateChange();
        }
示例#16
0
文件: BuildTurn.cs 项目: Corne/VOC
        public void AfterExecute(GameCommand command)
        {
            lock (buildLock)
            {
                if (!CanExecute(command)) return;

                switch (command)
                {
                    case GameCommand.BuildEstablisment:
                        expectedCommand = GameCommand.BuildRoad;
                        break;
                    case GameCommand.BuildRoad:
                        expectedCommand = GameCommand.NextState;
                        Ended?.Invoke(this, EventArgs.Empty);
                        break;
                }
            }
        }
示例#17
0
        public async Task SendAsync_IGameCommand_EventGameDataSentIsInvoked()
        {
            var diceConnectionMock = new Mock<DiceConnection>();
            var diceConnection = diceConnectionMock.Object;
            diceConnectionMock.Setup(mock => mock.SendAsync(It.IsAny<IDicePacket>())).ReturnsAsync(123);

            var isCalled = false;
            var instance = new GameConnection(diceConnection);
            instance.GameDataSent +=
                (sender, e) =>
                {
                    isCalled = true;
                };

            var gameCommand = new GameCommand() { Command="myCommand"};
            await instance.SendAsync(gameCommand);

            Assert.True(isCalled);
        }
示例#18
0
        private IEnumerator CheckBombPlacement()
        {
            ObstaclesStayDetectorForced detector = BombGO.GetComponentInChildren <ObstaclesStayDetectorForced>();

            detector.ReCheckCollisionsStart();
            yield return(WaitForFrames(2));

            detector.ReCheckCollisionsFinish();

            if (detector.OverlapsCurrentShipNow)
            {
                GameCommand command = GeneratePlaceBombCommand(BombGO.transform.position, BombGO.transform.eulerAngles);
                GameMode.CurrentGameMode.ExecuteCommand(command);
            }
            else
            {
                Messages.ShowError("The bomb must be touching ship's base");
                IsInReposition = true;
            }
        }
示例#19
0
文件: Game.cs 项目: mengtest/actdemo
    /// <summary>
    /// 定时发送游戏心跳
    /// </summary>
    private void SendGameHeartBeat()
    {
        if (m_BeatDuration == 0)
        {
            m_BeatStartTime = Time.realtimeSinceStartup;
            m_BeatDuration  = mGameRecv.GetBeatInterval();
            if (m_BeatDuration < MINDURATION)
            {
                m_BeatDuration = (uint)MINDURATION;
            }
        }

        float time = Time.realtimeSinceStartup;

        if (time - m_BeatStartTime >= m_BeatDuration)
        {
            m_BeatStartTime = time;
            GameCommand.SendCustom(CustomHeader.CLIENT_CUSTOMMSG_HEART_BEAT);
        }
    }
            public override MouseHandlingResult HandleClick()
            {
                GameCommand command = GameCommand.Create(GameCommandType.SetRallyOrder);

                command.RelatedControlGroup = this.Item;
                Engine_AIW2.Instance.DoForSelected(SelectionCommandScope.CurrentPlanet_UnlessViewingGalaxy, delegate(GameEntity selected)
                {
                    if (selected.TypeData.MetalFlows[MetalFlowPurpose.BuildingShipsInternally] == null)
                    {
                        return(DelReturn.Continue);
                    }
                    command.RelatedEntityIDs.Add(selected.PrimaryKeyID);
                    return(DelReturn.Continue);
                });
                if (command.RelatedEntityIDs.Count > 0)
                {
                    World_AIW2.Instance.QueueGameCommand(command, true);
                }
                return(MouseHandlingResult.None);
            }
示例#21
0
    public static void TryExecute(GameCommand command)
    {
        if (command.GetType() == AcceptsCommandType)
        {
            Console.Write("Command is executed: " + command.Type, LogTypes.GameCommands, true, "aqua");

            GameController.ConfirmCommand();
            command.Execute();
            CommandsReceived++;

            if (command.GetType() == typeof(SyncPlayerWithInitiativeCommand))
            {
                AcceptsCommandType = null;
            }
        }
        else
        {
            Console.Write("Command is not executed: wrong type of initialization command", LogTypes.GameCommands, true, "aqua");
        }
    }
示例#22
0
        private void ReadUserInput(out bool isQuitGame)
        {
            isQuitGame = false;
            ConsoleKey key = Console.ReadKey(true).Key;

            if (key == ConsoleKey.Escape)
            {
                isQuitGame   = true;
                _game.Paused = true;
            }
            else
            {
                GameCommand command = TranslateCommand(key);

                if (command != GameCommand.NoCommand && _onUserAction != null)
                {
                    _onUserAction(this, new UserEventArgs(command));
                }
            }
        }
示例#23
0
        public ActionResult Delete(
            Guid id,
            [FromBody] GameCommand gameCommand
            )
        {
            try
            {
                if (gameCommand == null || id != gameCommand.Id)
                {
                    return(NotFound());
                }

                _applicationGameService.Remove(gameCommand);
                return(Ok("Partida deletada com sucesso!"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#24
0
        public override async Task DoAction(GameCommand command)
        {
            var commandItem = command.GetCommandIndex(0);

            if (commandItem.Command.Equals("next"))
            {
                var list = new List <IPlayer>();
                command.GetGameInfo <GameInfo>().CanKilledList.ForEach(p => {
                    if (p.VotedPlayer != null)
                    {
                        list.Add(p.VotedPlayer);
                    }
                });
                //获取票数最多的
                var target = (from item in list group item by item into gro orderby gro.Count() descending select new { Player = gro.Key, Count = gro.Count() }).FirstOrDefault();
                if (target == null)
                {
                    await command.GameInput.ReplyGroup("竞选失败请认真投票!");

                    return;
                }
                target.Player.IsSheriff = true;
                await command.GameInput.ReplyGroup("恭喜玩家 {0}, 被选为警长, 荣获票数 : {1} ".Format(target.Player.PlayerNickName, target.Count));

                Next(command);
            }
            else if (commandItem.Command.Equals("vote"))
            {
                var     index  = Convert.ToInt32(commandItem.Contents.First());
                IPlayer player = command.GetGameInfo <GameInfo>().GetPlayer(index);
                IPlayer self   = command.GetGameInfo <GameInfo>().GetPlayerById(command.GameInput.Sender.Id);
                if (self == null)
                {
                    await command.GameInput.ReplyTemp("您没有参与游戏,或则您已经出局!");

                    return;
                }
                self.VotedPlayer = player;
                await command.GameInput.ReplyGroup("玩家 : {0} -> {1}".Format(self.PlayerNickName, player == null ? "" : player.PlayerNickName));
            }
        }
示例#25
0
        /// <summary>
        /// Called when a command needs to be handled
        /// </summary>
        /// <param name="client">Client executing the command</param>
        /// <param name="cmdLine">Args for the command</param>
        /// <returns>True if succeeded</returns>
        public static bool HandleCommand(GameClient client, string cmdLine)
        {
            try
            {
                // parse args
                string[]    pars      = ParseCmdLine(cmdLine);
                GameCommand myCommand = GuessCommand(pars[0]);

                //If there is no such command, return false
                if (myCommand == null)
                {
                    return(false);
                }

                if (client.Account.PrivLevel < myCommand.m_lvl)
                {
                    if (!SinglePermission.HasPermission(client.Player, pars[0].Substring(1, pars[0].Length - 1)))
                    {
                        if (pars[0][0] == '&')
                        {
                            pars[0] = '/' + pars[0].Remove(0, 1);
                        }
                        //client.Out.SendMessage("You do not have enough priveleges to use " + pars[0], eChatType.CT_Important, eChatLoc.CL_SystemWindow);
                        //why should a player know the existing commands..
                        client.Out.SendMessage("No such command (" + pars[0] + ")", eChatType.CT_System, eChatLoc.CL_SystemWindow);
                        return(true);
                    }
                    //else execute the command
                }

                ExecuteCommand(client, myCommand, pars);
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("HandleCommand", e);
                }
            }
            return(true);
        }
示例#26
0
        private bool TryToPlaceObstacle()
        {
            if (IsEnteredPlacementZone && !IsPlacementBlocked && !IsLocked)
            {
                IsLocked = true;

                GameCommand command = GeneratePlaceObstacleCommand(
                    ChosenObstacle.Name,
                    ChosenObstacle.ObstacleGO.transform.position,
                    ChosenObstacle.ObstacleGO.transform.eulerAngles
                    );
                GameMode.CurrentGameMode.ExecuteCommand(command);
                return(true);
            }
            else
            {
                Messages.ShowError("The obstacle cannot be placed");
                IsLocked = false;
                return(false);
            }
        }
        private void ExtraAttackTargetSelected()
        {
            var subphase = Phases.StartTemporarySubPhaseNew(
                "Extra Attack",
                typeof(ExtraAttackSubPhase),
                delegate {
                Phases.FinishSubPhase(typeof(ExtraAttackSubPhase));
                Phases.FinishSubPhase(typeof(SelectTargetForSecondAttackSubPhase));
                CallBack();
            }
                );

            subphase.Start();

            GameCommand command = Combat.GenerateIntentToAttackCommand(Selection.ThisShip.ShipId, Selection.AnotherShip.ShipId);

            if (command != null)
            {
                GameMode.CurrentGameMode.ExecuteCommand(command);
            }
        }
    public static void CreateDiceModificationsButton(GenericAction actionEffect, Vector3 position)
    {
        GameObject prefab    = (GameObject)Resources.Load("Prefabs/GenericButton", typeof(GameObject));
        GameObject newButton = MonoBehaviour.Instantiate(prefab, GameObject.Find("UI/CombatDiceResultsPanel").transform.Find("DiceModificationsPanel"));

        newButton.GetComponent <RectTransform>().localPosition = position;

        newButton.name = "Button" + actionEffect.DiceModificationName;
        newButton.transform.GetComponentInChildren <Text>().text = actionEffect.DiceModificationName;

        newButton.GetComponent <Button>().onClick.AddListener(
            delegate {
            GameCommand command = DiceModificationsManager.GenerateDiceModificationCommand(actionEffect.DiceModificationName);
            GameMode.CurrentGameMode.ExecuteCommand(command);
        }
            );
        Tooltips.AddTooltip(newButton, actionEffect.ImageUrl);

        newButton.GetComponent <Button>().interactable = true;
        newButton.SetActive(ShowOnlyForHuman());
    }
        public override async Task DoAction(GameCommand command)
        {
            var commandItem = command.GetCommandIndex(0);

            if (commandItem.Command.Equals("move"))
            {
                var     index  = Convert.ToInt32(commandItem.Contents.First());
                IPlayer target = command.GetGameInfo <GameInfo>().GetPlayer(index);
                if (target == null && command.GetGameInfo <GameInfo>().GetAllKilledPlayer().Contains(target))
                {
                    await command.GameInput.ReplyGroup("请输入正确的移交对象!");

                    return;
                }
                else
                {
                    target.IsSheriff = true;
                    Next(command);
                }
            }
        }
示例#30
0
        protected override void Func_StartHost(Host host, GameCommand command)
        {
            Debug.Log("STARTING CLIENT FROM NETWORK THREAD");
            try
            {
                Address addy = new Address
                {
                    Port = command.Port
                };
                addy.SetHost(command.Host);

                host.Create();
                m_peer = host.Connect(addy, command.ChannelCount);
                MyPeer = m_peer;
                Debug.Log($"Client started on port: {command.Port} with {command.ChannelCount} channels.");
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
        }
示例#31
0
        public override async Task DoAction(GameCommand command)
        {
            var witcher = command.GetGameInfo <GameInfo>().GetPlayerByIdentity(IdentityType.Witcher).FirstOrDefault() as Witcher;

            if (!CheckIdentity(command))
            {
                await command.GameInput.ReplyTemp("只有女巫才可以操作!");

                return;
            }
            if (command.Commands.Where(p => p.Command.Equals("empty")).Count() > 0)
            {
                Next(command);
                return;
            }

            foreach (var item in command.Commands)
            {
                //救人命令
                if (item.Command.Equals("save") && witcher.Antidote > 0)
                {
                    witcher.Antidote--;
                    command.GetGameInfo <GameInfo>().WolferWillKilled = null;
                    await command.GameInput.ReplyTemp("成功救下!");
                }
                else if (item.Command.Equals("poison") && witcher.Poison > 0)
                {
                    int index = Convert.ToInt32(item.Contents.First());
                    //获取期望毒杀的目标
                    var player = command.GetGameInfo <GameInfo>().GetPlayer(index);
                    if (player != null)
                    {
                        command.GetGameInfo <GameInfo>().PoisonKilled = player;
                        witcher.Poison--;
                    }
                }
            }

            Next(command);
        }
示例#32
0
        /// <summary>
        /// 狼人杀人阶段
        /// </summary>
        /// <param name="command"></param>
        public override async Task DoAction(GameCommand command)
        {
            var wolfers = command.GetGameInfo <GameInfo>().GetWolfers(true);

            var commandItem = command.GetCommandIndex(0);

            IPlayer self = command.GetGameInfo <GameInfo>().GetPlayerById(command.GameInput.Sender.Id);

            if (!CheckIdentity(command))
            {
                await command.GameInput.ReplyTemp("只有狼人才能操作!");

                return;
            }
            if (commandItem.Command.Equals("kill"))
            {
                int     index  = Convert.ToInt32(commandItem.Contents.FirstOrDefault());
                IPlayer player = command.GetGameInfo <GameInfo>().GetPlayer(index);
                (self as Wolfer).SetTarget(player);
                if (player != null)
                {
                    await command.GameInput.ReplyTemp("您投票 -> {0} 玩家成功!".Format(player.PlayerNickName));
                }
            }
            if (commandItem.Command.Equals("next") || wolfers.Where(p => (p as Wolfer).IsOptioned == false).Count() == 0)
            {
                var list = new List <IPlayer>();
                wolfers.ForEach(p =>
                {
                    if ((p as Wolfer).KillTargetPlayer != null)
                    {
                        list.Add((p as Wolfer).KillTargetPlayer);
                    }
                });
                ///如果狼人操作完成
                command.GetGameInfo <GameInfo>().WolferWillKilled = (from item in list group item by item into gro orderby gro.Count() descending select gro.Key).FirstOrDefault();
                wolfers.ForEach(p => (p as Wolfer).Reset());
                Next(command);
            }
        }
示例#33
0
        public void Setup(string ServerName, bool LoadConfig = false)
        {
            _servername      = ServerName;
            sGameCommand     = new GameCommand(ServerName);
            sGameCommand.sGC = sGameCommand;
            sIrcBase.Networks[ServerName].IrcRegisterHandler("PRIVMSG", HandlePrivmsg);
            sIrcBase.Networks[ServerName].IrcRegisterHandler("PART", HandleLeft);
            sIrcBase.Networks[ServerName].IrcRegisterHandler("KICK", HandleKick);
            sIrcBase.Networks[ServerName].IrcRegisterHandler("QUIT", HandleQuit);
            sIrcBase.Networks[ServerName].IrcRegisterHandler("NICK", HandleNewNick);
            sIrcBase.Networks[ServerName].IrcRegisterHandler("MODE", HandleMode);
            InitIrcCommand();
            SchumixBase.DManager.Update("maffiagame", string.Format("ServerName = '{0}'", ServerName), string.Format("ServerId = '{0}'", IRCConfig.List[ServerName].ServerId));

            if (CleanConfig.Database)
            {
                SchumixBase.sCleanManager.CDatabase.CleanTable("maffiagame");
            }

            Console.CancelKeyPress += (sender, e) => { Clean(); };
            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => { Clean(); };
        }
示例#34
0
 public static void UpdatePosition(Figure figure, GameField field, ref bool runGame)
 {
     KeyboardControls keyboard = new KeyboardControls();
     keyboard.OnLeftPressed += HandleOnLeftPressed;
     keyboard.OnRightPressed += HandleOnRightPressed;
     keyboard.OnRotatePressed += HandleOnRotatePressed;
     keyboard.OnEscapePressed += HandleOnEscapePressed;
     keyboard.ProcessInput();
     switch (command)
     {
         case GameCommand.none:
             break;
         case GameCommand.left:
             if (figure.PositionY > 0)
             {
                 figure.MoveLeft();
             }
             break;
         case GameCommand.right:
             if (figure.PositionY + figure.Form.GetLength(1) < field.Field.GetLength(1))
             {
                 figure.MoveRight();
             }
             break;
         case GameCommand.rotate:
             if ((figure.PositionX + figure.Form.GetLength(1) - 1 < field.Field.GetLength(0))
              && (figure.PositionY + figure.Form.GetLength(0) - 1 < field.Field.GetLength(1)))
             {
                 figure.RotateR();
             }
             break;
         case GameCommand.escape:
             runGame = false;
             break;
         default:
             break;
     }
     command = GameCommand.none;
 }
示例#35
0
        private static void ExecuteCommand(GameCommand command, ref Game g, GameView view)
        {
            switch (command)
            {
            case GameCommand.MoveLeft:
                TryMoveShape(ref g, view, -1, 0);
                break;

            case GameCommand.MoveRight:
                TryMoveShape(ref g, view, 1, 0);
                break;

            case GameCommand.MoveDown:
                TryMoveShape(ref g, view, 0, 1);
                break;

            case GameCommand.Land:
                while (TryMoveShape(ref g, view, 0, 1))
                {
                    System.Threading.Thread.Sleep(GAME_QUANTUM);
                }
                break;

            case GameCommand.Rotate:
                Shape rotated = BL.RotateShape(g.CurrentShape);
                if (BL.IsPositionPossible(g.Field, rotated))
                {
                    Point2D[] makeEmpty;
                    Point2D[] makeFilled;

                    BL.CalcChangedPoints(g.CurrentShape, rotated, out makeEmpty, out makeFilled);
                    g.CurrentShape = rotated;
                    UI.DrawPoints(makeEmpty, ShapeKind.Empty, view);
                    UI.DrawPoints(makeFilled, g.CurrentShape.Kind, view);
                }
                break;
            }
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public async override Task Init(GameCommand command)
        {
            if (StepMessage != null)
            {
                await command.GameInput.ReplyGroup(StepMessage);
            }
            //针对组
            var msg = GetInitMessage(command);

            if (msg != null)
            {
                await command.GameInput.ReplyGroup(GetInitMessage(command));
            }

            if (IsEmpty(command))
            {
                await command.Empty(NextState);
            }
            else
            {
                command.IsRunNextState = false;
            }
        }
示例#37
0
        public override async Task DoAction(GameCommand command)
        {
            if (!CheckIdentity(command))
            {
                await command.GameInput.ReplyTemp("只有预言家才可以操作!");

                return;
            }
            var commandItem = command.GetCommandIndex(0);

            if (commandItem.Command.Equals("check"))
            {
                int     index  = Convert.ToInt32(commandItem.Contents.First());
                IPlayer player = command.GetGameInfo <GameInfo>().GetPlayer(index);
                await command.GameInput.ReplyTemp("这个人的身份是 : {0}".Format(player.Identity == IdentityType.Wolfer ? "狼" : "好"));

                Next(command);
            }
            else
            {
                await command.GameInput.ReplyTemp("命令错误!");
            }
        }
            public override MouseHandlingResult HandleClick()
            {
                //debug = true;
                if (iCampaignName.Instance.CampaignName.Trim().Length <= 0)
                {
                    iCampaignName.Instance.CampaignName = World_AIW2.Instance.Setup.MapType.InternalName + "." + World_AIW2.Instance.Setup.Seed;
                }
                Window_SaveGameMenu.Instance.OverallCampaignName = iCampaignName.Instance.CampaignName;
                GameCommand command = GameCommand.Create(GameCommandType.SaveGame);
                //generate the saveGame entry from the name and state of the game
                DateTime dt = DateTime.Now;
                //Generate a SaveGameData from the saveGame and campaignName boxes,
                //along with game metadata
                SaveGameData data = new SaveGameData(iSaveGameName.Instance.SaveName, World_AIW2.Instance.Setup.Seed,
                                                     World_AIW2.Instance.GameSecond, iCampaignName.Instance.CampaignName,
                                                     dt, World_AIW2.Instance.Setup.MasterAIType.Name, World_AIW2.Instance.Setup.Difficulty.Name);

                data.setShortMapType(World_AIW2.Instance.Setup.MapType.InternalName);
                command.RelatedString = data.ToString();
                command.RelatedBool   = true; // tells it to quit after completing the save
                World_AIW2.Instance.QueueGameCommand(command, true);
                return(MouseHandlingResult.None);
            }
示例#39
0
        private void button1_Click(object sender, EventArgs e)
        {
            string computerKey = txtComputerKey.Text;
            string baseUrl     = txtUrl.Text;

            SetConfigValue("ComputerKey", computerKey);
            SetConfigValue("BaseURL", baseUrl);
            // go get that secret key
            GameCommand gc = new GameCommand();

            Dictionary <string, string> data = new Dictionary <string, string>()
            {
                { "computer_key", computerKey },
                { "current_time", DateTime.Now.ToString() }
            };

            dynamic obj = gc.GetWebResponse($"{baseUrl}/computers/getSecret", data);

            if (obj.status == "ok")
            {
                SetConfigValue("Secret", obj.secret);
            }
        }
示例#40
0
    public bool IsOnlyActionPressed(GameCommand action)
    {
        if (!IsActionPressed(action))
        {
            return(false);
        }
        var pressed = true;

        foreach (GameCommand command in Enum.GetValues(typeof(GameCommand)))
        {
            if (command == action)
            {
                continue;
            }
            if (IsActionPressed(command))
            {
                pressed = false;
                break;
            }
        }

        return(pressed);
    }
示例#41
0
文件: Game.cs 项目: mengtest/actdemo
    void Update()
    {
        if (!mbNetInit || mClientNet == null)
        {
            return;
        }

        iTick++;
        if (iTick % 2 == 0)
        {
            mClientNet.Excutue();
        }

        if (Input.GetKeyDown(KeyCode.F))
        {
            GameCommand.SendCustom((CustomHeader)141, 0, 3, 1);
        }

//         if (ObjectManager.mRole != null && !WorldStage.mbReConnected)
//         {
//             SendGameHeartBeat();
//         }
    }
示例#42
0
    // SQUADRONS

    private static void PrepareSquadrons()
    {
        if (ReplaysManager.Mode == ReplaysMode.Write)
        {
            foreach (var squad in SquadBuilder.SquadLists)
            {
                JSONObject parameters = new JSONObject();
                parameters.AddField("player", squad.PlayerNo.ToString());
                parameters.AddField("type", squad.PlayerType.ToString());

                squad.SavedConfiguration["description"].str = squad.SavedConfiguration["description"].str.Replace("\n", "");
                parameters.AddField("list", squad.SavedConfiguration);

                GameController.SendCommand(
                    GameCommandTypes.SquadsSync,
                    null,
                    parameters.ToString()
                    );

                Console.Write("Command is executed: " + GameCommandTypes.SquadsSync, LogTypes.GameCommands, true, "aqua");
                GameController.GetCommand().Execute();
            }
            ;
        }
        else if (ReplaysManager.Mode == ReplaysMode.Read)
        {
            for (int i = 0; i < 2; i++)
            {
                GameCommand command = GameController.GetCommand();
                if (command.Type == GameCommandTypes.SquadsSync)
                {
                    Console.Write("Command is executed: " + command.Type, LogTypes.GameCommands, true, "aqua");
                    command.Execute();
                }
            }
        }
    }
示例#43
0
 internal void pictureBoxBoard_MouseClick(object sender, MouseEventArgs e)
 {
     if (isActive)
     {
         int[] IndexesOfClikedCell = ConvertCoordinatesToBoardIndexes(e.X, e.Y);
         if (chosenCell[0] != -1)
         {
             List <int[]> posibleMovesForChosenCell = board[chosenCell[0], chosenCell[1]].PosibleMoves(chosenCell, board);
             if (posibleMovesForChosenCell.Exists(delegate(int[] move) { return(move[0] == IndexesOfClikedCell[0] && move[1] == IndexesOfClikedCell[1]); }))
             {
                 int[] posibleMove = new int[] { IndexesOfClikedCell[0], IndexesOfClikedCell[1], board[IndexesOfClikedCell[0], IndexesOfClikedCell[1]].GetIdentifer() };
                 IFigure[,] boardAfterMove = MakeMove(board, posibleMove);
                 List <int[]> enemyPosibleMovesAfterMove;
                 PosibleMovesCalculator(boardAfterMove, out enemyPosibleMovesAfterMove);
                 if (Check(boardAfterMove, enemyPosibleMovesAfterMove)[0] != -1)
                 {
                     return;
                 }
                 command  = new GameCommand(this, chosenCell, IndexesOfClikedCell, board);
                 isActive = false;
                 return;
             }
         }
         if (board[IndexesOfClikedCell[0], IndexesOfClikedCell[1]] != null && board[IndexesOfClikedCell[0], IndexesOfClikedCell[1]].GetColor() == color)
         {
             List <int[]> posibleMovesForThisCell = board[IndexesOfClikedCell[0], IndexesOfClikedCell[1]].PosibleMoves(IndexesOfClikedCell, board);
             RemoveCheckMoves(ref posibleMovesForThisCell);
             chosenCell = IndexesOfClikedCell;
             drawer.HighLite(posibleMovesForThisCell);
             return;
         }
         if (board[IndexesOfClikedCell[0], IndexesOfClikedCell[1]] == null)
         {
             drawer.DeHighLite();
         }
     }
 }
示例#44
0
            public override MouseHandlingResult HandleClick()
            {
                WorldSide localSide = World_AIW2.Instance.GetLocalPlayerSide();

                if (localSide == null)
                {
                    return(MouseHandlingResult.PlayClickDeniedSound);
                }
                GameEntity hacker = localSide.Entities.GetFirstMatching(EntityRollupType.KingUnits);

                if (hacker == null)
                {
                    return(MouseHandlingResult.PlayClickDeniedSound);
                }
                if (hacker.Combat != this.Target.Combat)
                {
                    return(MouseHandlingResult.PlayClickDeniedSound);
                }
                if (!this.Type.Implementation.GetCanBeHacked(this.Target, hacker))
                {
                    return(MouseHandlingResult.PlayClickDeniedSound);
                }
                if (localSide.StoredHacking < this.Type.Implementation.GetCostToHack(this.Target, hacker))
                {
                    return(MouseHandlingResult.PlayClickDeniedSound);
                }
                GameCommand command = GameCommand.Create(GameCommandType.SetActiveHack);

                command.RelatedHack = this.Type;
                command.RelatedEntityIDs.Add(hacker.PrimaryKeyID);
                command.TargetEntityIDs.Add(this.Target.PrimaryKeyID);
                if (command.RelatedEntityIDs.Count > 0)
                {
                    World_AIW2.Instance.QueueGameCommand(command, true);
                }
                return(MouseHandlingResult.None);
            }
示例#45
0
 internal void Execute(GameCommand gc)
 {
     if (gc is NewGame ng)
     {
         GameFlow.NewGame(ng.UIPlayerColor);
     }
     else if (gc is LoadGame lc)
     {
         var(h, c) = Storage.Load(lc.Name);
         GameFlow.StartFrom(h, c);
     }
     else if (gc is ListGames)
     {
         Console.WriteLine("Saved games:");
         Storage.GetNames().ForEach(n => Console.WriteLine(n));
     }
     else if (gc is SaveGame sc)
     {
         var history = GameFlow.History;
         if (history == null)
         {
             Console.WriteLine("Nothing to save yet");
         }
         else
         {
             Storage.Save(sc.Name, history, GameFlow.PlayerAColor !.Value);
         }
     }
     else if (gc is DeleteGame dc)
     {
         Storage.Delete(dc.Name);
     }
     else
     {
         throw new ArgumentOutOfRangeException(nameof(gc));
     }
 }
示例#46
0
        /// <summary>
        /// Reacts to file change and process it. Changes can be 2 types: Field data edited, or last bot command (added/edited).
        /// If lastLine stays the same -> we update our field
        /// Else we update last command
        /// </summary>
        /// <param name="sender">Request sender</param>
        /// <param name="e"> EventArgs for this kind of event. </param>
        private void FsWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("BOT_FILE_WATCHER file edited");
            if (e.FullPath != watchingFilePath)
            {
                return;
            }

            string fileContent;

            using (FileStream fs = new FileStream(watchingFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                StreamReader sr = new StreamReader(fs);
                fileContent = sr.ReadToEnd();
            }

            string[] lines = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            if (lastLine.Equals(lines.Last()))
            {
                using (MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(fileContent)))
                {
                    field = BotJournalFileHelper.ReadFieldFromStream(ms);
                }
                Console.WriteLine("field edited");
                FieldEdited?.Invoke(this, new FieldChangedEventArgs(this.field, field));
            }
            else
            {
                GameCommand command = BotJournalFileHelper.ParseGameCommand(lines.Last());

                Console.WriteLine("command edited");
                CommandEdited?.Invoke(this, new CommandChangedEventArgs(this.command, command));
                this.command = command;
                lastLine     = lines.Last();
            }
        }
示例#47
0
    public static bool ShouldBeRecorded(GameCommand command)
    {
        if (DebugManager.NoReplayCreation)
        {
            return(false);
        }

        bool result = true;

        switch (command.Type)
        {
        case GameCommandTypes.PressSkip:
            if (command.SubPhase == typeof(SubPhases.ObstaclesPlacementSubPhase))
            {
                result = false;
            }
            break;

        default:
            break;
        }

        return(result);
    }
示例#48
0
        public virtual void SyncDiceRerollSelected()
        {
            JSONObject[] diceRerollSelectedArray = new JSONObject[DiceRoll.CurrentDiceRoll.DiceList.Count];
            for (int i = 0; i < DiceRoll.CurrentDiceRoll.DiceList.Count; i++)
            {
                bool       isSelected     = DiceRoll.CurrentDiceRoll.DiceList[i].IsSelected;
                string     isSelectedText = isSelected.ToString();
                JSONObject isSelectedJson = new JSONObject();
                isSelectedJson.AddField("selected", isSelectedText);
                diceRerollSelectedArray[i] = isSelectedJson;
            }
            JSONObject diceRerollSelected = new JSONObject(diceRerollSelectedArray);
            JSONObject parameters         = new JSONObject();

            parameters.AddField("dice", diceRerollSelected);

            GameCommand command = GameController.GenerateGameCommand(
                GameCommandTypes.SyncDiceRerollSelected,
                Phases.CurrentSubPhase.GetType(),
                parameters.ToString()
                );

            GameMode.CurrentGameMode.ExecuteCommand(command);
        }
示例#49
0
 public KeyDownEventArgs(GameCommand command)
 {
     this.Command = command;
 }
示例#50
0
文件: ScriptMgr.cs 项目: mynew4/DAoC
		/// <summary>
		/// Checks for 'help' param and executes command
		/// </summary>
		/// <param name="client">Client executing the command</param>
		/// <param name="myCommand">command to be executed</param>
		/// <param name="pars">Args for the command</param>
		/// <returns>Command result</returns>
		private static void ExecuteCommand(GameClient client, GameCommand myCommand, string[] pars)
		{
			// what you type in script is what you get; needed for overloaded scripts,
			// like emotes, to handle case insensitive and guessed commands correctly
			pars[0] = myCommand.m_cmd;

			//Log the command usage
			if (client.Account == null || ((ServerProperties.Properties.LOG_ALL_GM_COMMANDS && client.Account.PrivLevel > 1) || myCommand.m_lvl > 1))
			{
				string commandText = String.Join(" ", pars);
				string targetName = "(no target)";
				string playerName = (client.Player == null) ? "(player is null)" : client.Player.Name;
				string accountName = (client.Account == null) ? "account is null" : client.Account.Name;

				if (client.Player == null)
				{
					targetName = "(player is null)";
				}
				else if (client.Player.TargetObject != null)
				{
					targetName = client.Player.TargetObject.Name;
					if (client.Player.TargetObject is GamePlayer)
						targetName += "(" + ((GamePlayer)client.Player.TargetObject).Client.Account.Name + ")";
				}
				GameServer.Instance.LogGMAction("Command: " + playerName + "(" + accountName + ") -> " + targetName + " - \"/" + commandText.Remove(0, 1) + "\"");

			}
			if (client.Player != null)
			{
				client.Player.Notify(DOL.Events.GamePlayerEvent.ExecuteCommand, new ExecuteCommandEventArgs(client.Player, myCommand, pars));
			}
			myCommand.m_cmdHandler.OnCommand(client, pars);
		}
示例#51
0
文件: ScriptMgr.cs 项目: mynew4/DAoC
		/// <summary>
		/// Searches the script assembly for all command handlers
		/// </summary>
		/// <returns>True if succeeded</returns>
		public static bool LoadCommands(bool quiet = false)
		{
			m_gameCommands.Clear();

			ArrayList asms = new ArrayList(Scripts);
			asms.Add(typeof(GameServer).Assembly);

			//build array of disabled commands
			string[] disabledarray = ServerProperties.Properties.DISABLED_COMMANDS.Split(';');

			foreach (Assembly script in asms)
			{
				if (log.IsDebugEnabled)
					log.Debug("ScriptMgr: Searching for commands in " + script.GetName());
				// Walk through each type in the assembly
				foreach (Type type in script.GetTypes())
				{
					// Pick up a class
					if (type.IsClass != true) continue;
					if (type.GetInterface("DOL.GS.Commands.ICommandHandler") == null) continue;

					try
					{
						object[] objs = type.GetCustomAttributes(typeof(CmdAttribute), false);
						foreach (CmdAttribute attrib in objs)
						{
							bool disabled = false;
							foreach (string str in disabledarray)
							{
								if (attrib.Cmd.Replace('&', '/') == str)
								{
									disabled = true;
									log.Info("Will not load command " + attrib.Cmd + " as it is disabled in server properties");
									break;
								}
							}

							if (disabled)
								continue;

							if (m_gameCommands.ContainsKey(attrib.Cmd))
							{
								log.Info(attrib.Cmd + " from " + script.GetName() + " has been suppressed, a command of that type already exists!");
								continue;
							}
							if (log.IsDebugEnabled && quiet == false)
								log.Debug("ScriptMgr: Command - '" + attrib.Cmd + "' - (" + attrib.Description + ") required plvl:" + attrib.Level);

							GameCommand cmd = new GameCommand();
							cmd.Usage = attrib.Usage;
							cmd.m_cmd = attrib.Cmd;
							cmd.m_lvl = attrib.Level;
							cmd.m_desc = attrib.Description;
							cmd.m_cmdHandler = (ICommandHandler)Activator.CreateInstance(type);
							m_gameCommands.Add(attrib.Cmd, cmd);
							if (attrib.Aliases != null)
							{
								foreach (string alias in attrib.Aliases)
								{
									m_gameCommands.Add(alias, cmd);
								}
							}
						}
					}
					catch (Exception e)
					{
						if (log.IsErrorEnabled)
							log.Error("LoadCommands", e);
					}
				}
			}
			log.Info("Loaded " + m_gameCommands.Count + " commands!");
			return true;
		}
示例#52
0
 private static void HandleOnRotatePressed(object s, EventArgs e)
 {
     command = GameCommand.rotate;
 }
示例#53
0
 public override void HandleCommand(GameCommand command)
 {
     base.HandleCommand(command);
     if (command is EndTurnCommand) IsSatisfied = true;
 }
    public override void ExecuteCommand(GameCommand command) {
        base.ExecuteCommand(command);

        if(currentCommand == GameCommand.Spawn) {
            var shipGo = Instantiate(spawnables[(int)(dataVector.x)]
                , spawnLocation.position, spawnables[(int)(dataVector.x)]
                .transform.rotation) as GameObject;
            var ship = shipGo.GetComponent<Ship>();
            ship.hubStation = this;
            ship.shipUI = shipUI;
            activeFleet.Add(ship);
            if(isServer) NetworkServer.Spawn(shipGo);

            if(ship.type == ShipType.Cargo)
                ship.route = cargoRoutes[0];
            else if(ship.type == ShipType.Shuttle) {
                ship.route = shuttleRoutes[0];
            } else ship.route = explorerRoutes[0];

            CompletedCommand(command);
        }
    }
示例#55
0
 public void HandleCommand(GameCommand command)
 {
     if (activeDialog != null && activeDialog is ICommandFilter)
     {
         ((ICommandFilter)activeDialog).HandleCommand(command);
     }
 }
示例#56
0
        public void ExpectNothingToHappenIfCommandNotRollDice(GameCommand command)
        {
            var dice = CreateDice(7);
            var turn = new Mock<IGameTurn>();
            var state = new RollState(turn.Object, dice);
            state.AfterExecute(command);

            turn.Verify(t => t.NextFlowState(), Times.Never);
            turn.Verify(t => t.SetState<RobberDiscardState>(), Times.Never);
        }
示例#57
0
        public void ExpectNothingToHappenIfNoStealCommand(GameCommand command)
        {
            var turn = new Mock<IGameTurn>();
            var board = CreateBoard();

            var state = new RobberStealState(turn.Object, board);

            state.AfterExecute(command);

            turn.Verify(t => t.NextFlowState(), Times.Never);
        }
示例#58
0
    public virtual void HandleCommand(GameCommand command)
    {

    }
示例#59
0
 public override void CompletedCommand(GameCommand command) {
     base.CompletedCommand(command);
     shipController.Stop();
 }
示例#60
0
 public void AfterExecute(GameCommand command)
 {
     if (command == GameCommand.StealResource)
         turn.NextFlowState();
 }