Ejemplo n.º 1
0
        private void SendCommandInternal(string command, Action callback, params object[] args)
        {
            if (string.IsNullOrWhiteSpace(command))
            {
                throw new ArgumentNullException(nameof(command));
            }

            command = string.Format(command, args);

            TryStartTimedCommand(command);

            EngineCommand cmd = IdentifyCommand(command);

            if (cmd == EngineCommand.Exit)
            {
                throw new Exception("Can't send exit command.");
            }

            _inputToProcess.Enqueue(command);

            if (null != callback)
            {
                _commandCallbacks.Enqueue(callback);
            }

            if (_inputToProcess.Count == 1)
            {
                RunNextCommand();
            }
        }
Ejemplo n.º 2
0
        public void Engine_Execute_ReturnsEmpty()
        {
            var command       = new EngineCommand(_console, LoggerMock.GetLogger <EngineCommand>().Object);
            var resultMessage = command.Execute();

            Assert.Equal("", resultMessage);
        }
Ejemplo n.º 3
0
        public EngineCommand PollCommand(Bot bot)
        {
            var line = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(line))
            {
                return(null);
            }

            EngineCommand command = null;
            var           parse   = line.Split(' ');

            switch (parse[0])
            {
            case "settings":
                command = new SettingsCommand(bot.MatchSettings, parse[1], parse[2]);
                break;

            case "update":
                if (parse[1] == "game")
                {
                    command = new GameStateCommand(bot.GameState, parse[2], parse[3]);
                }
                else
                {
                    if (bot.MatchSettings.PlayerNames.Contains(parse[1]))
                    {
                        if (!bot.Players.ContainsKey(parse[1]))
                        {
                            bot.Players.Add(parse[1], new PlayerState(bot.MatchSettings.FieldWidth, bot.MatchSettings.FieldHeight));
                        }

                        var player = bot.Players[parse[1]];
                        command = new PlayerCommand(player, parse[1], parse[2], parse[3]);
                    }
                    else
                    {
                        Console.WriteLine("Invalid player: '{0}'", parse[1]);
                    }
                }
                break;

            case "action":
                command = new BotCommand(bot, parse[1], parse[2]);
                break;
            }

            if (command == null)
            {
                Console.WriteLine("Invalid command: '{0}'", parse[0]);
            }

            return(command);
        }
Ejemplo n.º 4
0
        private void TryStartTimedCommand(string command)
        {
            EngineCommand cmd = IdentifyCommand(command);

            if (cmd == EngineCommand.BestMove)
            {
                string[] split = command.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (split.Length > 2 && split[1] == "time")
                {
                    if (TimeSpan.TryParse(split[2], out TimeSpan ts))
                    {
                        StartTimedCommand(ts);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private static MySqlCommand CreateTextCommand(EngineCommand engineCommand)
        {
            MySqlCommand command = new MySqlCommand(engineCommand.CommandText)
            {
                CommandType = CommandType.Text
            };

            if (engineCommand.Parameters == null)
            {
                return(command);
            }

            foreach (var pair in engineCommand.Parameters)
            {
                command.Parameters.Add(new MySqlParameter(pair.Key, pair.Value));
            }

            return(command);
        }
Ejemplo n.º 6
0
        public static SqliteCommand CreateTextCommand(EngineCommand engineCommand)
        {
#pragma warning disable CA2100 // Review SQL queries for security vulnerabilities
            SqliteCommand command = new SqliteCommand(engineCommand.CommandText)
            {
                CommandType = CommandType.Text
            };
#pragma warning restore CA2100 // Review SQL queries for security vulnerabilities

            if (engineCommand.Parameters == null)
            {
                return(command);
            }

            foreach (var pair in engineCommand.Parameters)
            {
                command.Parameters.Add(new SqliteParameter(pair.Key, pair.Value));
            }

            return(command);
        }
Ejemplo n.º 7
0
        private void ProcessEngineOutput(EngineCommand command, string[] outputLines)
        {
            string errorMessage       = "";
            string invalidMoveMessage = "";

            for (int i = 0; i < outputLines.Length; i++)
            {
                if (outputLines[i].StartsWith("err"))
                {
                    errorMessage += outputLines[i].Substring(outputLines[i].IndexOf(' ') + 1) + Environment.NewLine;
                }
                else if (outputLines[i].StartsWith("invalidmove"))
                {
                    invalidMoveMessage += outputLines[i].Substring(outputLines[i].IndexOf(' ') + 1) + Environment.NewLine;
                }
            }

            if (!string.IsNullOrWhiteSpace(errorMessage))
            {
                throw new EngineErrorException(errorMessage.Trim(), outputLines);
            }

            if (!string.IsNullOrWhiteSpace(invalidMoveMessage))
            {
                throw new EngineInvalidMoveException(invalidMoveMessage.Trim(), outputLines);
            }

            string firstLine = "";
            string lastLine  = "";

            if (null != outputLines && outputLines.Length > 0)
            {
                firstLine = outputLines[0];
                lastLine  = outputLines[outputLines.Length - 1];
            }

            // Update other properties
            switch (command)
            {
            case EngineCommand.NewGame:
            case EngineCommand.Play:
            case EngineCommand.Pass:
            case EngineCommand.Undo:
                Board = !string.IsNullOrWhiteSpace(firstLine) ? GameBoard.ParseGameString(firstLine, true) : null;
                break;

            case EngineCommand.ValidMoves:
                ValidMoves = !string.IsNullOrWhiteSpace(firstLine) ? NotationUtils.ParseMoveStringList(Board, firstLine) : null;
                break;

            case EngineCommand.BestMove:
                // Update the target move (and potentially auto-play it)
                ProcessBestMove(lastLine, true);
                TryStopTimedCommand();
                break;

            case EngineCommand.Options:
                string[] optionLines = new string[outputLines.Length];
                Array.Copy(outputLines, optionLines, optionLines.Length);
                EngineOptions.ParseEngineOptionLines(optionLines);
                break;

            case EngineCommand.Info:
                ID = firstLine.StartsWith("id ") ? firstLine.Substring(3).Trim() : "Unknown";
                EngineCapabilities = new EngineCapabilities(lastLine);
                break;

            default:
                break;
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// ExecuteCommandScalarAsync
        /// </summary>
        /// <param name="Transaction"></param>
        /// <param name="dbName"></param>
        /// <param name="engineCommand"></param>
        /// <param name="useMaster"></param>
        /// <returns></returns>
        /// <exception cref="DatabaseException"></exception>
        public async Task <object?> ExecuteCommandScalarAsync(IDbTransaction?Transaction, string dbName, EngineCommand engineCommand, bool useMaster = false)
        {
            using MySqlCommand command = CreateTextCommand(engineCommand);

            if (Transaction == null)
            {
                return(await MySQLExecuter.ExecuteCommandScalarAsync(GetConnectionString(dbName, useMaster), command).ConfigureAwait(false));
            }
            else
            {
                return(await MySQLExecuter.ExecuteCommandScalarAsync((MySqlTransaction)Transaction, command).ConfigureAwait(false));
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// ExecuteCommandNonQueryAsync
        /// </summary>
        /// <param name="Transaction"></param>
        /// <param name="dbName"></param>
        /// <param name="engineCommand"></param>
        /// <returns></returns>
        /// <exception cref="DatabaseException"></exception>
        public async Task <int> ExecuteCommandNonQueryAsync(IDbTransaction?Transaction, string dbName, EngineCommand engineCommand)
        {
            using MySqlCommand command = CreateTextCommand(engineCommand);

            if (Transaction == null)
            {
                return(await MySQLExecuter.ExecuteCommandNonQueryAsync(GetConnectionString(dbName, true), command).ConfigureAwait(false));
            }
            else
            {
                return(await MySQLExecuter.ExecuteCommandNonQueryAsync((MySqlTransaction)Transaction, command).ConfigureAwait(false));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// ExecuteCommandReaderAsync
        /// </summary>
        /// <param name="Transaction"></param>
        /// <param name="dbName"></param>
        /// <param name="engineCommand"></param>
        /// <param name="useMaster"></param>
        /// <returns></returns>
        /// <exception cref="DatabaseException"></exception>
        public async Task <IDataReader> ExecuteCommandReaderAsync(IDbTransaction?Transaction, string dbName, EngineCommand engineCommand, bool useMaster = false)
        {
            //使用using的话,会同时关闭reader.
            //在Microsoft.Data.Sqlite实现中, dipose connection后,会自动dispose command
#pragma warning disable CA2000 // Dispose objects before losing scope
            SqliteCommand dbCommand = CreateTextCommand(engineCommand);
#pragma warning restore CA2000 // Dispose objects before losing scope

            if (Transaction == null)
            {
                return(await SQLiteExecuter.ExecuteCommandReaderAsync(GetConnectionString(dbName, useMaster), dbCommand).ConfigureAwait(false));
            }
            else
            {
                return(await SQLiteExecuter.ExecuteCommandReaderAsync((SqliteTransaction)Transaction, dbCommand).ConfigureAwait(false));
            }
        }
Ejemplo n.º 11
0
        private void ProcessEngineOutput(EngineCommand command, string[] outputLines)
        {
            string errorMessage       = "";
            string invalidMoveMessage = "";

            foreach (string line in outputLines)
            {
                if (line.StartsWith("err"))
                {
                    errorMessage = line.Substring(line.IndexOf(' ') + 1);
                }
                else if (line.StartsWith("invalidmove"))
                {
                    invalidMoveMessage = line.Substring(line.IndexOf(' ') + 1);
                }
            }

            if (!string.IsNullOrWhiteSpace(errorMessage))
            {
                throw new EngineException(errorMessage);
            }

            if (!string.IsNullOrWhiteSpace(invalidMoveMessage))
            {
                throw new InvalidMoveException(invalidMoveMessage);
            }

            string firstLine = "";
            string lastLine  = "";

            if (null != outputLines && outputLines.Length > 0)
            {
                firstLine = outputLines[0];
                lastLine  = outputLines[outputLines.Length - 2]; // ignore the ok line
            }

            // Update other properties
            switch (command)
            {
            case EngineCommand.Board:
            case EngineCommand.NewGame:
            case EngineCommand.Play:
            case EngineCommand.Pass:
            case EngineCommand.Undo:
                Board = !string.IsNullOrWhiteSpace(firstLine) ? new ViewerBoard(firstLine) : null;
                break;

            case EngineCommand.ValidMoves:
                ValidMoves = !string.IsNullOrWhiteSpace(firstLine) ? new MoveSet(firstLine) : null;
                break;

            case EngineCommand.BestMove:
                // Update the target move (and potentially auto-play it)
                ProcessBestMove(lastLine, true);
                TryStopTimedCommand();
                break;

            case EngineCommand.History:
                BoardHistory = !string.IsNullOrWhiteSpace(firstLine) ? new BoardHistory(firstLine) : null;
                break;

            case EngineCommand.Options:
                string[] optionLines = new string[outputLines.Length - 1];
                Array.Copy(outputLines, optionLines, optionLines.Length);
                EngineOptions.ParseEngineOptionLines(optionLines);
                break;

            case EngineCommand.Info:
            case EngineCommand.Help:
            default:
                break;
            }
        }