public MultiplayerController(BotManager player, OnReciveCallBack onRcCallBack, OnDisconnect onDCCallBack,
                              OnGameIsReady onGameIsReady, OnGameFinished onGameFinished,
                              OnEnemyDCAccepted onEnemyDCAccepted, OnReconnectComplete onReconnectComplete,
                              OnReconnectFailed onReconnectFailed, OnWeakConectionDetected onWeakConnection,
                              bool isForExistingGame, OnRuleReady onRuleReady)
 {
     this.player           = player;
     io                    = new SocketIOComponent(Constants.SOCKET_URL);
     reconnectMode         = false;
     eventHandler          = new EventHandler();
     lastDataTime          = 0f;
     this.onDCCallBack     = onDCCallBack;
     this.onWeakConnection = onWeakConnection;
     if (!isForExistingGame)
     {
         eventHandler.initializeForFirstTime(this, io, onRcCallBack, onDCCallBack, onGameIsReady,
                                             onGameFinished, onEnemyDCAccepted, onReconnectComplete,
                                             onReconnectFailed);
         //Thread acceptGameThread = new Thread(new ThreadStart(acceptGame));
         //acceptGameThread.Start();
     }
     else
     {
         (new Thread(() =>
         {
             requestGameRule(onRcCallBack, onDCCallBack, onGameIsReady,
                             onGameFinished, onEnemyDCAccepted, onReconnectComplete, onReconnectFailed, onRuleReady);
         })).Start();
     }
 }
Beispiel #2
0
        // Checks if a winning coniditon has occured
        internal bool CheckForWinner(char playerChar)
        {
            if (turnCount == 9)
            {
                OnGameFinished?.Invoke(this, null);
            }
            bool       output         = false; //output = IsAWinner;
            List <int> occupiedPlaces = new List <int>();

            for (int i = 0; i < GameArray.Length; i++)
            {
                if (GameArray[i] == playerChar)
                {
                    occupiedPlaces.Add(i);
                }
            }
            if (CheckForItemsInList(occupiedPlaces, 1, 2, 3) ||
                CheckForItemsInList(occupiedPlaces, 4, 5, 6) ||
                CheckForItemsInList(occupiedPlaces, 7, 8, 9) ||
                CheckForItemsInList(occupiedPlaces, 3, 5, 7) ||
                CheckForItemsInList(occupiedPlaces, 1, 4, 7) ||
                CheckForItemsInList(occupiedPlaces, 2, 5, 8) ||
                CheckForItemsInList(occupiedPlaces, 3, 6, 9) ||
                CheckForItemsInList(occupiedPlaces, 1, 5, 9))
            {
                output = true;
            }
            return(output);
        }
    private void Update()
    {
        if (isTrainingRunning == false)
        {
            return;
        }

        trainingRunTime += Time.deltaTime;

        if (Input.GetKeyDown(KeyCode.C))
        {
            itemsLate       = 15;
            itemsCorrect    = 25;
            itemsEarly      = 7;
            trainingRunTime = maxGametime;
        }

        if (trainingRunTime >= maxGametime)
        {
            TapReactionFeedbackData feedbackData = new TapReactionFeedbackData();
            feedbackData.CookiesBurnt           = itemsLate;
            feedbackData.CookiesCorrect         = itemsCorrect;
            feedbackData.CookiesRaw             = itemsEarly;
            feedbackData.GainedXPPerCorrectItem = gainedXPPerCorrectItem;
            feedbackData.GainedXPPerFailedItem  = gainedXPPerFailedItem;
            isTrainingRunning = false;
            OnGameFinished?.Invoke(feedbackData);
        }
    }
Beispiel #4
0
 private void CheckIfOneTeamWon()
 {
     for (int index = 0; index < GameStructure.GameTeams.Count; index++)
     {
         if (GameStructure.GameTeams[index].score >= GameInitializers.SCORE_NEEDED_FOR_VICTORY)
         {
             OnGameFinished?.Invoke(this, EventArgs.Empty);
         }
     }
 }
Beispiel #5
0
    public void FishEaten()
    {
        _currentFish++;
        _anglerfish.FishEaten();

        if (_currentFish == FishLimit)
        {
            Utils.SaveBestTime(_currentTime);
            OnGameFinished?.Invoke(_currentTime);
        }
    }
Beispiel #6
0
 private void CheckForGameTimedOut(float deltaTime)
 {
     if (!GameManager.Singleton.GameFinished)
     {
         m_timeLimit -= deltaTime;
         if (m_timeLimit <= 0)
         {
             OnGameFinished?.Invoke(); // The game is finished.
         }
     }
 }
 public void onLoadForExistingGameComplete(MultiplayerController parent, OnReciveCallBack onRcCallBack, OnDisconnect onDCCallBack,
                                           OnGameIsReady onGameIsReady, OnGameFinished onGameFinished, OnEnemyDCAccepted onEnemyDCAccepted,
                                           OnReconnectComplete onReconnectComplete, OnReconnectFailed onReconnectFailed,
                                           OnRuleReady onRuleReady, OnWeakConectionDetected onWeakConnection, bool isExistingGame)
 {
     this.onDCCallBack     = onDCCallBack;
     this.onWeakConnection = onWeakConnection;
     (new Thread(() =>
     {
         requestGameRule(onRcCallBack, onDCCallBack, onGameIsReady,
                         onGameFinished, onEnemyDCAccepted, onReconnectComplete, onReconnectFailed, onRuleReady);
     })).Start();
 }
Beispiel #8
0
 public void CheckForWinCondition()
 {
     if (GameManager.Singleton.GameFinished) // Don't change the outcome after the game has finished.
     {
         return;
     }
     foreach (Team team in TeamManager.Singleton.Teams)
     {
         if (CalculateScore(team.Score) >= m_winCondition) // A team has met the win condition.
         {
             OnGameFinished?.Invoke();
         }
     }
 }
    private void Update()
    {
        if (!IsPlaying)
        {
            return;
        }

        var dir = Vector3.up * TimeManager.UnscaleDeltaTime * PointerSpeed;

        dir = movingDir ? -dir : dir;

        pointer.localPosition += dir;
        if (Mathf.Abs(pointer.localPosition.y) > pointerMovingRange)
        {
            movingDir = !movingDir;
        }

        if (Input.GetButtonDown("Fire1") || Input.GetKeyDown(KeyCode.Space))
        {
            IsPlaying = false;
            StartCoroutine(StartAnimation());
        }

        return;

        if (Input.GetKeyDown(KeyCode.O))
        {
            MessageBox.DisplayMessage("Minigame won!", "You successfully harvest the crop!");
            if (OnGameFinished != null)
            {
                OnGameFinished.Invoke(1);
            }
            IsPlaying              = false;
            MessageBox.OnContinue += StopPlay;
        }

        if (Input.GetKeyDown(KeyCode.P))
        {
            MessageBox.DisplayMessage("Minigame failed!", "Half of the crops you harvested are lost!");
            if (OnGameFinished != null)
            {
                OnGameFinished.Invoke(1);
            }
            IsPlaying              = false;
            MessageBox.OnContinue += StopPlay;
        }
    }
Beispiel #10
0
    void HandleSameItems(GridItem gridItem)
    {
        if (GridController.Instance.CheckRowItemsAreSame(gridItem.IndexY, GameStateController.Instance.CurrentState) ||
            GridController.Instance.CheckColumnItemsAreSame(gridItem.IndexX, GameStateController.Instance.CurrentState) ||
            GridController.Instance.CheckDiagonalItemsAreSame(gridItem.IndexX, gridItem.IndexY, GameStateController.Instance.CurrentState))
        {
            OnGameFinished?.Invoke($"{GameStateController.Instance.CurrentState.ToString()} WON!");

            gameFinished = true;
        }

        if (GridController.Instance.CheckAllRowsFull())
        {
            OnGameFinished?.Invoke("It's a Tie");

            gameFinished = true;
        }
    }
Beispiel #11
0
    void EndGameAnim()
    {
        for (int i = 0; i < endGameCubes.Count; i++)
        {
            endGameCubes[i].GetComponent <Rigidbody>().isKinematic = false;
            endGameCubes[i].GetComponent <Rigidbody>().useGravity  = true;
            endGameCubes[i].GetComponent <BoxCollider>().isTrigger = false;
            endGameCubes[i].GetComponent <BoxCollider>().enabled   = true;
            endGameCubes[i].gameObject.transform.parent            = null;

            endGameCubes.Remove(endGameCubes[i]); // todo  dagilan objelerin yeni levele baslamadan once destroylanmasi lazim. Maybe Ground OnCollisionEnter.

            if (endGameCubes.Count <= 0)
            {
                Debug.Log("Finished");
                OnGameFinished?.Invoke(nextLevelIndex);
            }
        }
    }
Beispiel #12
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="GameMenuControl"/> class.
        /// </summary>
        /// <param name="game"> The game. </param>
        public GameMenuControl(Game game)
        {
            _game = game;
            InitializeComponent();
            Score = game.Score;
            Time  = game.Time;
            var gameControl = new GameControl(game, this)
            {
                Dock = DockStyle.Fill
            };

            this.tableLayoutPanel1.Controls.Add(gameControl, 0, 1);

            game.OnTimeChanged += (sender, t) =>
            {
                if (time.InvokeRequired)
                {
                    time.Invoke((MethodInvoker) delegate { Time = t; });
                    return;
                }

                Time = t;
            };

            game.OnScoreChanged += (sender, s) =>
            {
                if (score.InvokeRequired)
                {
                    score.Invoke((MethodInvoker) delegate { Score = s; });
                    return;
                }

                Score = s;
            };

            gameControl.OnGameFinished += (sender, args) =>
            {
                game.End();
                OnGameFinished?.Invoke(this, args);
            };
            game.Start();
        }
Beispiel #13
0
        /// <summary>
        /// Unload any content (textures, fonts, etc) used by this state. Called when the state is removed.
        /// </summary>
        public override void UnloadContent()
        {
            /*try
             * {
             *  ServiceManager.Game.GraphicsDevice.Reset();
             *  ServiceManager.Game.GraphicsDevice.VertexDeclaration = null;
             *  ServiceManager.Game.GraphicsDevice.Vertices[0].SetSource(null, 0, 0);
             * }
             * catch (Exception ex)
             * {
             *  // If the graphics device was disposed already, it throws an exception.
             *  Console.Error.WriteLine(ex);
             * }*/

            if (mouseCursor != null)
            {
                mouseCursor.DisableCustomCursor();
                mouseCursor = null;
            }
            EnvironmentEffects = null;
            Bases        = null;
            buffbar      = null;
            cd           = null;
            hud          = null;
            renderer     = null;
            fps          = null;
            map          = null;
            visibleTiles = null;
            Scores       = null;
            Players      = null;
            Projectiles  = null;
            Chat         = null;
            buffer       = null;
            miniMap.Dispose();
            miniMap = null;

            if (OnGameFinished != null)
            {
                EventArgs args = new EventArgs();
                OnGameFinished.Invoke(this, args);
            }
        }
        private void requestGameRule(OnReciveCallBack onRcCallBack, OnDisconnect onDCCallBack, OnGameIsReady onGameIsReady,
                                     OnGameFinished onGameFinished, OnEnemyDCAccepted onEnemyDCAccepted,
                                     OnReconnectComplete onReconnectComplete, OnReconnectFailed onReconnectFailed, OnRuleReady onRuleReady)
        {
            io.Connect();
            while (!io.IsConnected)
            {
                io.On(Constants.serverMessage.events.CONNECT, (SocketIOEvent obj) =>
                {
                }
                      );
                io.On(Constants.serverMessage.events.DISCONNECT, onDisconnect);
                Thread.Sleep(100);
            }
            eventHandler.initializeForFirstTime(this, io, onRcCallBack, onDCCallBack, onGameIsReady,
                                                onGameFinished, onEnemyDCAccepted, onReconnectComplete, onReconnectFailed);
            bool ruleIsReady = false;

            io.On(Constants.serverMessage.events.GAME_RULE_READY, (obj) =>
            {
                ruleIsReady       = true;
                GameInfo info     = new GameInfo();
                string gameToken  = player.user.getGameToken();
                string userToken  = player.user.getUserToken();
                string enemyToken = player.user.getOpponentToken();
                string enemyName  = player.user.getEnemyName();
                info.fillWithCommonData(obj, userToken, gameToken, enemyToken, enemyName);
                onRuleReady(info);
                player.user.setGameMode(Constants.gameMode.MULTI_PLAYER, info);
                Thread t = new Thread(new ThreadStart(retryConnection));
                t.Start();
            }
                  );
            while (!ruleIsReady)
            {
                io.Emit(Constants.serverMessage.events.REQUEST_GAME_RULE);
                Thread.Sleep(100);
            }
        }
 public void initializeForFirstTime(MultiplayerController parent, SocketIOComponent io, OnReciveCallBack onRcCallBack, OnDisconnect onDCCallBack, OnGameIsReady onGameIsReady, OnGameFinished onGameFinished, OnEnemyDCAccepted onEnemyDCAccepted, OnReconnectComplete onReconnectComplete, OnReconnectFailed onReconnectFailed)
 {
     this.parent              = parent;
     this.io                  = io;
     this.onRcCallBack        = onRcCallBack;
     this.onDCCallBack        = onDCCallBack;
     this.onGameIsReady       = onGameIsReady;
     this.onGameFinished      = onGameFinished;
     this.onEnemyDCAccepted   = onEnemyDCAccepted;
     this.onReconnectComplete = onReconnectComplete;
     this.onReconnectFailed   = onReconnectFailed;
     io.On(Constants.serverMessage.events.START_GAME, startGame);
     io.On(Constants.serverMessage.events.END_GAME, endGame);
     io.On(Constants.serverMessage.events.ENEMY_DC_ACCEPTED, enemyDCAccepted);
     io.On(Constants.serverMessage.events.ON_GAME_STATUS_READY, gameStatusRecieve);
     io.On(Constants.serverMessage.events.ON_RECONNECT_FAILED, onRecFailed);
     io.On(Constants.serverMessage.events.NEW_TOKENS, onNewTokenRecieved);
     io.On(Constants.serverMessage.events.SERVER_ORDER, onServerOrder);
     io.On(Constants.serverMessage.events.CORRECTION, onCorrection);
     io.On(Constants.serverMessage.events.PING_SUC, onPingSuc);
     //io.On(Strings.serverMessage.events.ENABLE_USER, onEnableUser);
 }
Beispiel #16
0
 //loops every turn
 void GameLoop()
 {
     while (turnCount <= 9)
     {
         Player currentPlayer;
         if (IsPlayer1Turn)
         {
             currentPlayer = Player1;
         }
         else
         {
             currentPlayer = Player2;
         }
         int turnInt = currentPlayer.Turn(this);
         GameArray[turnInt - 1] = currentPlayer.PlayerChar;
         IsPlayer1Turn          = !IsPlayer1Turn;
         turnCount++;
         OnGameChanged?.Invoke(this, GameArray);
         if (CheckForWinner(currentPlayer.PlayerChar))
         {
             OnGameFinished?.Invoke(this, currentPlayer);
         }
     }
 }
    private void AfterSlice()
    {
        var maxHitZone1 = hitZone1.localPosition.y + hitZone1.sizeDelta.y * 0.5f;
        var minHitZone1 = hitZone1.localPosition.y - hitZone1.sizeDelta.y * 0.5f;
        var maxHitZone2 = hitZone2.localPosition.y + hitZone2.sizeDelta.y * 0.5f;
        var minHitZone2 = hitZone2.localPosition.y - hitZone2.sizeDelta.y * 0.5f;

        MessageBox.OnContinue += StopPlay;
        if (pointer.localPosition.y > minHitZone1 &&
            pointer.localPosition.y < maxHitZone1)
        {
            MessageBox.DisplayMessage("Minigame won!", "You successfully harvest the crop!");
            if (OnGameFinished != null)
            {
                OnGameFinished.Invoke(1);
            }
        }
        else if (
            pointer.localPosition.y > minHitZone2 &&
            pointer.localPosition.y < maxHitZone2)
        {
            MessageBox.DisplayMessage("Minigame Passed!", "A quarter of the crops you harvested are lost!");
            if (OnGameFinished != null)
            {
                OnGameFinished.Invoke(0.5f);
            }
        }
        else
        {
            MessageBox.DisplayMessage("Minigame Failed!", "Half of the crops you harvested are lost!");
            if (OnGameFinished != null)
            {
                OnGameFinished.Invoke(0);
            }
        }
    }
Beispiel #18
0
 private void GameFinished(bool won)
 {
     isStarted = false;
     OnGameFinished?.Invoke(won);
 }
Beispiel #19
0
        /// <summary>
        /// Try to move the currently selected piece to the given board tile.
        /// </summary>
        /// <param name="tile"></param>
        /// <returns>Returns true if movement was successfull.</returns>
        private bool MoveSelectedPieceTo(BoardTile tile, Player player)
        {
            if (SelectedTile.CanMoveTo(this, tile))
            {
                // Check if current move is a castling move
                if (SelectedTile.OccupyingPiece != null && SelectedTile.OccupyingPiece.GetType() == typeof(King) &&
                    tile.OccupyingPiece != null && tile.OccupyingPiece.GetType() == typeof(Rook) &&
                    tile.OccupyingPiece.IsWhite == SelectedTile.OccupyingPiece.IsWhite)
                {
                    var rookDestination = ((Rook)tile.OccupyingPiece).GetCastleLocation(this, tile);
                    rookDestination.OccupyingPiece = tile.OccupyingPiece;
                    tile.OccupyingPiece            = null;

                    tile = ((King)SelectedTile.OccupyingPiece).GetCastleLocation(this, SelectedTile, tile);
                }

                currentRountData.AddMove(new PlayerMove(player, SelectedTile, tile));

                latestTiles.Clear();
                latestTiles.Add(tile);
                latestTiles.Add(SelectedTile);

                if (tile.OccupyingPiece == null && SelectedTile.OccupyingPiece.GetType() != typeof(Pawn))
                {
                    movesMadeWithoutProgress++;
                }
                else
                {
                    movesMadeWithoutProgress = 0;
                }

                tile.OccupyingPiece = SelectedTile.OccupyingPiece;
                SelectedTile.OccupyingPiece.PostMovementEvent(tile);
                SelectedTile.OccupyingPiece = null;

                if (IsCheckmate(player))
                {
                    OnGameFinished?.Invoke(this, new GameFinishedEvent(player, GameFinishedReason.CheckMate));
                }
                else if (!EnoughMaterialOnBoard())
                {
                    OnGameFinished?.Invoke(this, new GameFinishedEvent(null, GameFinishedReason.InsufficientMaterial));
                }
                else if (IsStalemate(player.IsWhite))
                {
                    OnGameFinished?.Invoke(this, new GameFinishedEvent(null, GameFinishedReason.Stalemate));
                }
                else if (movesMadeWithoutProgress >= 75)
                {
                    OnGameFinished?.Invoke(this, new GameFinishedEvent(null, GameFinishedReason.Move75));
                }

                if (currentRountData.IsDone)
                {
                    OnRoundFinished?.Invoke(this, currentRountData);
                    currentRountData = new RoundFinishedEvent(currentRountData.Round + 1);
                }

                return(true);
            }

            return(false);
        }
 public void Finish()
 {
     OnGameFinished?.Invoke(this, null);
 }
Beispiel #21
0
 void IClientListener <TPlayerStatus, TRoomMessage, TMsg> .OnGameFinished() => OnGameFinished.Invoke();
Beispiel #22
0
 public void FinishGame()
 {
     OnGameFinished?.Invoke();
     _currentGameId = -1;
 }
Beispiel #23
0
        public async Task TickAsync(PlayerActionEnum action, CancellationToken cancellationToken = default)
        {
            Block block;

            if (_block == null) // first run init
            {
                await GenerateNewBlockPairAsync();

                block = (Block)_block.Clone();
                await DrawGlassAsync(true, cancellationToken);
            }
            else
            {
                if (action == PlayerActionEnum.None && BlockHasStuck(_block)) // check stuck
                {
                    await ApplyBlockAsync(_block);
                    await RecalculateLinesAsync(cancellationToken);
                    await GenerateNewBlockPairAsync();
                    await DisplayNextBlockAsync(cancellationToken);
                }

                block = (Block)_block.Clone();
                switch (action)
                {
                case PlayerActionEnum.None:
                case PlayerActionEnum.SoftDrop:
                    block.Y++;
                    break;

                case PlayerActionEnum.Left:
                {
                    block.X--;
                    break;
                }

                case PlayerActionEnum.Right:
                {
                    block.X++;
                    break;
                }

                case PlayerActionEnum.Rotate:
                {
                    block = await _block.RotateAsync(cancellationToken);

                    break;
                }

                case PlayerActionEnum.Drop:
                    var inc = false;
                    while (CanApply(block))
                    {
                        inc = true;
                        block.Y++;
                    }

                    if (inc && block.Y > 0)
                    {
                        block.Y--;
                    }
                    break;

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

            if (CanApply(block))
            {
                _block = block;

                await DrawGlassAsync(false, cancellationToken);
                await DrawBlockAsync(_block, Constants.GlassDeltaX, Constants.GlassDeltaY, cancellationToken);
            }
            else
            {
                if (_block.Y == 0)
                {
                    OnGameFinished?.Invoke(this, new EventArgs());
                }
            }

            await Task.CompletedTask;
        }
 public void FinishGame()
 {
     OnGameFinished?.Invoke();
     IsGameRunning = false;
 }
Beispiel #25
0
 public void GameFinished()
 {
     OnGameFinished?.Invoke();
 }