Exemplo n.º 1
0
        private static void PlayGame()
        {
            //List<SimpleComputerPlayer> players = new List<SimpleComputerPlayer>();
            var   threads = new List <Thread>();
            Table table   = new ContractTable();

            for (int i = 0; i < Table.Seats.Length - 1; i++)
            //foreach (Seat seat in Table.Seats)
            {
                //seat is not used
                //(new ConsolePlayer(Console.In, Console.Out)).JoinTable(table);
                var p = new SimpleComputerPlayer();
                p.JoinTable(table);
                threads.Add(p.Start());
            }
            var ph = new ConsolePlayer(System.Console.In, System.Console.Out);

            ph.JoinTable(table);
            table.StartSession();

            foreach (var t in threads)
            {
                t.Join();
            }
        }
 public void TestDoHitPromptsTheUserWithTheConsole()
 {
     _mockConsole.Setup(m => m.Prompt(It.IsAny<string>())).Returns("H");
     ConsolePlayer player = new ConsolePlayer("Rob", _mockConsole.Object);
     player.DoHit();
     _mockConsole.Verify(m => m.Prompt("[H]it or [S]tand"), Times.Once());
 }
        public async Task HandleEventAsync(object emitter, CommandExecutedEvent @event)
        {
            if (@event.CommandContext.Exception is CommandNotFoundException && R.Commands != null)
            {
                var text = @event.CommandContext.GetCommandLine();

                IRocketPlayer rocketPlayer = null;
                if (@event.Actor is UnturnedUser user)
                {
                    var player = user.SteamPlayer;
                    if (UnturnedPermissions.CheckPermissions(player, text))
                    {
                        rocketPlayer = UnturnedPlayer.FromSteamPlayer(player);
                    }
                }
                else if (@event.Actor.Type.Equals(KnownActorTypes.Console, StringComparison.OrdinalIgnoreCase))
                {
                    rocketPlayer = new ConsolePlayer();
                }

                if (rocketPlayer != null)
                {
                    R.Commands.Execute(rocketPlayer, text);
                    @event.CommandContext.Exception = null;
                }
            }
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            var player1 = new SimpleComputerPlayer();

            player1.Id = "1";
            var player2 = new ConsolePlayer();

            player2.Id = "2";
            var game = new CodeCompete.DotNet.TicTacToe.TicTacToe(new GamePlayer <Move>[] { player1, player2 });

            var result     = game.PlayGame();
            var finalState = result.GameMoves[result.GameMoves.Length - 1].State.Board;

            for (int i = 0; i < finalState.Length; i++)
            {
                var row = finalState[i];

                for (int j = 0; j < row.Length; j++)
                {
                    Console.Write(string.Format("{0} ", row[j]));
                }
                Console.Write(Environment.NewLine + Environment.NewLine);
            }

            if (result.Winner != null)
            {
                Console.WriteLine("Winner: " + result.Winner.Id);
            }
        }
Exemplo n.º 5
0
 static void Main(string[] args)
 {
     Console.Write("Monopoly");
     while (true)
     {
         Console.Write("\n\nPlease enter the number of players:\t");
         string strNumber = Console.ReadLine();
         int    numberOfPlayers;
         if (int.TryParse(strNumber, out numberOfPlayers) && numberOfPlayers >= 2 && numberOfPlayers <= 8)
         {
             Player[] players = new Player[numberOfPlayers];
             for (int i = 0; i < players.Length; i++)
             {
                 Console.Write("\nIs Player " + (i + 1).ToString() + " a bot player? \nY/N\t");
                 string botCheck = Console.ReadLine();
                 Console.Write("\nPlease enter Player " + (i + 1).ToString() + "'s name:\t");
                 if (botCheck == "Y")
                 {
                     players[i] = new BotPlayer(Console.ReadLine(), 5000);
                 }
                 else
                 {
                     players[i] = new ConsolePlayer(Console.ReadLine(), 5000);
                 }
             }
             Player winner = PlayGame(players);
             Console.WriteLine("\n\nPlayer " + winner.Name + "is the winner!");
             Console.WriteLine("\nThank to all of you for playing");
             Console.ReadKey();
             break;
         }
     }
 }
Exemplo n.º 6
0
        /// <summary>
        ///     Convert array to object
        /// </summary>
        /// <param name="maze">maze array</param>
        /// <returns>object list</returns>
        public static List <ConsoleBlock> ConvertMazeArrayToObject(int[,] maze, ref ConsolePlayer player, ref ConsoleExitDoor exitDoor)
        {
            List <ConsoleBlock> units = new List <ConsoleBlock>();

            for (int i = 0; i < maze.GetLength(0); i++)
            {
                for (int j = 0; j < maze.GetLength(1); j++)
                {
                    Position position = new Position(i, j);
                    switch (maze[i, j])
                    {
                    case -1:
                        exitDoor = new ConsoleExitDoor(position);
                        break;

                    case 1:
                        units.Add(new ConsoleBlock(position));
                        break;

                    case 2:
                        player = new ConsolePlayer(position);
                        break;
                    }
                }
            }

            return(units);
        }
Exemplo n.º 7
0
        public Task HandleEventAsync(object emitter, CommandExecutedEvent @event)
        {
            async UniTask Task()
            {
                // RocketMod commands must run on main thread
                await UniTask.SwitchToMainThread();

                if (@event.CommandContext.Exception is CommandNotFoundException && R.Commands != null)
                {
                    var text = @event.CommandContext.GetCommandLine();

                    IRocketPlayer rocketPlayer = null;
                    if (@event.Actor is UnturnedUser user)
                    {
                        var player = user.SteamPlayer;
                        if (UnturnedPermissions.CheckPermissions(player, text))
                        {
                            rocketPlayer = UnturnedPlayer.FromSteamPlayer(player);
                        }
                    }
                    else if (@event.Actor.Type.Equals(KnownActorTypes.Console, StringComparison.OrdinalIgnoreCase))
                    {
                        rocketPlayer = new ConsolePlayer();
                    }

                    if (rocketPlayer != null)
                    {
                        R.Commands.Execute(rocketPlayer, text);
                        @event.CommandContext.Exception = null;
                    }
                }
            }

            return(Task().AsTask());
        }
Exemplo n.º 8
0
        public void StartGame()
        {
            AIPlayer         firstPlayer;
            ConsolePlayer    secondPlayer = new ConsolePlayer(gameProcessor);
            Tuple <int, int> blackHole    = GetBlackHole();

            PointState color = GetColor();

            if (color == PointState.White)
            {
                firstPlayer = new AIPlayer(gameProcessor, false);
                gameProcessor.StartGame(blackHole, secondPlayer.MakeMove());
            }
            else
            {
                firstPlayer = new AIPlayer(gameProcessor, true);
                gameProcessor.StartGame(blackHole);
            }

            //game loop
            while (true)
            {
                firstPlayer.MakeMove();
                secondPlayer.MakeMove();
            }
        }
Exemplo n.º 9
0
 //TODO: Remove duplicate code
 private void Drow(ConsolePlayer player)
 {
     Console.ForegroundColor = player.Color;
     Console.SetCursorPosition(player.Position.CoordinateX, player.Position.CoordinateY);
     Console.WriteLine("X");
     Console.ForegroundColor = defaultColor;
 }
Exemplo n.º 10
0
        public Task HandleEventAsync(object emitter, CommandExecutedEvent @event)
        {
            async UniTask Task()
            {
                // RocketMod commands must run on main thread
                await UniTask.SwitchToMainThread();

                if (@event.CommandContext.Exception is CommandNotFoundException && R.Commands != null)
                {
                    IRocketPlayer rocketPlayer;
                    if (@event.Actor is UnturnedUser user)
                    {
                        var steamPlayer = user.SteamPlayer;
                        if (!UnturnedPermissions.CheckPermissions(steamPlayer, $"/{@event.CommandContext.CommandAlias}"))
                        {
                            // command doesnt exist or no permission
                            return;
                        }

                        rocketPlayer = UnturnedPlayer.FromSteamPlayer(steamPlayer);
                    }
                    else if (@event.Actor.Type.Equals(KnownActorTypes.Console, StringComparison.OrdinalIgnoreCase))
                    {
                        rocketPlayer = new ConsolePlayer();

                        var command = R.Commands.GetCommand(@event.CommandContext.CommandAlias.ToLower(CultureInfo.InvariantCulture));
                        if (command == null)
                        {
                            return;
                        }
                    }
                    else
                    {
                        // unsupported user
                        return;
                    }

                    if (string.IsNullOrEmpty(@event.CommandContext.CommandAlias))
                    {
                        Console.WriteLine("command alias is null or empty");
                        return;
                    }

                    var args = new List <string> {
                        @event.CommandContext.CommandAlias
                    };
                    args.AddRange(@event.CommandContext.Parameters);

                    R.Commands.Execute(rocketPlayer, args.ToArray());
                    @event.ExceptionHandled = true;
                }
            }

            return(Task().AsTask());
        }
Exemplo n.º 11
0
        private static bool Handle(string input)
        {
            //check if it is a command
            if (input.StartsWith("/"))
            {
                ICommand cmd = null;

                string[] commandSplit = input.Remove(0, 1).Split(' ');
                string[] args         = commandSplit.Where((val, index) => index != 0).ToArray();
                cmd = Command.Find(commandSplit[0]);

                if (cmd == null)
                {
                    WriteLine("Command not found!");
                    return(false); // cannot run the command
                }
                if (cp == null)
                {
                    cp = new ConsolePlayer(cio);
                }
                try {
                    cmd.Use(cp, args);
                }
                catch (Exception e) { Logger.LogError(e); Logger.Log("Command aborted"); }
                Logger.Log("CONSOLE used: /" + commandSplit[0]);
            }
            else if (input.ToLower() == "!stop")
            {
                Console.Write("Would you like to save all? [y/n]:");
                if (Console.ReadLine().ToLower().StartsWith("y"))
                {
                    Server.SaveAll();
                    Server.Stop();
                }
                else
                {
                    Server.Stop();
                }
                return(true);
            }
            else if (input.ToLower() == "!copyurl")
            {
                System.Windows.Forms.Clipboard.SetDataObject(Server.URL, true);
            }
            else
            {
                Player.UniversalChat(Colors.white + "[Console] " + Server.DefaultColor + input);
                Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 1);
                Logger.Log("[Console] " + input, Color.Yellow, Color.Black, LogType.Normal);
            }
            return(false);
        }
Exemplo n.º 12
0
 private static void UpdatePosition(ConsolePlayer player)
 {
     UpdateLastPosition(player);
     player.Move(key);
     if (CheckPosition.HasPlayerReachedWall(player))
     {
         ResetPosition(player);
     }
     else
     {
         State.PlayerNeedsRedraw = true;
     }
 }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            ConsolePlayer consolePlayer = new ConsolePlayer("あなた");
            CpuPlayer     cpuPlayer     = new CpuPlayer("CPU");

            Referee referee = new Referee();

            while (true)
            {
                referee.Judge(consolePlayer, cpuPlayer);
                Console.WriteLine("\n\n---------------------------------------------\n\n");
            }
        }
Exemplo n.º 14
0
        public void ShouldReturnDirection_WhenValidUserInputReceived(string userInput, Direction direction)
        {
            var io = new Mock <IInputOutput>();

            io.Setup(x => x.Input())
            .Returns(userInput);
            var player        = new ConsolePlayer(io.Object);
            var listOfOptions = new List <Direction>
            {
                Direction.North, Direction.South, Direction.East, Direction.West
            };
            var result = player.DecideNextMove(listOfOptions);

            Assert.Equal(direction, result);
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            Do(() =>
            {
                Out("Welcome to Cross And Circle game....");
                Out("Select player. Type X or O:");
                var id     = GetPlayerId();
                var player = new ConsolePlayer(id, mre);
                var game   = GameFactory.CreateGameWithBot(player, player);
                Out("Game started");
                game.Start();
            });

            mre.WaitOne();
        }
Exemplo n.º 16
0
        public void ShouldAdviseUser_WhenInvalidInputReceived(string userInput, string errorMessage)
        {
            var io = new Mock <IInputOutput>();

            io.SetupSequence(x => x.Input())
            .Returns(userInput)
            .Returns("s");
            var player        = new ConsolePlayer(io.Object);
            var listOfOptions = new List <Direction>
            {
                Direction.North, Direction.South, Direction.East
            };
            var result = player.DecideNextMove(listOfOptions);

            Assert.Equal(Direction.South, result);
            io.Verify(x => x.Output(errorMessage), Times.Exactly(1));
        }
Exemplo n.º 17
0
        public void ShouldReturnAvailableDirection()
        {
            var io = new Mock <IInputOutput>();

            io.SetupSequence(x => x.Input())
            .Returns("a")
            .Returns("s");
            var player        = new ConsolePlayer(io.Object);
            var listOfOptions = new List <Direction>
            {
                Direction.North, Direction.South, Direction.East
            };
            var result = player.DecideNextMove(listOfOptions);

            Assert.Equal(Direction.South, result);
            io.Verify(x => x.Input(), Times.Exactly(2));
            io.Verify(x => x.Output("Option not available; choose again."), Times.Exactly(1));
        }
Exemplo n.º 18
0
        public void LooseGame()
        {
            // Arrange
            var          secret        = new int[] { 3, 2, 3, 0 };
            const string secretText    = "3 2 3 0";
            var          console       = new ConsoleMock("1234" + "7654" + "2345" + "5241" + "2634" + "5273" + "5132" + "6352" + "4172" + "6352");
            var          consolePlayer = new ConsolePlayer(console);
            var          game          = new Game(8, 4, 10, secret);

            // Act
            var result = game.Play(consolePlayer);

            // Assert
            Assert.False(result.WasTheSecretGuessed);
            Assert.DoesNotContain(WinText, console.Output);
            Assert.Contains(LoseText, console.Output);
            Assert.Contains(secretText, console.Output);
        }
Exemplo n.º 19
0
        public void IgnoreKeysThatDoesNotMapToPegs()
        {
            // Arrange
            const string Input = "\t192d3\r4 5";
            var          expectedPegNumbers = new int[] { 1, 2, 3, 4, 5 };
            var          console            = new ConsoleMock(Input);
            var          consolePlayer      = new ConsolePlayer(console);

            // Act
            consolePlayer.BeginGame(8, 5, 10);
            var guess = consolePlayer.GetGuess();

            consolePlayer.ResultFromPreviousGuess(5, 0);
            consolePlayer.EndGame(true, 1, guess);

            // Assert
            Assert.Equal(expectedPegNumbers, guess);
        }
Exemplo n.º 20
0
        private void testParseChoices(string userText, int minResponseCount, int maxResponseCount, int minResponseValue, int maxResponseValue, bool noDuplicates, int[] ExpectedResult)
        {
            var actualResult = ConsolePlayer.ParseChoice(userText, minResponseCount, maxResponseCount, minResponseValue, maxResponseValue, noDuplicates);

            if (ExpectedResult == null)
            {
                Assert.IsNull(actualResult);
            }
            else
            {
                Assert.IsNotNull(actualResult);
                Assert.AreEqual(ExpectedResult.Length, actualResult.Count);
                for (int i = 0; i < actualResult.Count; i++)
                {
                    Assert.AreEqual(ExpectedResult[i], actualResult[i]);
                }
            }
        }
Exemplo n.º 21
0
        public void CreateBoard()
        {
            var mazeArray = _mazeController.GenerateMazeArray();

            ConsolePlayer player       = new ConsolePlayer(new Position {
            });
            ConsoleExitDoor exitDoor   = new ConsoleExitDoor(new Position {
            });
            List <ConsoleBlock> blocks = Helper.ConvertMazeArrayToObject(mazeArray, ref player, ref exitDoor);

            //Insert blocks into board
            _consoleBoard.Insert(blocks);
            _consoleBoard.Insert(player);
            _consoleBoard.Insert(exitDoor);

            _consoleController.DrowBoard(_consoleBoard);

            var a = _computerController.PlayMazeLogic(_consoleBoard);
        }
Exemplo n.º 22
0
        static void UndoPlayer(Player p, TimeSpan delta, string[] names, int[] ids, Vec3S32[] marks)
        {
            UndoDrawOp op = new UndoDrawOp();

            op.Start = DateTime.UtcNow.Subtract(delta);
            op.who   = names[0]; op.ids = ids;

            if (Player.IsSuper(p))
            {
                // undo them across all loaded levels
                Level[] levels = LevelInfo.Loaded.Items;
                if (p == null)
                {
                    p = new ConsolePlayer();
                }

                foreach (Level lvl in levels)
                {
                    op.SetMarks(marks);
                    op.SetLevel(lvl);
                    op.Player = p; p.level = lvl;
                    DrawOpPerformer.DoQueuedDrawOp(p, op, null, marks);
                }
            }
            else
            {
                DrawOpPerformer.Do(op, null, p, marks);
            }

            string namesStr = names.Join(name => PlayerInfo.GetColoredName(p, name));

            if (op.found)
            {
                Chat.MessageGlobal("Undid {1}%S's changes for the past &b{0}", delta.Shorten(true), namesStr);
                Logger.Log(LogType.UserActivity, "Actions of {0} for the past {1} were undone.", names.Join(), delta.Shorten(true));
            }
            else
            {
                Player.Message(p, "No changes found by {1} %Sin the past &b{0}", delta.Shorten(true), namesStr);
            }
        }
Exemplo n.º 23
0
        public static ConsoleGameTable CreateTestGame(GameMode gameMode, object endingCondition)
        {
            ConsoleGameTable gameTable = new ConsoleGameTable();

            object[] endingConditionParams = new object[2];
            endingConditionParams[0] = gameTable;
            endingConditionParams[1] = endingCondition;
            gameTable.ChangeGameMode(gameMode, endingConditionParams);

            ConsolePlayer player1 = new ConsolePlayer(gameTable);
            ConsolePlayer player2 = new ConsolePlayer(gameTable);
            ConsolePlayer player3 = new ConsolePlayer(gameTable);
            ConsolePlayer player4 = new ConsolePlayer(gameTable);

            gameTable.Sit(player1);
            gameTable.Sit(player2);
            gameTable.Sit(player3);
            gameTable.Sit(player4);

            return(gameTable);
        }
Exemplo n.º 24
0
        public bool Execute(IRocketPlayer player, string command)
        {
            string[] commandParts = Regex.Matches(command, @"[\""](.+?)[\""]|([^ ]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture).Cast <Match>().Select(m => m.Value.Trim('"').Trim()).ToArray();

            if (commandParts.Length != 0)
            {
                name = commandParts[0];
                string[] parameters = commandParts.Skip(1).ToArray();
                if (player == null)
                {
                    player = new ConsolePlayer();
                }
                IRocketCommand rocketCommand = GetCommand(name);
                if (rocketCommand != null)
                {
                    if (rocketCommand.AllowedCaller == AllowedCaller.Player && player is ConsolePlayer)
                    {
                        Logger.Log("This command can't be called from console");
                        return(false);
                    }
                    if (rocketCommand.AllowedCaller == AllowedCaller.Console && !(player is ConsolePlayer))
                    {
                        Logger.Log("This command can only be called from console");
                        return(false);
                    }
                    try
                    {
                        rocketCommand.Execute(player, parameters);
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError("An error occured while executing " + rocketCommand.Name + " [" + String.Join(", ", parameters) + "]: " + ex.ToString());
                    }
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 25
0
        static void PlayGame()
        {
            IGame state   = new Othello();
            var   player1 = new ConsolePlayer()
            {
                Name = "Player 1"
            };
            //var player1 = new MonteCarloTreeSearchPlayer(1000) { Name = "Player 1" };
            var player2 = new MonteCarloTreeSearchPlayer(1000)
            {
                Name = "Player 2"
            };
            var playerLookup = new Dictionary <PlayerId, IPlayer>()
            {
                { PlayerId.Player1, player1 },
                { PlayerId.Player2, player2 },
            };
            PlayerId winner;

            while (!state.IsTerminal(out winner))
            {
                ConsolePlayer.GetBoardRepresentation((dynamic)state, Console.Out);
                var currentPlayer = playerLookup[state.CurrentPlayersTurn];
                state = currentPlayer.MakeMove(state, state.ExpandSuccessors());
                Console.WriteLine(currentPlayer.Name + " selected " + state.DescribeLastMove() + ".");
                Console.WriteLine();
            }
            Console.WriteLine("THE GAME IS OVER!");
            ConsolePlayer.GetBoardRepresentation((dynamic)state, Console.Out);
            if (winner == PlayerId.None)
            {
                Console.WriteLine("THE GAME WAS A TIE!");
            }
            else
            {
                Console.WriteLine("THE WINNER IS " + playerLookup[winner].Name + "!");
            }
        }
Exemplo n.º 26
0
        public void WinGame()
        {
            // Arrange
            var          secret      = new int[] { 1, 1, 2, 2 };
            const string Input       = "1234" + "5670" + "1122";
            const string ResultText1 = "Correct: 1 | Wrong position: 1";
            const string ResultText2 = "Correct: 0 | Wrong position: 0";
            const string ResultText3 = "Correct: 4 | Wrong position: 0";

            var console       = new ConsoleMock(Input);
            var consolePlayer = new ConsolePlayer(console);
            var game          = new Game(8, 4, 10, secret);

            // Act
            var result = game.Play(consolePlayer);

            // Assert
            Assert.True(result.WasTheSecretGuessed);
            Assert.Contains(WinText, console.Output);
            Assert.DoesNotContain(LoseText, console.Output);
            Assert.Contains(ResultText1, console.Output);
            Assert.Contains(ResultText2, console.Output);
            Assert.Contains(ResultText3, console.Output);
        }
        internal static void executeCommand(IRocketCommand command, Steamworks.CSteamID caller, string commandString)
        {
            if (!command.AllowFromConsole && !IsPlayer(caller))
            {
                Logger.Log("This command can't be called from console");
                return;
            }

            string[] collection = Regex.Matches(commandString, @"[\""](.+?)[\""]|([^ ]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture).Cast <Match>().Select(m => m.Value.Trim('"').Trim()).ToArray();

            try
            {
                IRocketPlayer p = UnturnedPlayer.FromCSteamID(caller);
                if (p == null)
                {
                    p = new ConsolePlayer();
                }
                command.Execute(p, collection);
            }
            catch (Exception ex)
            {
                Logger.LogError("An error occured while executing command /" + command.Name + " " + commandString + ": " + ex.ToString());
            }
        }
Exemplo n.º 28
0
        public void Start()
        {
            server = ServerSettings.GetSetting("IRC-Server");
            port = ServerSettings.GetSettingInt("IRC-Port");
            nickname = ServerSettings.GetSetting("IRC-Nickname");
            channel = ServerSettings.GetSetting("IRC-Channel");
            opChannel = ServerSettings.GetSetting("IRC-OPChannel");
            password = ServerSettings.GetSetting("IRC-NickServ");
            if (nickname == "" || server == "" || channel == "#" || channel == "" || port == -1 || !ServerSettings.GetSettingBoolean("IRC-Enabled"))
                return;
            ircControllers = LoadIrcControllers();
            Logger.Log("Connecting to IRC...");
            botOn = true;
            try
            {
                // Connect
                irc = new TcpClient(server, port);
                sstream = irc.GetStream();
                sread = new StreamReader(sstream);
                swrite = new StreamWriter(sstream);
            }
            catch (Exception e)
            {
                Logger.Log("Error connecting to " + server + ": " + e);
                return;
            }

            // Identify
            swrite.WriteLine("USER {0} {0} {0} :{1}", nickname, nickname);
            swrite.Flush();
            swrite.WriteLine("NICK {0}", nickname);
            swrite.Flush();

            cp = new ConsolePlayer(cio);

            while (botOn)
            {
                try
                {
                    if ((line = sread.ReadLine()) != null && botOn)
                    {
                        if (debug) Logger.Log(line);
                        splitLine = line.Split(' ');

                        if (splitLine.Length > 0)
                        {
                            if (splitLine[1] == "376" || splitLine[1] == "422")
                            {
                                swrite.WriteLine("JOIN {0}", channel);
                                swrite.Flush();
                                if (opChannel != "#" || opChannel != "")
                                {
                                    swrite.WriteLine("JOIN {0}", opChannel);
                                    swrite.Flush();
                                }
                                swrite.WriteLine("NS IDENTIFY {0} {1}", nickname, password);
                                swrite.Flush();
                                connected = true;
                                Logger.Log("Connected!");
                            }

                            if (splitLine[0] == "PING")
                            {
                                swrite.WriteLine("PONG {0}", splitLine[1]);
                                swrite.Flush();
                            }
                        }
                        string replyChannel = "";
                        if (line.Split(' ')[2] != channel && line.Split(' ')[2] != opChannel) replyChannel = line.Split('!')[0].Remove(0, 1);
                        else replyChannel = line.Split(' ')[2];
                        line = line.Replace("%", "&");
                        if (GetSpokenLine(line).Equals("!players"))
                        {
                            swrite.WriteLine("PRIVMSG {0} :" + "There are " + Server.Players.Count + " player(s) online:",
                                         replyChannel);
                            swrite.Flush();
                            string playerString = "";
                            Server.Players.ForEach(delegate(Player pl)
                            {
                                playerString = playerString + pl.Username + ", ";
                            });
                            swrite.WriteLine("PRIVMSG {0} :" + playerString.Remove(playerString.Length - 2, 2),
                                         replyChannel);
                            swrite.Flush();
                        }
                        else if (GetSpokenLine(line).Equals("!url"))
                        {
                            swrite.WriteLine("PRIVMSG {0} :" + "The url for the server is: " + Server.URL,
                                         replyChannel);
                            swrite.Flush();
                        }
                        else if (GetSpokenLine(line).StartsWith("!"))
                        {
                            if (GetSpokenLine(line).Trim().Length > 1)
                            {
                                string name = GetSpokenLine(line).Trim().Substring(1);
                                ICommand c = Command.Find(name);
                                if (c != null)
                                {
                                    int i = GetSpokenLine(line).Trim().IndexOf(" ");
                                    if (i > 0)
                                    {
                                        string[] cargs = GetSpokenLine(line).Trim().Substring(i + 1).Split(' ');
                                        cp.replyChannel = replyChannel;
                                        c.Use(cp, cargs);
                                    }
                                    else
                                    {
                                        cp.replyChannel = replyChannel;
                                        c.Use(cp, new string[0]);
                                    }
                                }
                            }
                        }
                        else if (line.ToLower().Contains("privmsg") && splitLine[1] != "005")
                        {
                            if (replyChannel != opChannel)
                            {
                                try
                                {
                                    Player.UniversalChat("[IRC] <" + GetUsernameSpeaking(line) + ">: " + IRCToClassic(GetSpokenLine(line)));
                                    Logger.Log("[IRC] <" + GetUsernameSpeaking(line) + ">: " + IRCToClassic(GetSpokenLine(line)));
                                }
                                catch { }
                            }
                            else if (replyChannel == opChannel)
                            {
                                try
                                {
                                    Player.UniversalChatOps("[OPIRC] <" + GetUsernameSpeaking(line) + ">: " + IRCToClassic(GetSpokenLine(line)));
                                    Logger.Log("[OPIRC] <" + GetUsernameSpeaking(line) + ">: " + IRCToClassic(GetSpokenLine(line)));
                                }
                                catch { }
                            }
                        }
                    }
                }
                catch { }
            }
            // Clean up
            connected = false;
            swrite.Close();
            sread.Close();
            irc.Close();
        }
Exemplo n.º 29
0
        public void Init()
        {
            logger.log("Server initialized");
            //Init salt
            string saltChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~";
            Random rand = new Random();
            int saltLength = rand.Next(12, 16);
            for (int i = 0; i < saltLength; i++)
            {
                salt += saltChars[rand.Next(0, saltChars.Length - 1)];
            }

            //Load config
            LoadConfig();
            //Put server name in console title
            Console.Title = this.serverName;
            if (!this.isPublic) { Console.Title += " (PRIVATE)"; }

            playerlist = new Player[maxPlayers + 2];  //Extra slot is for rejects, and another one (for some odd reason it's less by one)
            for (int i = 0; i < maxPlayers + 2; i++)
            {
                playerlist[i] = null;
            }

            //Load world and start save timer
            if (!Directory.Exists("maps"))
            {
                Directory.CreateDirectory("maps");
            }
            if (!File.Exists("maps/" + worldPath))
            {
                world = new World(worldPath, 256, 64, 256);
                world.Save();
            }
            else
            {
                world = new World(worldPath);
                //world.Save();
            }
            worldSaveTimer = new System.Timers.Timer(60000.0);
            worldSaveTimer.Elapsed += new System.Timers.ElapsedEventHandler(delegate
            {
                world.Save();
            });

            physics = new BasicPhysics(world, lavaSpongeEnabled);
            this.physThread = new System.Threading.Thread(PhysicsUpdateLoop);
            physThread.Start();
            logger.log("Started BasicPhysics Engine");

            //Intercept Ctrl+C
            Console.CancelKeyPress += new ConsoleCancelEventHandler(delegate
                {
                    world.Save();
                });

            //Load Commands
            Command.Init();
            consolePlayer = new ConsolePlayer();

            //Load blocks
            Blocks.Init();

            //Load special chars
            Player.specialChars = new Dictionary<string, char>();
            Player.specialChars.Add(@"\:D", (char)2);        //☻
            Player.specialChars.Add(@"\<3", (char)3);        //♥
            Player.specialChars.Add(@"\<>", (char)4);        //♦
            Player.specialChars.Add(@"\club", (char)5);      //♣
            Player.specialChars.Add(@"\spade", (char)6);     //♠
            Player.specialChars.Add(@"\boy", (char)11);      //♂
            Player.specialChars.Add(@"\girl", (char)12);     //♀
            Player.specialChars.Add(@"\8note", (char)13);    //♪
            Player.specialChars.Add(@"\16note", (char)14);   //♫
            Player.specialChars.Add(@"\*", (char)15);        //☼
            Player.specialChars.Add(@"\>", (char)16);        //►
            Player.specialChars.Add(@"\<-", (char)27);       //←
            Player.specialChars.Add(@"\<", (char)17);        //◄
            Player.specialChars.Add(@"\updn", (char)18);     //↕
            Player.specialChars.Add(@"\2!", (char)19);       //‼
            Player.specialChars.Add(@"\p", (char)20);        //¶
            Player.specialChars.Add(@"\sec", (char)21);      //§
            Player.specialChars.Add(@"\|up", (char)24);      //↑
            Player.specialChars.Add(@"\|dn", (char)25);      //↓
            Player.specialChars.Add(@"\->", (char)26);       //→
            //** The ← symbol was moved before ◄ due to parsing order issues
            Player.specialChars.Add(@"\lr", (char)29);       //↔
            Player.specialChars.Add(@"\up", (char)30);       //▲
            Player.specialChars.Add(@"\dn", (char)31);       //▼

            //Load ranks
            playerRanksDict = new Dictionary<string, byte>();
            try
            {
                if (File.Exists("ranks.txt"))
                {
                    StreamReader sr = new StreamReader(File.OpenRead("ranks.txt"));
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        if (line != null && !line.Equals("") && line.IndexOf(':') >= 0)
                        {
                            string user = line.Substring(0, line.IndexOf(':'));
                            byte rank = byte.Parse(line.Substring(line.IndexOf(':') + 1));
                            playerRanksDict.Add(user, rank);
                        }
                    }
                    sr.Close();
                }
            }
            catch (OverflowException)
            {
                logger.log("Error while loading ranks: rank cannot be higher than 255", Logger.LogType.Error);
                running = false;
                return;
            }
            catch (Exception e)
            {
                logger.log("Error while loading ranks:", Logger.LogType.Error);
                logger.log(e);
                running = false;
                return;
            }
            logger.log("Loaded ranks from ranks.txt");

            ipbanned = new List<string>();
            try
            {
                if (File.Exists("ipbans.txt"))
                {
                    StreamReader sr = new StreamReader(File.OpenRead("ipbans.txt"));
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        if (line != null && !line.Equals(""))
                        {
                            ipbanned.Add(line.Trim());
                        }
                    }
                    sr.Close();
                }
            }
            catch (Exception e)
            {
                logger.log("Error while loading ranks:", Logger.LogType.Error);
                logger.log(e);
                running = false;
                return;
            }
            logger.log("Loaded ipbans from ipbans.txt");
            //etc

            //Initialize heartbeat timer
            heartbeatTimer.Elapsed += new System.Timers.ElapsedEventHandler(delegate
                {
                    beater.Beat(false);
                });
            heartbeatTimer.Start();
            beater.Beat(true);  //Initial heartbeat

            //Start TCP listener thread
            this.ListenThread = new System.Threading.Thread( new System.Threading.ThreadStart( delegate
                {
                    this.listener = new TcpListener(IPAddress.Any, this.port);
                    try
                    {
                        listener.Start();
                        listener.BeginAcceptTcpClient(new AsyncCallback(ClientAccept), null);
                    }
                    catch(Exception e)
                    {
                        listener.Stop();
                        logger.log(e);
                    }
                    logger.log("Started listener thread");
                }));
            this.ListenThread.IsBackground = true;
            this.ListenThread.Start();
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            Board.Board board = new Board.Board(11, 11);
            board.Initialize();
            board.Print();

            #region test
            IAgent   player0 = new ConsolePlayer();                                             //AlphaBetaTT(1, new WeightedEvaluation(200, 150, 70, 20, 4));//WeightedEvaluation());//ConsolePlayer();//RandomAgent();
            IAgent   player1 = new AlphaBetaTT(2, new WeightedEvaluation(150, 200, 50, 20, 4)); //EvaluationMaterialBalance());
            IAgent[] players = new IAgent[2];
            players[0] = player0;
            players[1] = player1;
            #endregion test

            #region replay
            if (false)
            {
                ReplayLog(DEFAULT_LOG_PATH, board, true);

                Environment.Exit(0);
            }
            #endregion

            int player = 0;

            #region restore position from log
            if (false)
            {
                ReplayLog(DEFAULT_LOG_PATH, board, false);
            }
            #endregion

            while (player == 0 || player == 1)
            {
                (int, int)nextMove = players[player].GetNextMove(board);
                board.Move(nextMove);
                Console.WriteLine($"Next Move: {board.SerializeMove(board.log.Last.Value)}");
                board.Print();
                player = board.activePlayer;

                using (System.IO.StreamWriter file = new System.IO.StreamWriter(DEFAULT_LOG_PATH, true))
                {
                    file.WriteLine($"{board.SerializeMove(nextMove)}");
                }

                if (board.CheckTerminalPosition() == 0)
                {
                    player = -2;
                }
                else if (board.CheckTerminalPosition() == 1)
                {
                    player = -1;
                }
            }

            if (player == -1)
            {
                Console.WriteLine("Silver player won");
            }
            else if (player == -2)
            {
                Console.WriteLine("Gold player won");
            }

            LinkedList <(int, int)> possibleMoves = board.GetLegalMoves();

            Console.WriteLine("END!");
        }
Exemplo n.º 31
0
        public void Start()
        {
            server    = ServerSettings.GetSetting("IRC-Server");
            port      = ServerSettings.GetSettingInt("IRC-Port");
            nickname  = ServerSettings.GetSetting("IRC-Nickname");
            channel   = ServerSettings.GetSetting("IRC-Channel");
            opChannel = ServerSettings.GetSetting("IRC-OPChannel");
            password  = ServerSettings.GetSetting("IRC-NickServ");
            if (nickname == "" || server == "" || channel == "#" || channel == "" || port == -1 || !ServerSettings.GetSettingBoolean("IRC-Enabled"))
            {
                return;
            }
            ircControllers = LoadIrcControllers();
            Logger.Log("Connecting to IRC...");
            botOn = true;
            try
            {
                // Connect
                irc     = new TcpClient(server, port);
                sstream = irc.GetStream();
                sread   = new StreamReader(sstream);
                swrite  = new StreamWriter(sstream);
            }
            catch (Exception e)
            {
                Logger.Log("Error connecting to " + server + ": " + e);
                return;
            }

            // Identify
            swrite.WriteLine("USER {0} {0} {0} :{1}", nickname, nickname);
            swrite.Flush();
            swrite.WriteLine("NICK {0}", nickname);
            swrite.Flush();

            cp = new ConsolePlayer(cio);

            while (botOn)
            {
                try
                {
                    if ((line = sread.ReadLine()) != null && botOn)
                    {
                        if (debug)
                        {
                            Logger.Log(line);
                        }
                        splitLine = line.Split(' ');

                        if (splitLine.Length > 0)
                        {
                            if (splitLine[1] == "376" || splitLine[1] == "422")
                            {
                                swrite.WriteLine("JOIN {0}", channel);
                                swrite.Flush();
                                if (opChannel != "#" || opChannel != "")
                                {
                                    swrite.WriteLine("JOIN {0}", opChannel);
                                    swrite.Flush();
                                }
                                swrite.WriteLine("NS IDENTIFY {0} {1}", nickname, password);
                                swrite.Flush();
                                connected = true;
                                Logger.Log("Connected!");
                            }

                            if (splitLine[0] == "PING")
                            {
                                swrite.WriteLine("PONG {0}", splitLine[1]);
                                swrite.Flush();
                            }
                        }
                        string replyChannel = "";
                        if (line.Split(' ')[2] != channel && line.Split(' ')[2] != opChannel)
                        {
                            replyChannel = line.Split('!')[0].Remove(0, 1);
                        }
                        else
                        {
                            replyChannel = line.Split(' ')[2];
                        }
                        line = line.Replace("%", "&");
                        if (GetSpokenLine(line).Equals("!players"))
                        {
                            swrite.WriteLine("PRIVMSG {0} :" + "There are " + Server.Players.Count + " player(s) online:",
                                             replyChannel);
                            swrite.Flush();
                            string playerString = "";
                            Server.Players.ForEach(delegate(Player pl)
                            {
                                playerString = playerString + pl.Username + ", ";
                            });
                            swrite.WriteLine("PRIVMSG {0} :" + playerString.Remove(playerString.Length - 2, 2),
                                             replyChannel);
                            swrite.Flush();
                        }
                        else if (GetSpokenLine(line).Equals("!url"))
                        {
                            swrite.WriteLine("PRIVMSG {0} :" + "The url for the server is: " + Server.URL,
                                             replyChannel);
                            swrite.Flush();
                        }
                        else if (GetSpokenLine(line).StartsWith("!"))
                        {
                            if (GetSpokenLine(line).Trim().Length > 1)
                            {
                                string   name = GetSpokenLine(line).Trim().Substring(1);
                                ICommand c    = Command.Find(name);
                                if (c != null)
                                {
                                    int i = GetSpokenLine(line).Trim().IndexOf(" ");
                                    if (i > 0)
                                    {
                                        string[] cargs = GetSpokenLine(line).Trim().Substring(i + 1).Split(' ');
                                        cp.replyChannel = replyChannel;
                                        c.Use(cp, cargs);
                                    }
                                    else
                                    {
                                        cp.replyChannel = replyChannel;
                                        c.Use(cp, new string[0]);
                                    }
                                }
                            }
                        }
                        else if (line.ToLower().Contains("privmsg") && splitLine[1] != "005")
                        {
                            if (replyChannel != opChannel)
                            {
                                try
                                {
                                    Player.UniversalChat("[IRC] <" + GetUsernameSpeaking(line) + ">: " + IRCToClassic(GetSpokenLine(line)));
                                    Logger.Log("[IRC] <" + GetUsernameSpeaking(line) + ">: " + IRCToClassic(GetSpokenLine(line)));
                                }
                                catch { }
                            }
                            else if (replyChannel == opChannel)
                            {
                                try
                                {
                                    Player.UniversalChatOps("[OPIRC] <" + GetUsernameSpeaking(line) + ">: " + IRCToClassic(GetSpokenLine(line)));
                                    Logger.Log("[OPIRC] <" + GetUsernameSpeaking(line) + ">: " + IRCToClassic(GetSpokenLine(line)));
                                }
                                catch { }
                            }
                        }
                    }
                }
                catch { }
            }
            // Clean up
            connected = false;
            swrite.Close();
            sread.Close();
            irc.Close();
        }
Exemplo n.º 32
0
        public Task HandleEventAsync(object emitter, CommandExecutedEvent @event)
        {
            async UniTask Task()
            {
                // RocketMod commands must run on main thread
                await UniTask.SwitchToMainThread();

                if (@event.CommandContext.Exception is CommandNotFoundException && R.Commands != null)
                {
                    var commandAlias = @event.CommandContext.CommandAlias;
                    if (string.IsNullOrEmpty(commandAlias))
                    {
                        return;
                    }

                    var isRocketPrefixed = commandAlias.StartsWith(s_RocketPrefix);
                    if (isRocketPrefixed)
                    {
                        commandAlias = s_PrefixRegex.Replace(commandAlias, string.Empty, 1);
                    }

                    IRocketPlayer rocketPlayer;
                    if (@event.Actor is UnturnedUser user)
                    {
                        var steamPlayer = user.Player.SteamPlayer;
                        if (!(bool)s_CheckPermissionsMethod.Invoke(null, new object[] { steamPlayer, $"/{commandAlias}" }))
                        {
                            // command doesnt exist or no permission
                            @event.ExceptionHandled = true;
                            return;
                        }

                        rocketPlayer = UnturnedPlayer.FromSteamPlayer(steamPlayer);
                    }
                    else if (@event.Actor.Type.Equals(KnownActorTypes.Console, StringComparison.OrdinalIgnoreCase))
                    {
                        rocketPlayer = new ConsolePlayer();

                        var command = R.Commands.GetCommand(commandAlias.ToLower(CultureInfo.InvariantCulture));
                        if (command == null)
                        {
                            return;
                        }
                    }
                    else
                    {
                        // unsupported user; do not handle
                        return;
                    }

                    var commandLine = @event.CommandContext.GetCommandLine();
                    if (isRocketPrefixed)
                    {
                        commandLine = s_PrefixRegex.Replace(commandLine, string.Empty, count: 1);
                    }

                    R.Commands.Execute(rocketPlayer, commandLine);
                    @event.ExceptionHandled = true;
                }
            }

            return(Task().AsTask());
        }
Exemplo n.º 33
0
        private void txtMessage_KeyDown(object sender, KeyEventArgs e)
        {
            if ( e.KeyCode == Keys.Enter ) {

                if (txtMessage.Text.StartsWith("/"))
                {
                    ICommand cmd = null;

                    var commandSplit = txtMessage.Text.Remove(0, 1).Split(' ');
                    var args = commandSplit.Where((val, index) => index != 0).ToArray();
                    cmd = Command.Find(commandSplit[0]);

                    if (cmd == null)
                    {
                        Logger.Log("Command not found!");
                        txtMessage.Text = "";
                        return; // cannot run the command
                    }
                    if (cp == null)
                        cp = new ConsolePlayer(cio);
                    try
                    {
                        cmd.Use(cp, args);
                    }
                    catch (Exception ex) { Logger.LogError(ex); Logger.Log("Command aborted"); }
                    Logger.Log("CONSOLE used: /" + commandSplit[0]);
                    txtMessage.InHintState = true;
                    return;
                }

                if ( String.IsNullOrWhiteSpace(txtMessage.Text) ) {
                    Logger.Log("&4Please specify a valid message!");
                    txtMessage.InHintState = true;
                    return;
                }

                if ( cmbChatType.Text == "OpChat" ) {
                    Player.UniversalChatOps("&a<&fTo Ops&a> [&fConsole&a]:&f " + txtMessage.Text);
                    Logger.Log("<OpChat> &5[&1Console&5]: &1" + txtMessage.Text);
                    txtMessage.InHintState = true;
                }

                else if ( cmbChatType.Text == "AdminChat" ) {
                    Player.UniversalChatAdmins("&a<&fTo Admins&a> [&fConsole&a]:&f " + txtMessage.Text);
                    Logger.Log("<AdminChat> &5[&1Console&5]: &1" + txtMessage.Text);
                    txtMessage.InHintState = true;
                }
                else if (cmbChatType.Text == "GlobalChat")
                {
                    Server.GC.SendConsoleMessage(txtMessage.Text);
                    Logger.Log("<GC> &0[&2Console&0]: " + txtMessage.Text);
                    txtMessage.Text = "";
                }
                else {
                    Server.IRC.SendConsoleMessage(txtMessage.Text);
                    Player.UniversalChat("&a[&fConsole&a]:&f " + txtMessage.Text);
                    Logger.Log("&0[&2Console&0]: " + txtMessage.Text);
                    txtMessage.InHintState = true;
                }
            }
            else if ( e.KeyCode == Keys.Down ) {
                cmbChatType.SelectedIndex = cmbChatType.SelectedIndex + ( cmbChatType.Items.Count == 1 ? 0 : cmbChatType.SelectedIndex + 1 );
            }
            else if ( e.KeyCode == Keys.Up ) {
                cmbChatType.SelectedIndex = ( cmbChatType.SelectedIndex == 0 ? cmbChatType.Items.Count - 1 : cmbChatType.SelectedIndex - 1 );
            }
        }
Exemplo n.º 34
0
        public bool Execute(IRocketPlayer player, string command)
        {
            command = command.TrimStart('/');
            string[] commandParts = Regex.Matches(command, @"[\""](.+?)[\""]|([^ ]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture).Cast <Match>().Select(m => m.Value.Trim('"').Trim()).ToArray();

            if (commandParts.Length != 0)
            {
                name = commandParts[0];
                string[] parameters = commandParts.Skip(1).ToArray();
                if (player == null)
                {
                    player = new ConsolePlayer();
                }
                IRocketCommand rocketCommand = GetCommand(name);
                double         cooldown      = GetCooldown(player, rocketCommand);
                if (rocketCommand != null)
                {
                    if (rocketCommand.AllowedCaller == AllowedCaller.Player && player is ConsolePlayer)
                    {
                        Logger.Log("This command can't be called from console");
                        return(false);
                    }
                    if (rocketCommand.AllowedCaller == AllowedCaller.Console && !(player is ConsolePlayer))
                    {
                        Logger.Log("This command can only be called from console");
                        return(false);
                    }
                    if (cooldown != -1)
                    {
                        Logger.Log("This command is still on cooldown");
                        return(false);
                    }
                    try
                    {
                        bool cancelCommand = false;
                        if (OnExecuteCommand != null)
                        {
                            foreach (var handler in OnExecuteCommand.GetInvocationList().Cast <ExecuteCommand>())
                            {
                                try
                                {
                                    handler(player, rocketCommand, ref cancelCommand);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex);
                                }
                            }
                        }
                        if (!cancelCommand)
                        {
                            try
                            {
                                rocketCommand.Execute(player, parameters);
                                if (!player.HasPermission("*"))
                                {
                                    SetCooldown(player, rocketCommand);
                                }
                            }
                            catch (NoPermissionsForCommandException ex)
                            {
                                Logger.LogWarning(ex.Message);
                            }
                            catch (WrongUsageOfCommandException)
                            {
                                //
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError("An error occured while executing " + rocketCommand.Name + " [" + String.Join(", ", parameters) + "]: " + ex.ToString());
                    }
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 35
0
 public void Initialize()
 {
     _mockConsole = new Mock<IConsole>();
     _mockBank = new Mock<IBank>();
     _player = new ConsolePlayer("Rob", _mockConsole.Object, _mockBank.Object);
 }
Exemplo n.º 36
0
        static void Main(string[] args) {
            Logger.Init();
            ServerSettings.Init();
            cp = new ConsolePlayer(cio);
            bool checker = CheckArgs(args);
            Console.Title = ServerSettings.GetSetting("ServerName") + " - MCForge 6"; //Don't know what MCForge version we are using yet.
            if (!checker)
                new Thread(new ThreadStart(Server.Init)).Start();
            else
                Logger.Log("Aborting Setup..", LogType.Critical);

            //declare the Hooks
            //Error Logging
            Logger.OnRecieveErrorLog += new EventHandler<ErrorLogEventArgs>(Logger_OnRecieveErrorLog);
            //Normal Logs
            Logger.OnRecieveLog += new EventHandler<LogEventArgs>(Logger_OnRecieveLog);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            ConsoleKeyInfo keyInfo;
            if (Console.CursorLeft < 3)
                WriteInputLine();
            while ((keyInfo = Console.ReadKey()) != null) {
                char key = keyInfo.KeyChar;
                //handles escape
                if (keyInfo.Key == ConsoleKey.Escape) continue;
                // Ignore if Alt or Ctrl is pressed
                if ((keyInfo.Modifiers & ConsoleModifiers.Alt) == ConsoleModifiers.Alt)
                    continue;
                if ((keyInfo.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control)
                    continue;
                // Ignore if KeyChar value is \u0000.
                if (keyInfo.KeyChar == '\u0000') continue;
                // Ignore tab key.
                if (keyInfo.Key == ConsoleKey.Tab) continue;
                // handle function keys
                if (keyInfo.Key >= ConsoleKey.F1 && keyInfo.Key <= ConsoleKey.F24) continue;

                if (keyInfo.Key != ConsoleKey.Enter) {
                    if (keyInfo.Key == ConsoleKey.Backspace && input.Length > 0) {
                        ClearConsoleLine(Console.CursorTop);
                        Console.SetCursorPosition(0, Console.CursorTop);
                        if (!(input.Length < 1)) {
                            input = input.Remove(input.Length - 1, 1);
                            WriteInputLine("> " + input);
                        }
                    }
                    else if (Char.IsLetterOrDigit(key) || Char.IsPunctuation(key) || Char.IsSymbol(key) || key == ' ')
                        input += key.ToString();
                    continue;
                }
                else {
                    if (String.IsNullOrWhiteSpace(input)) {
                        WriteInputLine();
                        continue;
                    }
                    WriteLine("");
                    if (Handle(input)) return;
                    input = "";
                    WriteInputLine();
                }
            }
        }
Exemplo n.º 37
0
        private static bool Handle(string input) {
            //check if it is a command
            if (input.StartsWith("/")) {
                ICommand cmd = null;

                string[] commandSplit = input.Remove(0, 1).Split(' ');
                string[] args = commandSplit.Where((val, index) => index != 0).ToArray();
                cmd = Command.Find(commandSplit[0]);

                if (cmd == null) {
                    WriteLine("Command not found!");
                    return false; // cannot run the command
                }
                if (cp == null)
                    cp = new ConsolePlayer(cio);
                try {
                    cmd.Use(cp, args);
                }
                catch (Exception e) { Logger.LogError(e); Logger.Log("Command aborted"); }
                Logger.Log("CONSOLE used: /" + commandSplit[0]);
            }
            else if (input.ToLower() == "!stop") {
                Console.Write("Would you like to save all? [y/n]:");
                if (Console.ReadLine().ToLower().StartsWith("y")) {
                    Server.SaveAll();
                    Server.Stop();
                }
                else {
                    Server.Stop();
                }
                return true;
            }
            else if (input.ToLower() == "!copyurl") {
                System.Windows.Forms.Clipboard.SetDataObject(Server.URL, true);
            }
            else {
                Player.UniversalChat(Colors.white + "[Console] " + Server.DefaultColor + input);
                Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 1);
                Logger.Log("[Console] " + input, Color.Yellow, Color.Black, LogType.Normal);
            }
            return false;
        }