Esempio n. 1
0
    public void OnPieceRemoved(Piece piece)
    {
        ChessPlayer pieceOwner = (piece.team == TeamColor.White) ? whitePlayer : blackPlayer;

        pieceOwner.RemovePiece(piece);
        Destroy(piece.gameObject);
        audioOutput.PlayCaptureSound();
    }
Esempio n. 2
0
        void demandProcesses(ChessPlayer player)
        {
            setItems(false);
            var jobj = new JObject();

            jobj["id"] = player.Id;
            StartForm.Send(new Packet(PacketId.RequestProcesses, jobj));
            resetTimer.Start();
        }
Esempio n. 3
0
 public void StartNewGame()
 {
     SetGameState(GameState.Init);
     board.SetDependencies(this);
     CreatePiecesFromLayout(startingBoardLayout);
     activePlayer = whitePlayer;
     GenerateAllPossiblePlayerMoves(activePlayer);
     SetGameState(GameState.Play);
 }
Esempio n. 4
0
 public void StartNewGame()
 {
     UIManager.OnGameStarted();
     SetGameState(GameState.Init);
     CreatePiecesFromLayout(startingBoardLayout);
     activePlayer = whitePlayer;
     GenerateAllPossiblePlayerMoves(activePlayer);
     TryToStartThisGame();
 }
Esempio n. 5
0
    private int MiniMax(ChessGridInfo grid, ChessPlayer player, ChessPlayer enemy, bool isMaximazing, int depth, int alpha, int beta)
    {
        player.GenerateAllPossibleMoves(grid, true, true);
        enemy.GenerateAllPossibleMoves(grid, false, false);

        if (depth == 0 || !player.HasAnyMoves())
        {
            return(EvaluateGrid(grid, player, enemy));
        }

        List <Move> possibleMoves = OrderMoves(player.AllPossibleMoves, enemy.AllPossibleMoves);

        if (isMaximazing)
        {
            int bestScore = int.MinValue;

            for (int i = 0; i < possibleMoves.Count; i++)
            {
                grid.MakeMove(possibleMoves[i], player, enemy, true);

                int score = MiniMax(grid, enemy, player, !isMaximazing, depth - 1, alpha, beta);
                bestScore = Mathf.Max(score, bestScore);
                alpha     = Mathf.Max(alpha, bestScore);

                grid.UndoMove(player, enemy);

                if (alpha <= beta)
                {
                    break;
                }
            }

            return(bestScore);
        }
        else
        {
            int bestScore = int.MaxValue;

            for (int i = 0; i < possibleMoves.Count; i++)
            {
                grid.MakeMove(possibleMoves[i], player, enemy, true);

                int score = MiniMax(grid, enemy, player, !isMaximazing, depth - 1, alpha, beta);
                bestScore = Mathf.Min(score, bestScore);
                beta      = Mathf.Min(beta, bestScore);

                grid.UndoMove(player, enemy);

                if (alpha <= beta)
                {
                    break;
                }
            }

            return(bestScore);
        }
    }
Esempio n. 6
0
        private Position FindKing(ChessRepresentation representation, ChessPlayer player)
        {
            var position = Positions.PositionList
                           .Where(x => representation[x] != null)
                           .Where(x => representation[x].Owner == player)
                           .FirstOrDefault(x => representation[x].Kind == PieceKind.King);

            return(position);
        }
    public void NextPlayer()
    {
        var tempPlayer = _currentPlayer;

        _currentPlayer = _otherPlayer;
        _otherPlayer   = tempPlayer;

        // Update the turn UI
        m_TurnText.text = _currentPlayer.name;
    }
Esempio n. 8
0
    private void InitializePlayers()
    {
        IInputHandler whitePlayerInput = ChessGameSettings.WhitePlayerUsesAi ? new AiInput() as IInputHandler : new PlayerInputHandler();
        IInputHandler blackPlayerInput = ChessGameSettings.BlackPlayerUsesAi ? new AiInput() as IInputHandler : new PlayerInputHandler();

        whitePlayer = new ChessPlayer(whitePlayerInput, TeamColor.White);
        blackPlayer = new ChessPlayer(blackPlayerInput, TeamColor.Black);

        ActivePlayer = whitePlayer;
    }
Esempio n. 9
0
        void LogEntry(IInvite invite, ChessPlayer player)
        {
            EmbedBuilder builder = new EmbedBuilder();

            builder.Title = "Invite Created";
            builder.WithCurrentTimestamp();
            builder.AddField("For", player.Name, true);
            builder.AddField("Code", invite.Code, true);
            LogChnl(builder, SystemChannel);
        }
Esempio n. 10
0
 protected ChessPiece(ChessMatchState chessGameState, ChessPlayer color, Chessboard chessboard)
 {
     m_chessGameState = chessGameState;
     m_currentRow     = -1;
     m_currentColumn  = -1;
     m_color          = color;
     m_chessboard     = chessboard;
     m_selected       = false;
     m_firstMove      = true;
 }
Esempio n. 11
0
        void demandScreen(ChessPlayer player)
        {
            if (player == null)
            {
                return;
            }
            var jobj = new JObject();

            jobj["id"] = player.Id;
            StartForm.Send(new Packet(PacketId.RequestScreen, jobj));
        }
Esempio n. 12
0
    public void SetUpPiece(ChessPlayer player, pieceType type)
    {
        this.player = player;

        pieceName    = type.pieceName;
        infiniteMove = type.moveStyles.Item1;
        anyMove      = type.moveStyles.Item2;
        ghostMove    = type.moveStyles.Item3;
        SetMoveAttackVectors(type);
        SetSprite(pieceName);
    }
Esempio n. 13
0
        private ChessPlayer GetOpponent(ChessPlayer player)
        {
            switch (player)
            {
            case ChessPlayer.Black: return(ChessPlayer.White);

            case ChessPlayer.White: return(ChessPlayer.Black);

            default: throw new ArgumentOutOfRangeException();
            }
        }
Esempio n. 14
0
        public virtual bool IsStalemated(ChessPlayer player)
        {
            Cache <bool> cache = player == ChessPlayer.White ? stalematedCacheWhite : stalematedCacheBlack;

            if (cache.CachedAt == Moves.Count)
            {
                return(cache.Value);
            }

            return(cache.UpdateCache(WhoseTurn == player && !IsInCheck(player) && !HasAnyValidMoves(player), Moves.Count));
        }
Esempio n. 15
0
 protected bool doesHavePerm(ChessPerm perm, ChessPlayer user)
 {
     if (perm == ChessPerm.Player)
     {
         return(true);
     }
     if (user == null)
     {
         return(false);
     }
     return(user.Permission.HasFlag(perm));
 }
Esempio n. 16
0
        public List <ChessGame> BuildEntries(ChessPlayer player, ChessDbContext db, DateTime date, bool ignoreOnline)
        {
            var games = db.GetGamesOnDate(player.Id, date);

            if (ignoreOnline)
            {
                return(games
                       .Where(x => x.ApprovalNeeded == ApprovedBy.None || x.ApprovalNeeded == ApprovedBy.Moderator)
                       .ToList());
            }
            return(games.ToList());
        }
Esempio n. 17
0
    public bool CheckIfMoveIsValid(ChessGridInfo grid, ChessPlayer player, ChessPlayer enemy, Move pieceMove)
    {
        grid.MakeMove(pieceMove, player, enemy, true);

        enemy.GenerateAllPossibleMoves(grid, false, false);
        Piece king        = player.FindFirstPieceOfType(PieceType.King);
        bool  isMoveValid = !(enemy.IsFieldUnderAttack(king.SquareIndex));

        grid.UndoMove(player, enemy);

        return(isMoveValid);
    }
Esempio n. 18
0
    public static void CreatePiecePrefabAndInitialize(Vector2Int squareIndex, PieceType pieceType, TeamColor teamColor,
                                                      ChessGridInfo grid, ChessPlayer player)
    {
        Piece       newPiece = CreateChessPiece(squareIndex, pieceType, grid, player);
        PieceEntity entity   = PieceFactory.CreatePiecePrefab(pieceType.ToString()).GetComponent <PieceEntity>();

        IMovable pieceMovementType = PieceFactory.GetMovementType(pieceType.ToString()) == MovementType.MovesInLine ?
                                     new MoveInLine() as IMovable : new Jump();

        newPiece.SetData(squareIndex, squareIndex, pieceType, teamColor, false, pieceMovementType, entity);
        player.AddPiece(newPiece);
    }
Esempio n. 19
0
        private int GetNumberOfMoves(ChessPlayer player, IEnumerable <DbBaseMove> history)
        {
            var half = history.Count() / 2.0m;

            switch (player)
            {
            case ChessPlayer.White: return((int)Math.Floor(half));

            case ChessPlayer.Black: return((int)Math.Ceiling(half));

            default: throw new ArgumentOutOfRangeException(nameof(player), player, null);
            }
        }
Esempio n. 20
0
 private void PrintDebugDataForPlayer(ChessPlayer player, StringBuilder debugString)
 {
     debugString.AppendLine("Player: " + player + "[" + player.pieceColor + "]");
     debugString.AppendLine("  ID: " + player.Id.ToString());
     debugString.AppendLine("  IsMyTurn: " + player.IsMyTurn);
     debugString.AppendLine("  Clock: " + player.Clock.LeftTime);
     debugString.AppendLine("  LastTurnStarted: " + player.Clock.LastTurnStartAt);
     foreach (ChessPiece myPiece in player.MyPiecesInBoard)
     {
         debugString.AppendLine("  Piece: " + myPiece.ToString() + myPiece.BoardPosition);
         debugString.AppendLine("     id: " + myPiece.PieceId);
         debugString.AppendLine("  Init P: " + myPiece.InitialPosition.ToString());
     }
 }
Esempio n. 21
0
        private static Position CalculateFrom(ChessPlayer owner)
        {
            switch (owner)
            {
            case ChessPlayer.White:
                return(Positions.E1);

            case ChessPlayer.Black:
                return(Positions.E8);

            default:
                throw new ArgumentOutOfRangeException(nameof(owner), owner, null);
            }
        }
Esempio n. 22
0
    public void Resign()
    {
        if (!hasGameEnded)
        {
            ChessPlayer me              = GetCurrentlyActivePlayer();
            string      myColorTag      = me.GetMyChosenColor();
            string      myEnemyColorTag = me.GetMyEnemyColorTag();

            hasGameEnded = true;
            myScoreSheet.SetNewMove("", "", "", "", currentRound, false, false, false, false, false, false, myEnemyColorTag, false, hasGameEnded, true, false);
            Debug.Log($"{myColorTag} colored player resigned. {myEnemyColorTag} colored player won.");
            terminationString = "won by resignation";
        }
    }
Esempio n. 23
0
 public Move(string originalPosition, string newPosition, ChessPlayer player, char?promotion)
 {
     OriginalPosition = new BoardPosition(originalPosition);
     NewPosition      = new BoardPosition(newPosition);
     Player           = player;
     if (promotion.HasValue)
     {
         Promotion = char.ToUpper(promotion.Value);
     }
     else
     {
         Promotion = null;
     }
 }
Esempio n. 24
0
 public Move(BoardPosition originalPosition, BoardPosition newPosition, ChessPlayer player, char?promotion)
 {
     OriginalPosition = originalPosition;
     NewPosition      = newPosition;
     Player           = player;
     if (promotion.HasValue)
     {
         Promotion = char.ToUpper(promotion.Value);
     }
     else
     {
         Promotion = null;
     }
 }
Esempio n. 25
0
    public override void GeneratePossibleMoves(ChessGridInfo grid, ChessGridInfo gridCopy, ChessPlayer playerCopy,
                                               ChessPlayer enemyCopy, bool checkMovesValidity, bool checkSpecialMoves)
    {
        AvailableMoves.Clear();
        Vector2Int newSquare = Vector2Int.zero;

        for (int i = 0; i < possibleDirections.GetLength(0); i++)
        {
            if (i == 1 && MovedFirstTime)
            {
                break;
            }

            int newX = SquareIndex.x + possibleDirections[i, 0];
            int newY = SquareIndex.y + possibleDirections[i, 1];

            newSquare.Set(newX, newY);

            if (grid.CheckIfSquareIndexIsValid(newSquare))
            {
                Piece piece = grid.GetPieceOnSquareIndex(newSquare);
                Move  move  = CheckPromotionFlag(newSquare, piece);

                if (checkMovesValidity && piece == null)
                {
                    Piece attackedPieceCopy = piece == null ? null : gridCopy.GetPieceOnSquareIndex(piece.SquareIndex);
                    Move  moveCopy          = new Move(gridCopy.GetPieceOnSquareIndex(SquareIndex), newSquare, attackedPieceCopy, move.PromotionFlag);
                    bool  areMovesValid     = CheckIfMoveIsValid(gridCopy, playerCopy, enemyCopy, moveCopy);

                    if (!areMovesValid)
                    {
                        continue;
                    }
                }

                if (piece == null)
                {
                    AvailableMoves.Add(move);
                }
                else
                {
                    break;
                }
            }
        }

        PieceAttack(grid, gridCopy, playerCopy, enemyCopy, checkMovesValidity);
        EnPassant(grid, gridCopy, playerCopy, enemyCopy, checkMovesValidity);
    }
Esempio n. 26
0
        void makeWin(ChessPlayer winner)
        {
            if (MessageBox.Show($"Are you sure you want to make {(winner?.Name ?? "a draw")} win?", "Winner", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                != DialogResult.Yes)
            {
                return;
            }
            setItems(false);
            int id   = winner?.Id ?? -1;
            var jobj = new JObject();

            jobj["id"] = id;
            StartForm.Send(new Packet(PacketId.RequestGameEnd, jobj));
            resetTimer.Start();
        }
Esempio n. 27
0
    public void CreatePieceAndInitialize(Vector2Int squareCoords, TeamColor team, string type)
    {
        Piece newPiece = pieceCreator.CreatePiece(type).GetComponent <Piece>();

        newPiece.SetData(squareCoords, team, board);

        Material teamMaterial = pieceCreator.GetTeamMaterial(team);

        newPiece.SetMaterial(teamMaterial);
        board.SetPieceOnBoard(squareCoords, newPiece);

        ChessPlayer currentPlayer = team == TeamColor.White ? whitePlayer : blackPlayer;

        currentPlayer.AddPiece(newPiece);
    }
Esempio n. 28
0
    private void _init(ChessPlayer p)
    {
        if (p == ChessPlayer.Unkown)
        {
            return;
        }
        int AssistIndex1 = 4, AssistIndex2 = 4, AssistIndex3 = 5, AssistIndex4 = 6;

        Chess[] AssistChessArray =
        {
            new Chess(p, ChessKind.Ju,      null),
            new Chess(p, ChessKind.Ma,      null),
            new Chess(p, ChessKind.Xiang,   null),
            new Chess(p, ChessKind.Shi,     null),
            new Chess(p, ChessKind.King,    null),
            new Chess(p, ChessKind.Pao,     null),
            new Chess(p, ChessKind.Soldier, null),
        };
        // 车马炮象士将
        int row1 = p == ChessPlayer.Red ? 0 : kRow - 1;

        for (int i = 0; i < AssistIndex1; i++)
        {
            this.board[i][row1] = AssistChessArray[i];
            chessPieces.Add(Chess.remake(AssistChessArray[i], new Location(i, row1)));
            this.board[kColumn - 1 - i][row1] = AssistChessArray[i];
            chessPieces.Add(Chess.remake(AssistChessArray[i], new Location(kColumn - 1 - i, row1)));
        }
        this.board[(kColumn - 1) / 2][row1] = AssistChessArray[AssistIndex2];
        chessPieces.Add(Chess.remake(AssistChessArray[AssistIndex2], new Location((kColumn - 1) / 2, row1)));
        // 炮
        int row2 = p == ChessPlayer.Red ? 2 : kRow - 3;

        this.board[1][row2]           = AssistChessArray[AssistIndex3];
        this.board[kColumn - 2][row2] = AssistChessArray[AssistIndex3];
        // 卒
        int  row3 = p == ChessPlayer.Red ? 3 : kRow - 4;
        bool set  = true;

        for (int i = 0; i < kColumn; i++)
        {
            if (set)
            {
                this.board[i][row3] = AssistChessArray[AssistIndex4];
            }
            set = !set;
        }
    }
Esempio n. 29
0
        public bool TrySelect(ChessPlayer player, ChessboardTile tile)
        {
            int row, column;

            ChessboardTileHelper.TileToIndexes(tile, out row, out column);

            if (m_board[row, column] != null && m_board[row, column].Color == player)
            {
                m_board[row, column].Selected = true;
                m_selectedRow    = row;
                m_selectedColumn = column;
                return(true);
            }

            return(false);
        }
Esempio n. 30
0
        private void StartStopAlgorithmProgressbar(ChessPlayer player, bool start)
        {
            switch (player)
            {
            case ChessPlayer.White:
                InvokeIfRequired(progressbarAlgorithmLeft, () => progressbarAlgorithmLeft.MarqueeAnimationSpeed = start ? 10 : 0);
                break;

            case ChessPlayer.Black:
                InvokeIfRequired(progressbarAlgorithmRight, () => progressbarAlgorithmRight.MarqueeAnimationSpeed = start ? 10 : 0);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(player), player, null);
            }
        }