public async Task <string> InsertEngine(QuantumChessEngine engine)
        {
            var game = new Game(ObjectId.GenerateNewId(), engine);
            await ActiveGames_.InsertOneAsync(ChessBsonSerializationUtils.Serialize(game));

            return(game.Id.ToString());
        }
        private async Task <dynamic> GameInfo(dynamic args, CancellationToken cancellation_token)
        {
            string             game_id = Request.Query["gameId"];
            QuantumChessEngine engine  = await WebAppManagers.DatabaseManager.RequestEngine(game_id);

            var response = new Model.InfoResponse();

            response.ActivePlayer = PlayerUtils.ToString(engine.ActivePlayer);
            response.GameState    = GameStateUtils.ToString(engine.GameState);
            response.Squares      = new Dictionary <String, Model.InfoResponse.SquareEncoded>();
            for (int i = 0; i < 64; i++)
            {
                Position     pos    = Position.FromIndex(i);
                QuantumPiece qpiece = engine.QuantumChessboard.GetQuantumPiece(pos);
                if (qpiece.Piece.HasValue)
                {
                    response.Squares[pos.ToString()] = new Model.InfoResponse.SquareEncoded()
                    {
                        Player      = PlayerUtils.ToString(qpiece.Piece.Value.Player),
                        Piece       = PieceTypeUtils.ToString(qpiece.Piece.Value.PieceType),
                        Probability = qpiece.Probability
                    };
                }
                else
                {
                    response.Squares[pos.ToString()] = null;
                }
            }

            response.LastMovePositions = engine.LastMovePositions.Select((pos) => pos.ToString().ToLower()).ToArray();

            return(Response.AsJson(response));
        }
 public static QuantumChessMove ReadMoveRepeated(QuantumChessEngine engine)
 {
     for (;;)
     {
         try {
             return(ReadMove(engine));
         } catch (MoveParseException e) {
             Console.WriteLine(e.Message);
         }
     }
 }
Beispiel #4
0
 public QuantumChessMove Parse(QuantumChessEngine engine)
 {
     if (MoveType == "ordinary")
     {
         Position source = Position.Parse(Source);
         Position target = Position.Parse(Target);
         Piece?   piece  = engine.QuantumChessboard.GetQuantumPiece(source).Piece;
         if (piece.HasValue)
         {
             return(new OrdinaryMove(piece.Value, source, target));
         }
         else
         {
             throw new MoveParseException($"No piece found at {source}");
         }
     }
     else if (MoveType == "quantum")
     {
         Position source = Position.Parse(Source);
         Position?middle = null;
         if (!String.IsNullOrEmpty(Middle))
         {
             middle = Position.Parse(Middle);
         }
         Position target = Position.Parse(Target);
         Piece?   piece  = engine.QuantumChessboard.GetQuantumPiece(source).Piece;
         if (piece.HasValue)
         {
             return(new QuantumMove(piece.Value, source, middle, target));
         }
         else
         {
             throw new MoveParseException($"No piece found at {source}");
         }
     }
     else if (MoveType == "capitulate")
     {
         return(new CapitulateMove(engine.ActivePlayer));
     }
     else if (MoveType == "castle_left")
     {
         return(new CastleMove(engine.ActivePlayer, CastleType.Left));
     }
     else if (MoveType == "castle_right")
     {
         return(new CastleMove(engine.ActivePlayer, CastleType.Right));
     }
     else
     {
         throw new MoveParseException($"Unsupported move type: {MoveType}");
     }
 }
Beispiel #5
0
        public static void Main(string[] args)
        {
            int cols = 8;

            if (args.Length >= 1)
            {
                cols = Convert.ToInt32(args[0]);
            }

            var engine = new QuantumChessEngine();

            for (;;)
            {
                Output.DisplayQuantumChessboard(engine.QuantumChessboard, cols);
                Console.WriteLine();

                for (;;)
                {
                    try {
                        QuantumChessMove move = Input.ReadMoveRepeated(engine);
                        engine.Submit(move);
                        break;
                    } catch (MoveParseException e) {
                        Console.WriteLine(e.Message);
                    } catch (MoveProcessException e) {
                        Console.WriteLine(e.Message);
                    }
                }

                switch (engine.GameState)
                {
                case GameState.WhiteVictory:
                    Console.WriteLine();
                    Console.WriteLine("White victory!");
                    return;

                case GameState.BlackVictory:
                    Console.WriteLine();
                    Console.WriteLine("Black victory!");
                    return;

                case GameState.Tie:
                    Console.WriteLine();
                    Console.WriteLine("Players are tied!");
                    return;
                }
            }
        }
        public static Game Deserialize(BsonDocument document)
        {
            ObjectId  id            = document["_id"].AsObjectId;
            Player    active_player = PlayerUtils.FromString(document["active_player"].AsString);
            GameState game_state    = GameStateUtils.FromString(document["game_state"].AsString);
            DateTime  creation_time = document["creation_time"].ToLocalTime();

            var harmonics = new List <QuantumHarmonic>();

            foreach (BsonValue bson_harmonic_val in document["harmonics"].AsBsonArray)
            {
                BsonDocument bson_harmonic   = bson_harmonic_val.AsBsonDocument;
                GameState    harmonic_state  = GameStateUtils.FromString(bson_harmonic["harmonic_state"].AsString);
                ulong        degeneracy      = Convert.ToUInt64(bson_harmonic["degeneracy"].AsInt64);
                BsonArray    bson_chessboard = bson_harmonic["chessboard"].AsBsonArray;
                var          chessboard      = Chessboard.EmptyChessboard(harmonic_state);
                for (int i = 0; i < 64; i++)
                {
                    BsonValue bson_square_val = bson_chessboard[i];
                    if (bson_square_val.IsBsonNull)
                    {
                        chessboard[i] = null;
                    }
                    else
                    {
                        BsonDocument bson_square   = bson_square_val.AsBsonDocument;
                        Player       square_player = PlayerUtils.FromString(bson_square["player"].AsString);
                        PieceType    square_piece  = PieceTypeUtils.FromString(bson_square["piece"].AsString);
                        chessboard[i] = new Piece(square_player, square_piece);
                    }
                }
                harmonics.Add(new QuantumHarmonic(chessboard, degeneracy));
            }
            var quantum_chessboard = new QuantumChessboard(harmonics, game_state);

            var last_move_positions = new List <Position>();

            foreach (BsonValue pos_val in document["last_move_positions"].AsBsonArray)
            {
                last_move_positions.Add(Position.Parse(pos_val.AsString));
            }

            var engine = new QuantumChessEngine(quantum_chessboard, active_player, creation_time, last_move_positions.ToArray());

            return(new Game(id, engine));
        }
        private async Task <dynamic> SubmitMove(dynamic args, CancellationToken cancellation_token)
        {
            Model.MoveRequest request = this.Bind <Model.MoveRequest>();
            try {
                QuantumChessEngine engine = await WebAppManagers.DatabaseManager.RequestEngine(request.GameId);

                QuantumChessMove move = request.Parse(engine);
                engine.Submit(move);
                await WebAppManagers.DatabaseManager.UpdateEngine(request.GameId, engine);

                return(new {
                    Success = true
                });
            } catch (QuantumChessException e) {
                return(new {
                    Success = false,
                    Message = e.Message
                });
            }
        }
        private async Task <dynamic> NewGame(dynamic args, CancellationToken cancellation_token)
        {
            if (WebAppConfig.Instance.Captcha.Enabled)
            {
                bool captcha_validated = await ValidateCaptchaResponse(Request.Query["captcha_response"]);

                if (!captcha_validated)
                {
                    return(500);
                }
            }
            var    engine  = new QuantumChessEngine();
            string game_id = await WebAppManagers.DatabaseManager.InsertEngine(engine);

            var new_game_response = new Model.NewGameResponse()
            {
                GameId = game_id
            };

            return(Response.AsJson(new_game_response));
        }
 public Game(ObjectId id, QuantumChessEngine engine)
 {
     Id     = id;
     Engine = engine;
 }
Beispiel #10
0
 public async Task UpdateEngine(string gameId, QuantumChessEngine engine)
 {
     var replacement = new Game(new ObjectId(gameId), engine);
     await ActiveGames_.FindOneAndReplaceAsync(FilterById(gameId), ChessBsonSerializationUtils.Serialize(replacement));
 }
        public static QuantumChessMove ReadMove(QuantumChessEngine engine)
        {
            switch (engine.ActivePlayer)
            {
            case Player.White:
                Console.Write("white> ");
                break;

            case Player.Black:
                Console.Write("black> ");
                break;
            }

            string move_str = Console.ReadLine();

            string capitulate_move_regex   = @"^(quit|exit|capitulate)$";
            string agree_to_tie_move_regex = @"^tie$";
            string ordinary_move_regex     = @"^([A-Za-z][1-8])\s*([A-Za-z][1-8])$";
            string quantum_move_regex      = @"^(?:q|Q|quantum)\s+([A-Za-z][1-8])\s*((?:[A-Za-z][1-8])?)\s*([A-Za-z][1-8])$";
            string castle_move_regex       = @"^castle (left|right)$";

            Match ordinary_match = Regex.Match(move_str, ordinary_move_regex);
            Match quantum_match  = Regex.Match(move_str, quantum_move_regex);
            Match castle_match   = Regex.Match(move_str, castle_move_regex);

            if (Regex.IsMatch(move_str, capitulate_move_regex))
            {
                return(new CapitulateMove(engine.ActivePlayer));
            }
            else if (Regex.IsMatch(move_str, agree_to_tie_move_regex))
            {
                return(new AgreeToTieMove(engine.ActivePlayer));
            }
            else if (ordinary_match.Success)
            {
                Position     source = Position.Parse(ordinary_match.Groups[1].Captures[0].Value);
                Position     target = Position.Parse(ordinary_match.Groups[2].Captures[0].Value);
                QuantumPiece qpiece = engine.QuantumChessboard.GetQuantumPiece(source);
                if (qpiece.Piece.HasValue)
                {
                    return(new OrdinaryMove(qpiece.Piece.Value, source, target));
                }
                else
                {
                    throw new MoveParseException($"No piece found at {source}");
                }
            }
            else if (quantum_match.Success)
            {
                Position source = Position.Parse(quantum_match.Groups[1].Captures[0].Value);
                Position?middle = null;
                if (quantum_match.Groups[2].Captures[0].Length > 0)
                {
                    middle = Position.Parse(quantum_match.Groups[2].Captures[0].Value);
                }
                Position     target = Position.Parse(quantum_match.Groups[3].Captures[0].Value);
                QuantumPiece qpiece = engine.QuantumChessboard.GetQuantumPiece(source);
                if (qpiece.Piece.HasValue)
                {
                    return(new QuantumMove(qpiece.Piece.Value, source, middle, target));
                }
                else
                {
                    throw new MoveParseException($"No piece found at {source}");
                }
            }
            else if (castle_match.Success)
            {
                string     castle_type_str = castle_match.Groups[1].Captures[0].Value;
                CastleType castle_type;
                if (castle_type_str == "left")
                {
                    castle_type = CastleType.Left;
                }
                else if (castle_type_str == "right")
                {
                    castle_type = CastleType.Right;
                }
                else
                {
                    throw new MoveParseException($"Unsupported castle type: {castle_type_str}");
                }
                return(new CastleMove(engine.ActivePlayer, castle_type));
            }
            else
            {
                throw new MoveParseException("Unable to parse move");
            }
        }