Exemple #1
0
    public void removeChess(int index)
    {
        int playerKey = (redTurn ? 1 : 2);

        if (countdown >= dropTime && BoardUtility.canRemove(gameGrid, index, playerKey))
        {
            for (int i = 0; i < all_chess.Count; i++)
            {
                if (all_chess[i].x == index && all_chess[i].y != 5)
                {
                    all_chess[i].x++;
                }
                else if (all_chess[i].x == index && all_chess[i].y == 5)
                {
                    Chess chs = all_chess[i];
                    all_chess.Remove(chs);
                    Destroy(chs.gameObject);
                }
            }

            redTurn = !redTurn;

            //remove it from the gamegrid
            gameGrid = BoardUtility.removeFromGrid(gameGrid, index, 5);

            checkWinner();
        }
    }
    public override UnitState HandleInput(Controller controller)
    {
        var swappedAbility = SwapActiveAbility(controller);

        if (swappedAbility != null)
        {
            BoardVisuals.RemoveTilesFromHighlightsByUnit(Owner);
            CleanIndicator();
            return(swappedAbility);
        }

        List <PathfindingData> tilesInRange = GetTilesInRange();

        // handling a special case where the targetting is programmatic.
        // will ecentually need to accomodate for this in a more robust way using OOP
        if (abilityComponent.CurrentAbility.AutoTargets)
        {
            PathfindingData autoTarget = tilesInRange.FirstOrDefault(
                element => element.tile.IsOccupied() && element.tile.OccupiedBy.GetComponent <Monster> ()
                );

            if (autoTarget == null)
            {
                AudioComponent.PlaySound(Sounds.ERROR);
                onAbilityCanceled();
                return(new PlayerIdleState(Owner));
            }

            if (Owner.EnergyComponent.AdjustEnergy(-abilityComponent.CurrentAbility.EnergyCost) &&
                abilityComponent.PrepAbility(tilesInRange, autoTarget))
            {
                onAbilityCommited(Owner, abilityComponent.IndexOfCurrentAbility());
                return(new PlayerActingState(Owner, tilesInRange, autoTarget));
            }
        }

        Point mousePosition = BoardUtility.mousePosFromScreenPoint();

        HighlightTiles(tilesInRange, mousePosition);

        // user clicks on a walkable tile which is in range....
        if (controller.DetectInputFor(ControlTypes.CONFIRM))
        {
            PathfindingData selectedTarget = tilesInRange.Find(
                element => element.tile.Position == mousePosition
                );

            // transition to acting state if it's a valid selection
            // and we successfully prep our ability for use
            bool targetIsValid = selectedTarget != null && selectedTarget.tile.isWalkable;
            if (targetIsValid && Owner.EnergyComponent.AdjustEnergy(-abilityComponent.CurrentAbility.EnergyCost) &&
                abilityComponent.PrepAbility(tilesInRange, selectedTarget))
            {
                onAbilityCommited(Owner, abilityComponent.IndexOfCurrentAbility());
                return(new PlayerActingState(Owner, tilesInRange, selectedTarget));
            }
        }

        return(null);
    }
Exemple #3
0
    public void spawnChess(int index)
    {
        if (countdown >= dropTime && BoardUtility.canInsert(gameGrid, index))
        {
            countdown = 0;
            int chessKey = 0;
            //get the position to insert
            Vector2 pos = BoardUtility.insertingPosition(gameGrid, index);
            Chess   chs;
            if (redTurn)
            {
                chs = Instantiate(redChess) as Chess;
                chs.gameObject.transform.position = spawnPosition[index].position;
                chessKey = 1;
            }
            else
            {
                chs = Instantiate(yellowChess) as Chess;
                chs.gameObject.transform.position = spawnPosition[index].position;
                chessKey = 2;
            }
            chs.x = (int)pos.x;
            chs.y = (int)pos.y;
            all_chess.Add(chs);

            redTurn = !redTurn;

            //put it into the gamegrid
            gameGrid = BoardUtility.insertToGrid(gameGrid, pos, chessKey);

            checkWinner();
        }
    }
 public static int randomMove(int[] gameGrid, int key, bool allowRemove)
 {
     if (!allowRemove)
     {
         return(Random.Range(0, 7));
     }
     return(Random.Range(0, 7 + BoardUtility.numOfRemove(gameGrid, key)));
 }
Exemple #5
0
 public void clearBoard()
 {
     while (all_chess.Count != 0)
     {
         Chess chs = all_chess[0];
         all_chess.Remove(chs);
         Destroy(chs.gameObject);
     }
     BoardUtility.clearBoard(gameGrid);
 }
Exemple #6
0
        //Event Handler
        private async void _GetMove(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            GamePlayUtility.MakeMove(_CurrentTurn, btn);
            await BoardUtility.TryFlipEnemyDisks(_Board, _CurrentTurn, _Enemy(), _Index(btn));

            _UpdateDisplayScore();
            await _NextTurn();
        }
    private void queryMatchState()
    {
        // Read match history
        // Query more detail state about the match
        App.Bc.AsyncMatchService
        .ReadMatch(App.OwnerId, App.MatchId, (response, cbObject) =>
        {
            var match = App.CurrentMatch;
            var data  = JsonMapper.ToObject(response)["data"];

            int newVersion = int.Parse(data["version"].ToString());

            if (App.MatchVersion + 1 < (ulong)newVersion)
            {
                App.MatchVersion = (ulong)newVersion;

                // Setup a couple stuff into our TicTacToe scene
                App.BoardState  = (string)data["matchState"]["board"];
                App.PlayerInfoX = match.playerXInfo;
                App.PlayerInfoO = match.playerOInfo;
                App.WhosTurn    = match.yourToken == "X" ? App.PlayerInfoX : match.playerOInfo;
                App.OwnerId     = match.ownerId;
                App.MatchId     = match.matchId;

                //Checking if game is completed to assign winner and loser info
                BuildBoardFromState(App.BoardState);
                App.Winner = BoardUtility.CheckForWinner();
                if (App.Winner != 0)
                {
                    Transform[] toCheckDisplay = { DuringGameDisplay.transform, AfterGameDisplay.transform };
                    Transform statusOverlay    = toCheckDisplay[1].Find("StatusOverlay");
                    TextMeshProUGUI status     = statusOverlay.Find("StatusText").GetComponent <TextMeshProUGUI>();
                    if (App.Winner == 1)
                    {
                        status.text    = Truncate(App.PlayerInfoX.PlayerName, MAX_CHARS) + " Wins!";
                        App.WinnerInfo = App.PlayerInfoX;
                        App.LoserInfo  = App.PlayerInfoO;
                    }
                    else
                    {
                        status.text    = Truncate(App.PlayerInfoO.PlayerName, MAX_CHARS) + " Wins!";
                        App.WinnerInfo = App.PlayerInfoO;
                        App.LoserInfo  = App.PlayerInfoX;
                    }
                }

                // Load the Tic Tac Toe scene
                if (this != null && this.gameObject != null)
                {
                    App.GotoTicTacToeScene(gameObject);
                }
            }
        });
    }
Exemple #8
0
    public void Init(OnlineManager _onlineManager, e_teams _team, int[] _heroes)
    {
        team          = _team;
        onlineManager = _onlineManager;
        utility       = new BoardUtility(map.Board, map.MapSize);

        inputManager.GameStart(team);
        boardManager.GameStart(_heroes);
        deckManager.GameStart();

        ChangeStep(e_step.Placement);
    }
Exemple #9
0
        private void _CreateBoard()
        {
            //Generate 8x8 Panel
            for (int i = 0; i <= 63; i++)
            {
                Controls.Add(_CreatePanel(i));
            }
            _Board = Controls.OfType <Button>().ToList();

            //Initialize Disks
            BoardUtility.InitializeDisks(_Board, _WhitePlayer, _BlackPlayer);

            _UpdateDisplayScore();
        }
Exemple #10
0
        private async void _StartGame(object sender, EventArgs e)
        {
            _InitializePlayers();
            _CreateBoard();

            //Enable Panels
            await BoardUtility.EnablePossiblePanel(_Board, _CurrentTurn);

            _GameTimer.Start();

            if (_CurrentTurn is GreedyAI player)
            {
                await player.AutoMove(_Board);
            }
        }
Exemple #11
0
    public override void Enter()
    {
        // filter our tiles down to entrances only
        List <TileSpawnData> entrances = area.Board.levelData.tiles.Where(tiles => tiles.tileRef == TileTypes.ENTRANCE).ToList();
        // UnityEngine.Debug.Log (string.Format ("length :{0}", entrances.Count));
        // UnityEngine.Debug.Log (string.Format ("location :{0}", entrances[0].location));
        // UnityEngine.Debug.Log (string.Format ("tile ref :{0}", entrances[0].tileRef));
        // find min and max values for this board
        Point min = BoardUtility.SetMinV2Int(area.Board.levelData);
        Point max = BoardUtility.SetMaxV2Int(area.Board.levelData);

        InitializeResources(entrances, min, max);
        SetPlayerPosition(entrances, min, max);
        SetPlayerData();
        FinishLoading();
    }
 //check if the pieces are connecting to each other in the location
 public static bool isConnect(int[] gameGrid, int key, int num, int x, int y, int dx, int dy)
 {
     for (int i = 0; i < num; i++)
     {
         int cx = x + dx * i;
         int cy = y + dy * i;
         if (BoardUtility.isOutOfBound(cx, cy))
         {
             return(false);
         }
         if (gameGrid[BoardUtility.indexOf(cx, cy)] != key)
         {
             return(false);
         }
     }
     return(true);
 }
    private void AddNewCell(string jsonResponse, object cbObject)
    {
        var match = cbObject as MatchInfo;
        var data  = JsonMapper.ToObject(jsonResponse)["data"];

        //Determining if game is completed
        string board = (string)data["matchState"]["board"];

        match.complete = BoardUtility.IsGameCompleted(board);
        if (match.complete)
        {
            match.scoreSubmitted = true;
        }
        App.PlayerInfoO = match.playerOInfo;
        App.PlayerInfoX = match.playerXInfo;

        //Create game button cell
        GameButtonCell newItem = CreateItemCell(MyGamesScrollView, (index % 2) == 0);

        newItem.Init(match, this);
        newItem.transform.localPosition = Vector3.zero;
        index = index < matches.Count ? index++ : 0;
        m_itemCell.Add(newItem);

        //Ensuring no duplicated game button cells are created
        var tempList = new List <GameButtonCell>();

        for (int i = m_itemCell.Count - 1; i > -1; i--)
        {
            if (tempList.Count == 0)
            {
                tempList.Add(m_itemCell[i]);
                continue;
            }
            if (tempList[i].MatchInfo.matchId == m_itemCell[i].MatchInfo.matchId)
            {
                Destroy(m_itemCell[i].gameObject);
                m_itemCell.Remove(m_itemCell[i]);
            }
        }
    }
Exemple #14
0
    public void AcceptRematch(GameObject previousScene)
    {
        // Send Event back to opponent that its accepted
        var jsonData = new JsonData();

        jsonData["isReady"] = true;
        //Event to send to opponent to disable PleaseWaitScreen
        Bc.EventService.SendEvent(OpponentInfo.ProfileId, "playAgain", jsonData.ToJson());

        //Making sure player info is ready to be sent for OnCompleteGame()
        if (WinnerInfo == null || LoserInfo == null)
        {
            Winner     = BoardUtility.CheckForWinner();
            WinnerInfo = Winner == 1 ? PlayerInfoX : PlayerInfoO;
            LoserInfo  = Winner == 1 ? PlayerInfoO : PlayerInfoX;
        }
        // Reset Match
        OnCompleteGame();
        GotoMatchSelectScene(previousScene);
        _localMatchSelect.OnPickOpponent(OpponentInfo);
    }
Exemple #15
0
    public void checkWinner()
    {
        int player1 = MiniMaxScript.numOfConnect(gameGrid, 1, 4);
        int player2 = MiniMaxScript.numOfConnect(gameGrid, 2, 4);

        if (player1 != 0 || player2 != 0)
        {
            if (player1 != 0)
            {
                gameControl.endGame(1);
            }
            else
            {
                gameControl.endGame(2);
            }
        }
        if (BoardUtility.boardFull(gameGrid))
        {
            gameControl.endGame(0);
        }
    }
Exemple #16
0
        private async Task _NextTurn()
        {
            BoardUtility.DisablePanelAndResetText(_Board);
            if (!GamePlayUtility.IsPossibleToMove(_Board, _Enemy()))
            {
                if (!GamePlayUtility.IsPossibleToMove(_Board, _CurrentTurn))
                {
                    _GameOver();
                    return;
                }

                MessageBox.Show($"[{_Enemy().PlayerSide.Name}] Player can't move. [{_CurrentTurn.PlayerSide.Name}] Turn", "Game Notification");
                return;
            }

            _CurrentTurn          = _Enemy();
            _PlayerTurnLabel.Text = _CurrentTurn.PlayerSide.Name;
            if (_CurrentTurn is GreedyAI player)
            {
                await player.AutoMove(_Board);
            }
            return;
        }
    //minimax algorithm that will expend its search and return the heuristic value for different result
    //with remove option
    public static Node minimaxWithRemove(int[] gameGrid, int depth, int alpha, int beta, bool maximizingPlayer, int playerKey, int index, int h)
    {
        if (depth == 0)
        {
            Node n = new Node();
            n.value = heristic(gameGrid, playerKey, h);
            n.index = index;
            return(n);
        }
        else
        {
            if (maximizingPlayer)
            {
                Node n = new Node();
                n.value = -9999999;
                int j = -1;
                for (int i = 0; i < 14; i++)
                {
                    if (i < 7 && !BoardUtility.canInsert(gameGrid, i))
                    {
                        break;
                    }
                    else if (i >= 7 && !BoardUtility.canRemove(gameGrid, i - 7, playerKey))
                    {
                        break;
                    }

                    int[] newGrid = BoardUtility.copyGameGrid(gameGrid);

                    if (i < 7)
                    {
                        BoardUtility.insertToGrid(newGrid, BoardUtility.insertingPosition(newGrid, i), playerKey);
                    }
                    else
                    {
                        BoardUtility.removeFromGrid(newGrid, i - 7, 5);
                    }

                    Node n1 = minimax(newGrid, depth - 1, alpha, beta, false, playerKey, i, h);
                    if (n1.value >= n.value)
                    {
                        n = n1;
                        j = i;
                    }
                    else if (n1.value == n.value)
                    {
                        if (Random.Range(0, 2) == 1)
                        {
                            n = n1;
                            j = i;
                        }
                    }
                    if (alphaBeta && n1.value >= alpha)
                    {
                        alpha = n1.value;
                    }
                    if (alphaBeta && beta <= alpha)
                    {
                        break;
                    }
                }
                n.index = j;
                return(n);
            }
            else
            {
                Node n = new Node();
                n.value = 99999999;
                int key = (playerKey + 1) % 2;
                int j   = -1;
                for (int i = 0; i < 7; i++)
                {
                    if (i < 7 && !BoardUtility.canInsert(gameGrid, i))
                    {
                        break;
                    }
                    else if (i >= 7 && !BoardUtility.canRemove(gameGrid, i - 7, key))
                    {
                        break;
                    }

                    int[] newGrid = BoardUtility.copyGameGrid(gameGrid);

                    if (i < 7)
                    {
                        BoardUtility.insertToGrid(newGrid, BoardUtility.insertingPosition(newGrid, i), key);
                    }
                    else
                    {
                        BoardUtility.removeFromGrid(newGrid, i - 7, 5);
                    }

                    Node n1 = minimax(newGrid, depth - 1, alpha, beta, true, playerKey, i, h);
                    if (n1.value <= n.value)
                    {
                        n = n1;
                        j = i;
                    }
                    else if (n1.value == n.value)
                    {
                        if (Random.Range(0, 2) == 1)
                        {
                            n = n1;
                            j = i;
                        }
                    }
                    if (alphaBeta && beta >= n1.value)
                    {
                        beta = n1.value;
                    }
                    if (alphaBeta && beta <= alpha)
                    {
                        break;
                    }
                }
                n.index = j;
                return(n);
            }
        }
    }
Exemple #18
0
 public override void Set()
 {
     utility = GameplayManager.Instance.Utility;
 }
Exemple #19
0
    // Update is called once per frame
    void Update()
    {
        if (gameControl.gamestate == "gameplay")
        {
            countdown += Time.deltaTime;
            //player move
            //only usable when player is allowed to move
            if ((player1 == InputChoice.Player && redTurn) || (player2 == InputChoice.Player && !redTurn))
            {
                for (int i = 1; i < 8; i++)
                {
                    if (Input.GetKeyDown(i.ToString()))
                    {
                        buttonPressed(i - 1);
                    }
                }
                for (int i = 0; i < 7; i++)
                {
                    if (allowRemove)
                    {
                        if (Input.GetKeyDown(removeCode[i]))
                        {
                            removeButtonPressed(i);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            //if the first player is also a computer but with only random move
            if ((player1 == InputChoice.Random && redTurn) || (player2 == InputChoice.Random && !redTurn))
            {
                if (countdown >= computerThinkTime)
                {
                    int move = MiniMaxScript.randomMove(gameGrid, 1, allowRemove);
                    if (move < 7)
                    {
                        spawnChess(move);
                    }
                    else
                    {
                        removeChess(BoardUtility.getIndexOfRemove(gameGrid, move, 1));
                    }
                }
            }

            //if vsComputer
            if ((player1 == InputChoice.HeuristicOne && redTurn) || (player2 == InputChoice.HeuristicOne && !redTurn) ||
                (player1 == InputChoice.HeuristicTwo && redTurn) || (player2 == InputChoice.HeuristicTwo && !redTurn))
            {
                int heuristic;
                int player;
                //check which is current player and using which heuristic
                if (player1 == InputChoice.HeuristicOne && redTurn)
                {
                    heuristic = 1; player = 1;
                }
                else if (player1 == InputChoice.HeuristicOne && !redTurn)
                {
                    heuristic = 1; player = 2;
                }
                else if (player1 == InputChoice.HeuristicTwo && redTurn)
                {
                    heuristic = 2; player = 1;
                }
                else
                {
                    heuristic = 2; player = 2;
                }
                if (countdown >= computerThinkTime)
                {
                    //set minimax to also allow remove
                    if (allowRemove)
                    {
                        //gameGrid, depth, playerKey, heristic
                        int num = MiniMaxScript.miniMaxResultWithRemove(gameGrid, depth, player, heuristic);
                        if (num < 7)
                        {
                            spawnChess(num);
                        }
                        else
                        {
                            removeChess(num - 7);
                        }
                    }
                    else
                    {
                        spawnChess(MiniMaxScript.miniMaxResult(gameGrid, depth, player, heuristic));
                    }
                }
            }
        }
    }
    private void updateHud(bool updateNames = true)
    {
        // Check we if are not seeing a done match
        App.Winner = BoardUtility.CheckForWinner();

        // Read match history
        if (_history == null && App.Winner != 0)
        {
            _turnPlayed = true;
            App.Bc.AsyncMatchService
            .ReadMatchHistory(App.OwnerId, App.MatchId, OnReadMatchHistory);
        }

        enableDuringGameDisplay(App.Winner == 0);

        Transform[] toCheckDisplay = { DuringGameDisplay.transform, AfterGameDisplay.transform };
        //Game is finished
        if (App.Winner != 0)
        {
            App.IsAskingToRematch = false;
            App.AskedToRematch    = false;
        }
        if (DuringGameDisplay.activeInHierarchy)
        {
            TextMeshProUGUI status = toCheckDisplay[0].Find("StatusOverlay").Find("StatusText").GetComponent <TextMeshProUGUI>();
            // update the during Game Display
            status.text = App.Winner != 0 ? App.Winner == -1 ? "Match Tied" : "Match Completed" :
                          (App.WhosTurn == App.PlayerInfoX && App.CurrentMatch.yourToken == "X" ||
                           App.WhosTurn == App.PlayerInfoO && App.CurrentMatch.yourToken == "O") ? "Your Turn" :
                          Truncate(App.WhosTurn.PlayerName, MAX_CHARS) + "'s Turn";
        }
        else
        {
            Transform       statusOverlay = toCheckDisplay[1].Find("StatusOverlay");
            TextMeshProUGUI status        = statusOverlay.Find("StatusText").GetComponent <TextMeshProUGUI>();
            TextMeshProUGUI statusOutline = statusOverlay.Find("StatusTextOutline").GetComponent <TextMeshProUGUI>();
            if (App.Winner < 0)
            {
                status.text = "Game Tied!";
            }
            else if (App.Winner > 0)
            {
                if (App.Winner == 1)
                {
                    status.text    = Truncate(App.PlayerInfoX.PlayerName, MAX_CHARS) + " Wins!";
                    App.WinnerInfo = App.PlayerInfoX;
                    App.LoserInfo  = App.PlayerInfoO;
                }
                else
                {
                    status.text    = Truncate(App.PlayerInfoO.PlayerName, MAX_CHARS) + " Wins!";
                    App.WinnerInfo = App.PlayerInfoO;
                    App.LoserInfo  = App.PlayerInfoX;
                }
                if (!App.CurrentMatch.scoreSubmitted)
                {
                    if (App.WinnerInfo.ProfileId == App.ProfileId)
                    {
                        App.CheckAchievements();
                        App.PostToLeaderboard();
                    }
                    App.CurrentMatch.scoreSubmitted = true;
                    var jsonData = new JsonData();
                    jsonData["scoreSubmitted"]    = true;
                    jsonData["opponentProfileID"] = App.ProfileId;
                    jsonData["opponentName"]      = App.Name;
                    jsonData["matchID"]           = App.MatchId;
                    jsonData["ownerID"]           = App.OwnerId;
                    //Send event to opponent to prompt them to play again
                    App.Bc.EventService.SendEvent(App.CurrentMatch.matchedProfile.ProfileId, "gameConcluded", jsonData.ToJson());
                }
            }
            else
            {
                status.text = Truncate(App.WhosTurn.PlayerName, MAX_CHARS) + " Turn";
            }
            statusOutline.text = status.text;
        }

        if (updateNames)
        {
            Transform       playerVsOpp;
            TextMeshProUGUI playerXName, playerXNameOutline, playerOName, playerONameOutline;
            // update the names
            for (int i = 0; i < toCheckDisplay.Length; ++i)
            {
                playerVsOpp             = toCheckDisplay[i].Find("PlayerVSOpponent");
                playerXName             = playerVsOpp.Find("PlayerName").GetComponent <TextMeshProUGUI>();
                playerXNameOutline      = playerVsOpp.Find("PlayerNameOutline").GetComponent <TextMeshProUGUI>();
                playerXName.text        = Truncate(App.PlayerInfoX.PlayerName, MAX_CHARS);
                playerXNameOutline.text = playerXName.text;

                playerOName             = playerVsOpp.Find("OpponentName").GetComponent <TextMeshProUGUI>();
                playerONameOutline      = playerVsOpp.Find("OpponentNameOutline").GetComponent <TextMeshProUGUI>();
                playerOName.text        = Truncate(App.PlayerInfoO.PlayerName, MAX_CHARS);
                playerONameOutline.text = playerOName.text;
            }
        }
    }