Ejemplo n.º 1
0
        /// <summary>
        /// Handler for <see cref="UIElement.MouseDown"/> event of each cell in the game
        /// </summary>
        /// <param name="cellId">Index of the cell which was clicked in the <see cref="cellImages"/> array</param>
        async Task HandleCellClickAsync(int cellId)
        {
            if (cellId < 0 || cellId >= cellImages.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(cellId), $"Argument must be index of {nameof(Image)} in the {nameof(cellImages)} array");
            }

            if (!gameController.CanCellBeShot(cellId))
            {
                return;
            }

            long startTime = DateTime.Now.Ticks;

            cellImages[cellId].Source = ImageResourcesManager.shot;
            GameAudioManager.PlayShot();

            bool destroyedShip = await Task.Run(() => gameController.UpdateShipGridForShot(cellId));

            UpdateClicksUI();

            long timePassed = DateTime.Now.Ticks - startTime;

            if (timePassed < animationDuration)
            {
                await Task.Delay(new TimeSpan(animationDuration - timePassed));
            }

            if (destroyedShip)
            {
                GameAudioManager.PlayBubbles();
                UpdateAllCellsUI();
            }
            else
            {
                UpdateCellUI(cellId);
            }

            if (gameController.gameState == GameController.GameState.won)
            {
                await Task.Delay(new TimeSpan(animationDuration));
                await PlayVictoryAnimationAsync();
            }
            else if (gameController.gameState == GameController.GameState.lost)
            {
                await Task.Delay(new TimeSpan(animationDuration));
                await PlayDefeatAnimationAsync();
            }
        }