Esempio n. 1
0
        private void OnBoardUpdate()
        {
            TargetPiece = PieceName.INVALID;
            ValidMoves  = null;

            SendCommandInternal("history");

            if (GameInProgress)
            {
                SendCommandInternal("validmoves");
            }

            BoardUpdated?.Invoke(this, null);

            if (CurrentTurnIsEngineAI)
            {
                if (CurrentGameSettings.BestMoveType == BestMoveType.MaxDepth)
                {
                    SendCommandInternal("bestmove depth {0}", CurrentGameSettings.BestMoveMaxDepth);
                }
                else
                {
                    SendCommandInternal("bestmove time {0}", CurrentGameSettings.BestMoveMaxTime);
                }
            }
        }
Esempio n. 2
0
 protected virtual void OnUpdateBoard()
 {
     if (BoardUpdated != null)
     {
         BoardUpdated.Invoke(this);
     }
 }
Esempio n. 3
0
        public void MakeMove(Player player, int position)
        {
            /*
             * Position values start at zero, and end at eight
             * Zero being the top left, one being top middle, and so on.
             */


            // Raise our event
            BoardUpdated?.Invoke();
        }
Esempio n. 4
0
        private Task RefreshGame(string game)
        {
            Game = JsonConvert.DeserializeObject <Game>(game);

            //serialization reverses stack
            foreach (var n in Game.Board.Nodes)
            {
                n.Pieces = new Stack <Piece>(n.Pieces);
            }

            BoardUpdated?.Invoke(this, new EventArgs());
            return(Task.CompletedTask);
        }
Esempio n. 5
0
        public void PlacePieceAtPosition(Piece piece, int x, int y, bool initialize = false)
        {
            if (!initialize)
            {
                Tiles[piece.Y, piece.X].Piece = default;
            }

            piece.X = x;
            piece.Y = y;

            Tiles[y, x].Piece = piece;
            BoardUpdated.Invoke();
        }
Esempio n. 6
0
        public void UpdateBoard()
        {
            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    Game.Board.BoardMatrix[i, j] = Board.EMPTY;
                }
            }

            Game.Board.DefaultState();

            foreach (Player player in Game.Players)
            {
                foreach (Piece piece in player.Pieces)
                {
                    if (piece.Color == Color.White)
                    {
                        if (piece.IsQueen)
                        {
                            Game.Board.BoardMatrix[piece.Position.X, piece.Position.Y] = Board.WHITE_QUEEN;
                        }
                        else
                        {
                            Game.Board.BoardMatrix[piece.Position.X, piece.Position.Y] = Board.WHITE_PIECE;
                        }
                    }
                    if (piece.Color == Color.Blue)
                    {
                        if (piece.IsQueen)
                        {
                            Game.Board.BoardMatrix[piece.Position.X, piece.Position.Y] = Board.BLUE_QUEEN;
                        }
                        else
                        {
                            Game.Board.BoardMatrix[piece.Position.X, piece.Position.Y] = Board.BLUE_PIECE;
                        }
                    }
                }
            }
            BoardUpdated?.Invoke();
        }
Esempio n. 7
0
        private void SaveBoard()
        {
            Board board;

            if (_board != null)
            {
                _board.Title       = Title;
                _board.Description = Description;
                _board.ProjectId   = ProjectId;
                board = _board;
            }
            else
            {
                board = new Board
                {
                    Title       = Title,
                    Description = Description,
                    ProjectId   = ProjectId
                };
            }

            board.Color = Models.Util.ConvertBrushToByteArray(Background);
            BoardUpdated?.Invoke(this, DbManager.Instance.InsertOrUpdateEntity(board));
        }
        /// <summary>
        /// Update a position in the board shown on screen.
        /// </summary>
        /// <param name="move">
        /// Move performed, contains position to update.
        /// </param>
        /// <param name="result">
        /// Match result. If match is over and someone won, a line will be
        /// drawn over the final solution, given in the
        /// <paramref name="solution"/> parameter.
        /// </param>
        /// <param name="solution">The solution, in case someone won.</param>
        internal void UpdateBoard(Move move, Winner result, Pos[] solution)
        {
            // Update finished flag
            this.finished = result != Winner.None;

            // Is the screen board position empty and the game board has a
            // piece?
            if (pieces[move.row, move.col] == null &&
                board[move.row, move.col].HasValue)
            {
                // Then also place that piece in the screen board

                // Reference to the piece prefab
                GameObject piecePrefab;

                // The piece on the game board to also put in the screen board
                Piece piece = board[move.row, move.col].Value;

                // Determine the piece prefab to use based on the board piece
                if (piece.Is(PColor.White, PShape.Round))
                {
                    piecePrefab = whiteRoundPiece;
                }
                else if (piece.Is(PColor.White, PShape.Square))
                {
                    piecePrefab = whiteSquarePiece;
                }
                else if (piece.Is(PColor.Red, PShape.Round))
                {
                    piecePrefab = redRoundPiece;
                }
                else if (piece.Is(PColor.Red, PShape.Square))
                {
                    piecePrefab = redSquarePiece;
                }
                else
                {
                    throw new InvalidOperationException(
                              "Trying to instantiate an invalid piece");
                }

                // Instantiate the screen piece
                pieces[move.row, move.col] = Instantiate(
                    piecePrefab,
                    new Vector3(
                        // Horizontal position
                        leftPoleBase.x + move.col * distBtwPoles,
                        // Vertical position
                        leftPoleBase.y
                        + move.row * (totalHeightForPieces / board.rows)
                        + piecesLength / 2,
                        // Z-axis
                        2),
                    Quaternion.identity,
                    transform);

                // Correct scale of screen piece
                pieces[move.row, move.col].transform.localScale =
                    piecesScale * Vector3.one;

                // Is the column now full?
                if (board.IsColumnFull(move.col))
                {
                    // If so, close the arrow
                    uiArrows[move.col].Open = false;
                }

                // Animation last move
                StartCoroutine(AnimateLastMove(move));
            }
            // Or is the screen board position occupied while the game board
            // position is empty?
            else if (pieces[move.row, move.col] != null &&
                     !board[move.row, move.col].HasValue)
            {
                // In such case, destroy the screen board piece
                Destroy(pieces[move.row, move.col]);
                pieces[move.row, move.col] = null;

                // Open the arrow
                uiArrows[move.col].Open = true;
            }
            // Otherwise it's an impossible situation and we have a bug
            else
            {
                throw new InvalidOperationException(
                          "Board view representation not in sync with board model");
            }

            // Update previous player shape choice
            SelectShape(move.piece.color, move.piece.shape);

            // Disable or enable GUI stuff depending on who's playing next
            foreach (HumanMoveButton arrow in uiArrows)
            {
                arrow.gameObject.SetActive(
                    !finished && matchData.CurrentThinker is HumanThinker);
            }

            // Notify listeners that board was updated
            BoardUpdated.Invoke();

            // If match is finished and result is not a draw, draw a line
            // marking the solution
            if (result == Winner.Red || result == Winner.White)
            {
                // The variable where we'll place the line renderer
                LineRenderer linRend;

                // Game object which will hold the line renderer
                GameObject winLine = new GameObject("WinLine");

                // Determine initial and final line positions
                Vector3 start =
                    pieces[solution[0].row, solution[0].col].transform.position;
                Vector3 end = pieces[
                    solution[solution.Length - 1].row,
                    solution[solution.Length - 1].col]
                              .transform.position;
                start.z = -2;
                end.z   = -2;

                // Set the UI as the parent of the line game object
                winLine.transform.SetParent(transform);

                // Position the game object which will hold the line renderer
                winLine.transform.position = start;

                // Add the line renderer to the game object and retrieve it
                winLine.AddComponent <LineRenderer>();
                linRend = winLine.GetComponent <LineRenderer>();

                // Set line material (use same shader as used for sprites)
                linRend.material = new Material(Shader.Find("Sprites/Default"));

                // Set line width
                linRend.startWidth = 0.3f;
                linRend.endWidth   = 0.3f;

                // Set line color
                linRend.startColor = new Color(1f, 0f, 0f, 0.75f);
                linRend.endColor   = new Color(1f, 0f, 0f, 0.75f);

                // Set line position
                linRend.SetPosition(0, start);
                linRend.SetPosition(1, end);

                // Specify that positions are in world space
                linRend.useWorldSpace = true;

                // Make sure line appears in the correct sorting order
                linRend.sortingOrder = 5;
            }
        }
Esempio n. 9
0
 public void When(BoardUpdated boardUpdated)
 {
 }
Esempio n. 10
0
 protected virtual void OnBoardUpdated(EventArgs eventArgs)
 {
     BoardUpdated?.Invoke(this, eventArgs);
 }
Esempio n. 11
0
 public void SetUpGame()
 {
     SetUpPieces();
     Game.SetDefaultState();
     BoardUpdated?.Invoke();
 }
Esempio n. 12
0
        private void gameStateStreamHandler()
        {
            client.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {authToken}");
            client.OpenReadCompleted += (sender, e) => {
                StreamReader reader = new StreamReader(e.Result);
                while (!reader.EndOfStream)
                {
                    String tmp = reader.ReadLine();
                    if (tmp != "")
                    {
                        Console.WriteLine(tmp);
                        JObject json    = JObject.Parse(tmp);
                        String  msgType = (!json.ContainsKey("type")) ? null : $"{(String)json["type"]}";

                        try
                        {
                            if (msgType == "gameState")
                            {
                                this.uciParser.executeUCIOperation($"position startpos moves {(String)json["moves"]}");
                                int moveCount = ((String)json["moves"]).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Count();
                                playerTurn = (moveCount % 2 == 0) ? ChessmanColor.white : ChessmanColor.black;

                                if (moveCount > 0)
                                {
                                    lastMove = new Move(((String)json["moves"]).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[moveCount - 1], gameBoard, postMove: true);
                                }
                                whiteClockTime = int.Parse((String)(json["wtime"]));
                                blackClockTime = int.Parse((String)(json["btime"]));
                                if (clockStateUpdated != null)
                                {
                                    clockStateUpdated(this, ChessmanColor.white, whiteClockTime);
                                    clockStateUpdated(this, ChessmanColor.black, blackClockTime);
                                }
                                if (json.ContainsKey("status"))
                                {
                                    GameStatus sts = GameStatus.unknown;
                                    if (Enum.TryParse(((String)json["status"]), true, out sts))
                                    {
                                        gameStatus = sts;
                                    }
                                    else
                                    {
                                        gameStatus = GameStatus.unknown;
                                    }
                                }
                                if (json.ContainsKey("winner"))
                                {
                                    winner = (((String)json["winner"]) == "white") ? ChessmanColor.white : ChessmanColor.black;
                                    handleGameOver();
                                }
                            }
                            else if (msgType == "gameFull")
                            {
                                // Is Inital State Message
                                whiteClockTime = int.Parse((String)(((JObject)(json["state"]))["wtime"]));
                                blackClockTime = int.Parse((String)(((JObject)(json["state"]))["btime"]));
                                int moveCount = ((String)(((JObject)(json["state"]))["moves"])).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Count();
                                if (moveCount > 0)
                                {
                                    // Update Game Board Initial State
                                    this.uciParser.executeUCIOperation($"position startpos moves { ((String)(((JObject)(json["state"]))["moves"]))}");
                                    lastMove = new Move(((String)(((JObject)(json["state"]))["moves"])).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[moveCount - 1], gameBoard, postMove: true);
                                }

                                playerTurn = (moveCount % 2 == 0) ? ChessmanColor.white : ChessmanColor.black;

                                if (clockStateUpdated != null)
                                {
                                    clockStateUpdated(this, ChessmanColor.white, whiteClockTime);
                                    clockStateUpdated(this, ChessmanColor.black, blackClockTime);
                                }

                                if (json.ContainsKey("status"))
                                {
                                    GameStatus sts = GameStatus.unknown;
                                    if (Enum.TryParse(((String)(((JObject)(json["state"]))["status"])), true, out sts))
                                    {
                                        gameStatus = sts;
                                    }
                                    else
                                    {
                                        gameStatus = GameStatus.unknown;
                                    }
                                }
                                if (json.ContainsKey("winner"))
                                {
                                    winner = (((String)json["winner"]) == "white") ? ChessmanColor.white : ChessmanColor.black;
                                    handleGameOver();
                                }
                            }

                            clockUpdateTimer.Start();
                            clockUpdateTimer.Enabled = true;
                        }
                        catch
                        {
                        }


                        // Fire Event for UI to refresh Display
                        if (BoardUpdated != null)
                        {
                            BoardUpdated.Invoke();
                        }
                    }
                }

                reader.Close();
            };
            client.OpenReadAsync(new Uri(Helper.apiBaseEndpoint + $"/bot/game/stream/{fullId}"));
        }
        private void Socket_OnMessage(object sender, MessageEventArgs e)
        {
            if (!ShouldExit)
            {
                var watch    = System.Diagnostics.Stopwatch.StartNew();
                var response = e.Data;

                if (!response.StartsWith(ResponsePrefix))
                {
                    Console.WriteLine("Something strange is happening on the server... Response:\n{0}", response);
                    ShouldExit = true;
                }
                else
                {
                    var boardString = response.Substring(ResponsePrefix.Length);
                    var board       = new Board(boardString);
                    Board = board;
                    if (FullBoard.CurrentLevel == 0)
                    {
                        FullBoard.CurrentLevel = board.CurrentLevel;
                    }

                    if (FullBoard.CurrentLevel != board.CurrentLevel)
                    {
                        FullBoard = new Board(Constants.FullBoardSize);
                        if (Directory.Exists(Constants.CacheFolder))
                        {
                            var levelCacheFile = $"{Constants.CacheFolder}/{board.CurrentLevel}.dat";
                            if (File.Exists(levelCacheFile))
                            {
                                using (FileStream fs = new FileStream(levelCacheFile, FileMode.OpenOrCreate))
                                {
                                    FullBoard = (Board)formatter.Deserialize(fs);
                                }
                            }
                        }
                        FullBoard.CurrentLevel = board.CurrentLevel;
                    }
                    for (int layer = 0; layer < FullBoard.Field.GetLength(0); layer++)
                    {
                        for (int x = 0; x < FullBoard.Size; x++)
                        {
                            for (int y = 0; y < FullBoard.Size; y++)
                            {
                                if (FullBoard.IsAt(layer, x, y,
                                                   Element.ROBO_OTHER, Element.ROBO_OTHER_FLYING, Element.ROBO_OTHER_LASER, Element.ROBO_OTHER_FALLING,
                                                   Element.LASER_DOWN, Element.LASER_UP, Element.LASER_LEFT, Element.LASER_RIGHT, Element.ZOMBIE_DIE, Element.FEMALE_ZOMBIE, Element.MALE_ZOMBIE,
                                                   Element.AIM, Element.PATH, Element.GOLD))
                                {
                                    FullBoard.Field[layer, x, y] = (char)Element.EMPTY;
                                }
                            }
                        }
                    }
                    for (int layer = 0; layer < board.Field.GetLength(0); layer++)
                    {
                        for (int x = 0; x < board.Size; x++)
                        {
                            for (int y = 0; y < board.Size; y++)
                            {
                                var absolutePoint = new Point(x, y).RelativeToAbsolute(board.Size, board.Offset);
                                FullBoard.Field[layer, absolutePoint.X, absolutePoint.Y] = board.Field[layer, x, y];
                            }
                        }
                    }

                    if (board.HeroPosition.Y <= 1)
                    {
                        for (int x = 0; x < board.Size; x++)
                        {
                            var absolutePoint = new Point(x, -1).RelativeToAbsolute(board.Size, board.Offset);
                            FullBoard.Field[0, absolutePoint.X, absolutePoint.Y] = (char)Element.WALL_FRONT;
                        }
                    }

                    if (board.HeroPosition.X >= board.Size - 2)
                    {
                        for (int y = 0; y < board.Size; y++)
                        {
                            var absolutePoint = new Point(board.Size, y).RelativeToAbsolute(board.Size, board.Offset);
                            FullBoard.Field[0, absolutePoint.X, absolutePoint.Y] = (char)Element.WALL_FRONT;
                        }
                    }
                    FullBoard.HeroPosition = board.HeroPosition.RelativeToAbsolute(board.Size, board.Offset);

                    if (!Directory.Exists(Constants.CacheFolder))
                    {
                        Directory.CreateDirectory(Constants.CacheFolder);
                    }

                    using (FileStream fs = new FileStream($"Cache/{FullBoard.CurrentLevel}.dat", FileMode.OpenOrCreate))
                    {
                        formatter.Serialize(fs, FullBoard);
                    }
                    //Just print current state (gameBoard) to console

                    /*Console.Clear();
                     * Console.SetCursorPosition(0, 0);*/
                    var action = "";
                    var time   = "";
                    try
                    {
                        turnCounter++;
                        action = WhatToDo(board).ToString();
                        time   = $"Execution Time: {watch.ElapsedMilliseconds} ms";
                    }
                    catch { }
                    if (action.Contains("ACT(3)"))
                    {
                        Static.TurnsWithoutFire            = 0;
                        Static.PerkCooldownDeathRay        = 0;
                        Static.PerkCooldownUnstopableLaser = 0;
                    }
                    else
                    {
                        Static.TurnsWithoutFire++;
                    }
                    var str = new StringBuilder();

                    str.AppendLine(time);
                    str.AppendLine("Answer: " + action);
                    str.AppendLine("Gold collected: " + goldCollected);
                    str.AppendLine("Turns without fire: " + Static.TurnsWithoutFire);
                    str.AppendLine("DeathRay Perk Cooldown: " + Static.PerkCooldownDeathRay);
                    str.AppendLine("Unlimited Fire Perk Cooldown: " + Static.PerkCooldownUnlimitedFire);
                    str.AppendLine("Unstopable Laser Perk Cooldown: " + Static.PerkCooldownUnstopableLaser);
                    str.AppendLine(board.ToString());
                    str.AppendLine(FullBoard.ToString());
                    if (PrevBoard != null)
                    {
                        str.AppendLine(PrevFullBoard.ToString());
                    }
                    if (!action.IsNullOrEmpty())
                    {
                        prevState = str.ToString();
                    }

                    for (int layer = 0; layer < board.Field.GetLength(0); layer++)
                    {
                        for (int x = 0; x < board.Size; x++)
                        {
                            for (int y = 0; y < board.Size; y++)
                            {
                                PrevBoard.Field[layer, x, y] = board.Field[layer, x, y];
                            }
                        }
                    }

                    for (int layer = 0; layer < FullBoard.Field.GetLength(0); layer++)
                    {
                        for (int x = 0; x < FullBoard.Size; x++)
                        {
                            for (int y = 0; y < FullBoard.Size; y++)
                            {
                                PrevFullBoard.Field[layer, x, y] = FullBoard.Field[layer, x, y];
                            }
                        }
                    }

                    /*Console.WriteLine(str.ToString());
                     * Console.SetCursorPosition(0, 0);*/
                    ((WebSocket)sender).Send(action);
                    BoardUpdated?.Invoke(board, str.ToString());
                }
            }
        }