Exemplo n.º 1
0
 /// <summary>
 /// 指定球速度清零。
 /// </summary>
 /// <param name="ball">指定球</param>
 private void RemoveBallSpeed(GameBall ball)
 {
     if (ball != null)
     {
         ball.RemoveSpeed();
     }
 }
Exemplo n.º 2
0
    private void OnTriggerEnter(Collider c)
    {
        if (started)
        {
            return;
        }

        // Only allow the server player to start the game
        if (!NetworkManager.Instance.IsServer)
        {
            return;
        }

        Player player = c.GetComponent <Player>();

        if (player == null)
        {
            return;
        }
        started = true;

        // create the ball on the network
        GameBall ball = NetworkManager.Instance.InstantiateGameBall() as GameBall;

        ball.Reset();
        Destroy(gameObject);
    }
        public ActionResult PickNewNumber()
        {
            var gameInProgress = CurrentGame();

            if (gameInProgress == null)
            {
                return(RedirectToAction("GameEnded"));
            }

            var rand      = new Random();
            var newNumber = rand.Next(1, 75);

            while (gameInProgress.GameBalls.Where(x => x.Number == newNumber).Any())
            {
                //If the new number was already called, loop
                newNumber = rand.Next(1, 75);
            }

            var gameball = new GameBall {
                Game = gameInProgress, Letter = newNumber.ToBingoBallLetter(), Number = newNumber, Picked = DateTime.Now
            };

            gameInProgress.GameBalls.Add(gameball);
            Db.SaveChanges();

            Message = string.Format("Picked a new ball: {0}", newNumber.ToBingoBall());

            return(RedirectToAction("Current"));
        }
Exemplo n.º 4
0
        /// <summary>
        /// 恢复指定球碎片
        /// </summary>
        /// <param name="ball">球</param>
        private void RecoverPieces(GameBall ball)
        {
            if (ball != null)
            {
                if (ball.BallPiecesControl != null && ball.BallPiecesControl.RecoverPieces())
                {
                    return;
                }
                if (piecesThrowedBalls.Contains(ball))
                {
                    piecesThrowedBalls.Remove(ball);
                }
                if (ball.Pieces != null && ball.PiecesMaterial != null && ball.PiecesRigidbody != null)
                {
                    foreach (MeshRenderer m in ball.PiecesMaterial)
                    {
                        if (m.materials.Length > 0)
                        {
                            GameManager.UIManager.UIFadeManager.AddFadeOut(m.gameObject, 2.0f, true, m.materials);
                        }
                    }
                }

                StartCoroutine(RecoverPiecesDelay(ball));
            }
        }
Exemplo n.º 5
0
        private IEnumerator RecoverPiecesDelay(GameBall ball)
        {
            yield return(new WaitForSeconds(2.0f));

            if (ball.Pieces != null && ball.PiecesMaterial != null && ball.PiecesRigidbody != null)
            {
                foreach (Rigidbody r in ball.PiecesRigidbody)
                {
                    ICManager.ResetIC(r.gameObject);
                    r.gameObject.SetActive(true);
                }
                foreach (MeshRenderer m in ball.PiecesMaterial)
                {
                    if (m.materials.Length > 0)
                    {
                        foreach (Material ma in m.materials)
                        {
                            ma.color = new Color(ma.color.r, ma.color.g, ma.color.b, 1.0f);
                        }
                    }
                }

                ball.Pieces.SetActive(false);
                ball.CollectPiecesSecTick = ball.CollectPiecesSec;
            }
        }
Exemplo n.º 6
0
 private void CollectPiecesTick()//回收碎片tick
 {
     if (fCollectPiecesTick < 1.0f)
     {
         fCollectPiecesTick += Time.deltaTime;
     }
     else
     {
         fCollectPiecesTick = 0;
         GameBall ball = null;
         for (int i = piecesThrowedBalls.Count - 1; i >= 0; i--)
         {
             ball = piecesThrowedBalls[i];
             if (ball.CollectPiecesSecTick > 0)
             {
                 ball.CollectPiecesSecTick--;
             }
             else
             {
                 piecesThrowedBalls.Remove(ball);
                 RecoverPieces(ball);
             }
         }
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// 抛出指定球碎片
        /// </summary>
        /// <param name="ball">球</param>
        private void ThrowPieces(GameBall ball)
        {
            if (ball != null)
            {
                if (ball.BallPiecesControl != null && ball.BallPiecesControl.ThrowPieces())
                {
                    return;
                }
                if (ball.Pieces != null && ball.PiecesRigidbody != null)
                {
                    ball.Pieces.SetActive(true);

                    foreach (Rigidbody r in ball.PiecesRigidbody)
                    {
                        ICManager.ResetIC(r.gameObject);

                        r.gameObject.SetActive(true);
                        r.AddExplosionForce(ball.ThrowPiecesForce, transform.position, 6f);
                    }

                    ball.CollectPiecesSecTick = ball.CollectPiecesSec;
                    if (!piecesThrowedBalls.Contains(ball))
                    {
                        piecesThrowedBalls.Add(ball);
                    }
                }
            }
        }
Exemplo n.º 8
0
    private void OnTriggerEnter(Collider triggeringCollider)
    {
        // Only allow the server player to start the game
        // so the server is the owner of the ball
        // because if a client is the owner of the ball
        // and that client disconnects, the ball will be destroyed.
        if (!NetworkManager.Instance.IsServer)
        {
            return;
        }

        // We detect if the colliding gameobject has
        // the Component/Script Player.cs and if it doesn't have it
        // we simply don't do anything by using return;
        if (triggeringCollider.GetComponent <Player>() == null)
        {
            return;
        }


        // We need to create the ball on the network
        GameBall ball = NetworkManager.Instance.InstantiateGameBall() as GameBall;

        // Reset the ball position and give it a random velocity
        ball.Reset();

        // We destroy this trigger gameobject since we dont need it anymore.
        // This gameobject is destroyed only for the server.
        // However, it is destroyed for the client via Update() because
        // the ball is spawned.
        Destroy(gameObject);
    }
Exemplo n.º 9
0
    private void GameBallOutofRange(GameBall ball)
    {
        Vector3 position = m_gameBall.GetPosition();

        if (position.y > 0)
        {
            m_contestData.AddHeart();
            m_aiIndex = 0;
        }
        else
        {
            m_contestData.ReduceHeart();
            m_playerIndex = 0;
        }

        if (m_contestData != null && !m_contestData.m_changeAudio && m_change)
        {
//			GameAudioModuel audioModuel = GameStart.GetInstance().AudioModuel;
//			audioModuel.StopAudio();
        }

        m_contestUI.FreshUI(m_contestData.m_heart, m_contestData.m_index);
        m_gameBall.ResetVelocity();
        m_gameBall.SetPosition(m_ground.GroundData.GetFireBallPoint(ESide.Player));
        m_aiController.SwitchState(EAIControlState.BackToBornPoint);
        if (m_contestData.m_heart < 0)
        {
            m_player.SetIdle();
            m_contestUI.GameEnd();
            m_aiController.gameObject.SetActive(false);

            GameAudioModuel audioModuel = GameStart.GetInstance().AudioModuel;
            audioModuel.PlayAudio("lose");
        }
    }
Exemplo n.º 10
0
    private IEnumerator FireBall(GameBall ball, Vector2 dir, float force)
    {
        yield return(new WaitForEndOfFrame());

        ball.SetOutofRangeAction(HandleBallOutOfRangeAction);
        ball.SetActive(true);
        ball.SetPosition(m_instance.GetFireBallWorldPoint());
        ball.SetVelocity(dir, force, ESide.None);
    }
Exemplo n.º 11
0
 public virtual void OnAttach(GameBall ball)
 {
     Attached = true;
     Rigidbody.isKinematic = false;
     if (!_casualtiesCounted)
     {
         PlayerScore.AddCasualties(Casualties);
         _casualtiesCounted = true;
     }
 }
Exemplo n.º 12
0
        //球管理
        //============================

        /// <summary>
        /// 注册球
        /// </summary>
        /// <param name="name">球类型名称</param>
        /// <param name="ball">附加了GameBall组件的球实例</param>
        private bool RegisterBall(string name, GameBall ball)
        {
            if (ball == null)
            {
                GameLogger.Warning(TAG, "要注册的球 {0} 为空", name);
                GameErrorManager.LastError = GameError.ParamNotProvide;
                return(false);
            }
            return(RegisterBall(name, ball, ball.Pieces));
        }
Exemplo n.º 13
0
    public Pool(Transform holder, GameBall poolObject, int poolSize)
    {
        size        = poolSize;
        poolObjects = new GameBall[poolSize];

        for (int i = 0; i < poolSize; i++)
        {
            poolObjects[i] = Object.Instantiate(poolObject, holder);
            poolObjects[i].gameObject.SetActive(false);
        }
    }
Exemplo n.º 14
0
    public void ServieBall(Vector2 dir, float force)
    {
        if (m_instance != null)
        {
            m_instance.enabled = true;
            m_instance.PlayAnim(m_mechineData.m_servieBallAnim);
        }

        GameBall ball = CreateGameBall();

        CoroutineTool.GetInstance().StartGameCoroutine(FireBall(ball, dir, force));
    }
Exemplo n.º 15
0
 // Update is called once per frame
 void Update()
 {
     if (gameBall) {
         transform.position = gameBall.transform.position;
     } else {
         gameBall = GameObject.FindObjectOfType<GameBall>();
         if (gameBall){
             transform.position = gameBall.transform.position;
         }else{
             return;
         }
     }
 }
Exemplo n.º 16
0
    /// <summary>Starts the game.</summary>
    /// <returns>Void.</returns>
    public void StartGame()
    {
        // reset game state
        _playerLife       = 3;
        _enemyLife        = 3;
        _currentGameState = GameState.Started;
        // spawn game ball
        _gameBallObject = Instantiate(gameBallPrefab, gameBallSpawn);
        _gameBall       = _gameBallObject.GetComponent <GameBall>();
        // spawn ai player
        _enemyObject = Instantiate(enemyPrefab, enemySpawn);
        _aiPlayer    = _enemyObject.GetComponent <AIPlayer>();
        // spawn throwable obstacle (muffin)
        _throwableObstacleObject = Instantiate(throwableObstaclePrefab, throwableObstacleSpawn);
        _throwableObstacleObject.GetComponent <Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;

        // manage events
        if (_gameBall.OnPlayerGoalHit == null)
        {
            _gameBall.OnPlayerGoalHit = new UnityEvent();
        }

        if (_gameBall.OnEnemyGoalHit == null)
        {
            _gameBall.OnEnemyGoalHit = new UnityEvent();
        }

        if (_gameBall.OnThrowableObstacleHit == null)
        {
            _gameBall.OnThrowableObstacleHit = new UnityEvent();
        }

        _gameBall.OnPlayerGoalHit.RemoveListener(RegisterPlayerGoalHit);
        _gameBall.OnEnemyGoalHit.RemoveListener(RegisterEnemyGoalHit);
        _gameBall.OnThrowableObstacleHit.RemoveListener(ResetThrowableObstacle);
        _gameBall.OnPlayerGoalHit.AddListener(RegisterPlayerGoalHit);
        _gameBall.OnEnemyGoalHit.AddListener(RegisterEnemyGoalHit);
        _gameBall.OnThrowableObstacleHit.AddListener(ResetThrowableObstacle);

        // set rescue point if game ball is stuck
        _gameBall.SetRescuePoint(rescuePoint);
        // reset throwable obstacle
        ResetThrowableObstacle();
        // start AI
        _aiPlayer.StartAI(_gameBall.transform);
        // update UI
        OnGameStarted.Invoke();
        OnUpdatePlayersLife.Invoke(3, 3);
        // start timer at beginning
        StartCoroutine(CountdownToStart());
    }
Exemplo n.º 17
0
    public override void ExitState()
    {
        GameEventModuel eventModuel = GameStart.GetInstance().EventModuel;

        eventModuel.UnRegisterEventListener(GameEventID.TRIGGER_GAME_EVENT, OnTriggerEffectStart);
        eventModuel.UnRegisterEventListener(GameEventID.END_GAME_EVENT, OnTriggerEffectEnd);

        if (m_ground != null)
        {
            GameObject.Destroy(m_ground.gameObject);
            m_ground = null;
        }

        if (m_player != null)
        {
            m_player.Destroy();
            m_player = null;
        }

        if (m_playerController != null)
        {
            m_playerController.DestroyController();
            m_playerController = null;
        }

        if (m_gameBall != null)
        {
            m_gameBall.Destory();
            m_gameBall = null;
        }

        if (m_ai != null)
        {
            m_ai.Destroy();
            m_ai = null;
        }

        if (m_aiController != null)
        {
            m_aiController.DestroyController();
            m_aiController = null;
        }

        if (m_effect != null)
        {
            m_effect.Destory();
        }

        GameStart.GetInstance().UIModuel.UnLoadResUI(m_contestUI.gameObject);
    }
Exemplo n.º 18
0
        /// <summary>
        /// 激活指定的球
        /// </summary>
        /// <param name="type">球名字</param>
        private void ActiveBall(string type)
        {
            RecoverBallDef();
            GameBall ball = GetRegisteredBall(type);

            if (ball != null)
            {
                currentBallType = ball;
                currentBallType.Active(nextRecoverBallPos);
                currentBall = ball.gameObject;

                CamFollowTarget.SetData(currentContext, currentBall.transform);
                IsFollowCam.SetData(currentContext, true);
                IsLookingBall.SetData(currentContext, true);
            }
        }
Exemplo n.º 19
0
    private GameBall CreateGameBall()
    {
        GameBall ball = null;

        if (m_cacheBallList.Count > 0)
        {
            ball = m_cacheBallList[0];
            m_cacheBallList.RemoveAt(0);
        }
        else
        {
            ball = new GameBall(m_ballData, null);
        }
        m_ballList.Add(ball);
        return(ball);
    }
Exemplo n.º 20
0
        /// <summary>
        /// 取消注册球
        /// </summary>
        /// <param name="name">球类型名称</param>
        private bool UnRegisterBall(string name)
        {
            GameBall targetBall = GetRegisteredBall(name);

            if (targetBall != null)
            {
                ballTypes.Remove(targetBall);
                targetBall.Destroy();
                return(true);
            }
            else
            {
                GameLogger.Warning(TAG, "无法取消注册球 {0} 因为它没有注册", name);
                GameErrorManager.LastError = GameError.NotRegister;
                return(false);
            }
        }
Exemplo n.º 21
0
 //摄像机跟随 每帧
 private void CamFollow()
 {
     if (camFollowTarget == null)
     {
         isFollowCam = false;
         return;
     }
     if (isFollowCam)
     {
         if (!CurrentBall.IsNull())
         {
             GameBall ball = ((GameBall)CurrentBall.Data());
             ballCamFollowTarget.transform.position = Vector3.SmoothDamp(ballCamFollowTarget.transform.position, ball.transform.position, ref camVelocityTarget2, camFollowSpeed2);
             ballCamFollowTarget.transform.position = new Vector3(ballCamFollowTarget.transform.position.x, ball.transform.position.y, ballCamFollowTarget.transform.position.z);
             ballCamFollowHost.transform.position   = Vector3.SmoothDamp(ballCamFollowHost.transform.position, ball.transform.position, ref camVelocityTarget, camFollowSpeed);
         }
     }
 }
Exemplo n.º 22
0
 private void HandleBallOutOfRangeAction(GameBall ball)
 {
     if (ball == null)
     {
         return;
     }
     ball.ResetVelocity();
     ball.SetActive(false);
     m_ballList.Remove(ball);
     m_cacheBallList.Add(ball);
     m_fireBallIndex++;
     if (m_mechineData.m_fireBallCountOneRound < m_fireBallIndex)
     {
         m_instance.ServiceBall = null;
         CoroutineTool.GetInstance().StartCoroutine(StartFireBall());
         m_fireBallIndex = 0;
     }
 }
Exemplo n.º 23
0
 public GameBall[] GetInPlayerAreaBalls(Player player)
 {
     if (m_checkBalls == null)
     {
         m_checkBalls = new List <GameBall>();
     }
     m_checkBalls.Clear();
     for (int i = 0; i < m_ballList.Count; i++)
     {
         GameBall ball   = m_ballList[i];
         bool     inarea = PlayerCollider.CheckInHitBallArea(ball.GetBallInstance().transform, player.Transform,
                                                             player.PlayerData.m_radius, player.PlayerData.m_angle, player.BoxCollider);
         if (inarea)
         {
             m_checkBalls.Add(ball);
         }
     }
     return(m_checkBalls.ToArray());
 }
Exemplo n.º 24
0
        /// <summary>
        /// 注册球
        /// </summary>
        /// <param name="name">球类型名称</param>
        /// <param name="ball">附加了GameBall组件的球实例</param>
        /// <param name="pieces">球碎片组</param>
        private bool RegisterBall(string name, GameBall ball, GameObject pieces)
        {
            if (ball == null)
            {
                GameLogger.Warning(TAG, "要注册的球 {0} 为空", name);
                GameErrorManager.LastError = GameError.ParamNotProvide;
                return(false);
            }
            if (GetRegisteredBall(name) != null)
            {
                GameLogger.Log(TAG, "球 {0} 已经注册", name);
                GameErrorManager.LastError = GameError.AlredayRegistered;
                return(false);
            }

            ball.TypeName = name;
            if (pieces != null)
            {
                ball.Pieces = pieces;
            }
            ballTypes.Add(ball);

            if (pieces != null)
            {
                GameBallPiecesControl ballPiecesControl = pieces.GetComponent <GameBallPiecesControl>();
                if (ballPiecesControl != null)
                {
                    ballPiecesControl.Ball = ball;
                    ball.BallPiecesControl = ballPiecesControl;
                }
                if (pieces.activeSelf)
                {
                    pieces.SetActive(false);
                }
            }

            if (ball.gameObject.activeSelf)
            {
                ball.gameObject.SetActive(false);
            }

            return(ball.Init());
        }
Exemplo n.º 25
0
 public void Score(GameObject goal)
 {
     if (player.Defending == goal)
     {
         print("Computer Scores!");
         compScore++;
     }
     else if (computer.Defending == goal)
     {
         print("Player Scores!");
         playerScore++;
         computer.Defending.GetComponent <Goal>().ShowGoalLines(GameBall.gameObject.transform.position);
     }
     else
     {
         Debug.LogError("Issue with goal scoring!");
     }
     GameBall.Score();
     InPlay = false;
 }
Exemplo n.º 26
0
    //Creates a new ball from given ball types randomly
    void spawnBall()
    {
        //randomizer for ball spawns
        int r = Random.Range(0, 5);

        //Spawn bomb ball
        if (r == 0)
        {
            ball = (GameBall)Instantiate(BombBallPrefab, spawn.position, Quaternion.Euler(new Vector3(0, 0, 0)));
        }
        //Spawn fire ball
        else if (r == 1)
        {
            ball = (GameBall)Instantiate(FireBallPrefab, spawn.position, Quaternion.Euler(new Vector3(0, 0, 0)));
        }
        //spawn normal ball
        else
        {
            ball = (GameBall)Instantiate(BallPrefab, spawn.position, Quaternion.Euler(new Vector3(0, 0, 0)));
        }
        //set the game controller of the ball we made (used to send score back)
        ball.game = this;
    }
Exemplo n.º 27
0
    public void Serve()
    {
        if (!InPlay && !servePrepped)
        {
            PrepServe();
            return;
        }

        Collider     paddleCol = player.GetComponent <Collider>();
        Vector3      paddleCtr = player.gameObject.transform.position;
        PaddlePlayer paddle    = player.GetComponent <PaddlePlayer>();

        float paddleX = paddleCol.bounds.extents.x;
        float paddleY = paddleCol.bounds.extents.y;

        if (launchPoint.x <= paddleCtr.x + paddleX && launchPoint.x >= paddleCtr.x - paddleX &&     // between x direction
            launchPoint.y <= paddleCtr.y + paddleY && launchPoint.y >= paddleCtr.y - paddleY)       // between y direction
        {
            GameBall.Serve(paddle.Velocity);

            InPlay       = true;
            servePrepped = false;
        }
    }
Exemplo n.º 28
0
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            LoadPlayerSprites();
            LoadBallSprites();

            CreatePlayerAnimations();
            CreateBallAnimations();

            GameStadium Stadium = new GameStadium(spriteBatch, Texture2D.FromFile(GraphicsDevice, @"Graphics\Stadium\Template2.png"), Texture2D.FromFile(GraphicsDevice, @"Graphics\Stadium\Grass6.png"));

            Player        = new GamePlayer();
            Player.Sprite = new AnimatedSprite(Player, spriteBatch, playerTextures[0, 0], ClonePlayerAnimations());

            GameBall Ball = new GameBall();

            Ball.Sprite    = new AnimatedSprite(Ball, spriteBatch, ballTextures[0, 0], CloneBallAnimations());
            Ball.BallPoint = new Point(450, 235);

            Match = new GameMatch(spriteBatch, Content.Load <SpriteFont>("Fonts/Small"), new GameTeam(), new GameTeam(), Stadium, Ball, 5);
            Match.StartMatch();
        }
Exemplo n.º 29
0
 private void Awake()
 {
     _gameBall = GetComponentInParent <GameBall>();
 }
Exemplo n.º 30
0
        private static async Task RunDemoAsync()
        {
            Container gamesContainer = Program.database.GetContainer(containerId);

            // This code demonstrates interactions by a multi-player game service that hosts games with the database to save game state.
            // In this fictional game, players move about the 10x10 map and try to find balls.
            // The objective is to collect 2 balls of the same color, or a golden ball if one appears.
            // After 5 minutes, if the game is not complete, the player with highest number of balls wins.
            int                    gameId      = 420;
            int                    playerCount = 3;
            int                    ballCount   = 4;
            List <GameBall>        balls       = new List <GameBall>();
            List <GameParticipant> players     = new List <GameParticipant>();

            Console.WriteLine("At the start of the game, the balls are added on the map, and the players are added ...");

            // The below batch request is used to create the game balls and participants in an atomic fashion.
            TransactionalBatchResponse gameStartResponse = await gamesContainer.CreateTransactionalBatch(new PartitionKey(gameId))
                                                           .CreateItem <GameBall>(GameBall.Create(gameId, Color.Red, 4, 2))
                                                           .CreateItem <GameBall>(GameBall.Create(gameId, Color.Blue, 6, 4))
                                                           .CreateItem <GameBall>(GameBall.Create(gameId, Color.Blue, 8, 7))
                                                           .CreateItem <GameBall>(GameBall.Create(gameId, Color.Red, 8, 8))
                                                           .CreateItem <GameParticipant>(GameParticipant.Create(gameId, "alice"))
                                                           .CreateItem <GameParticipant>(GameParticipant.Create(gameId, "bob"))
                                                           .CreateItem <GameParticipant>(GameParticipant.Create(gameId, "carla"))
                                                           .ExecuteAsync();

            GameParticipant alice, bob, carla;
            GameBall        firstBlueBall, secondRedBall;

            using (gameStartResponse)
            {
                // Batch requests do not throw exceptions on execution failures as long as the request is valid, so we need to check the response status explicitly.
                // A HTTP 200 (OK) StatusCode on the batch response indicates that all operations succeeded.
                // An example later demonstrates a failure case.
                if (!gameStartResponse.IsSuccessStatusCode)
                {
                    // Log and handle failure
                    LogFailure(gameStartResponse);
                    return;
                }

                // Refresh in-memory state from response.
                // The TransactionalBatchResponse has a list of TransactionalBatchOperationResult, one for each operation within the batch request in the order
                // the operations were added to the TransactionalBatch.
                for (int index = 0; index < ballCount; index++)
                {
                    // The GetOperationResultAtIndex method returns the result of the operation at the given index with a Resource deserialized to the provided type.
                    TransactionalBatchOperationResult <GameBall> gameBallResult = gameStartResponse.GetOperationResultAtIndex <GameBall>(index);
                    balls.Add(gameBallResult.Resource);
                }

                firstBlueBall = balls[1];
                secondRedBall = balls[3];

                for (int index = ballCount; index < gameStartResponse.Count; index++)
                {
                    players.Add(gameStartResponse.GetOperationResultAtIndex <GameParticipant>(index).Resource);
                }

                alice = players.Single(p => p.Nickname == "alice");
                bob   = players.Single(p => p.Nickname == "bob");
                carla = players.Single(p => p.Nickname == "carla");
            }

            PrintState(players, balls);

            Console.WriteLine("Alice goes to 6, 4 and finds a blue ball ...");
            alice.BlueCount++;

            // Upserts maybe used to replace items or create them if they are not already present.
            // An existing item maybe replaced along with concurrency checks the ETag returned in the responses of earlier requests on the item
            // or without these checks if they are not required.
            // Item deletes may also be a part of batch requests.
            TransactionalBatchResponse aliceFoundBallResponse = await gamesContainer.CreateTransactionalBatch(new PartitionKey(gameId))
                                                                .UpsertItem <ParticipantLastActive>(ParticipantLastActive.Create(gameId, "alice"))
                                                                .ReplaceItem <GameParticipant>(alice.Nickname, alice, new TransactionalBatchItemRequestOptions {
                IfMatchEtag = alice.ETag
            })
                                                                .DeleteItem(firstBlueBall.Id)
                                                                .ExecuteAsync();

            using (aliceFoundBallResponse)
            {
                if (!aliceFoundBallResponse.IsSuccessStatusCode)
                {
                    // Log and handle failure
                    alice.BlueCount--;
                    LogFailure(aliceFoundBallResponse);
                    return;
                }

                // Refresh in-memory state from response.
                balls.Remove(firstBlueBall);

                // We only update the etag as we have the rest of the state we care about here already as needed.
                alice.ETag = aliceFoundBallResponse[1].ETag;
            }

            PrintState(players, balls);

            Console.WriteLine("Bob goes to 8, 8 and finds a red ball ...");
            bob.RedCount++;

            // Stream variants for all batch operations that accept an item are also available for use when the item is available as a Stream.
            Stream bobIsActiveStream = ParticipantLastActive.CreateStream(gameId, "bob");
            Stream bobAsStream       = Program.AsStream(bob);

            using (bobIsActiveStream)
                using (bobAsStream)
                {
                    TransactionalBatchResponse bobFoundBallResponse = await gamesContainer.CreateTransactionalBatch(new PartitionKey(gameId))
                                                                      .UpsertItemStream(bobIsActiveStream)
                                                                      .ReplaceItemStream(bob.Nickname, bobAsStream, new TransactionalBatchItemRequestOptions {
                        IfMatchEtag = bob.ETag
                    })
                                                                      .DeleteItem(secondRedBall.Id)
                                                                      .ExecuteAsync();

                    using (bobFoundBallResponse)
                    {
                        if (!bobFoundBallResponse.IsSuccessStatusCode)
                        {
                            // Log and handle failure.
                            bob.RedCount--;
                            LogFailure(bobFoundBallResponse);
                            return;
                        }

                        // Refresh in-memory state from response.
                        balls.Remove(secondRedBall);

                        // The resultant item for each operation is also available as a Stream that can be used for example if the response is just
                        // going to be transferred to some other system.
                        Stream updatedPlayerAsStream = bobFoundBallResponse[1].ResourceStream;

                        bob = Program.FromStream <GameParticipant>(updatedPlayerAsStream);
                    }
                }

            PrintState(players, balls);

            Console.WriteLine("A golden ball appears near each of the players to select an instant winner ...");
            TransactionalBatchResponse goldenBallResponse = await gamesContainer.CreateTransactionalBatch(new PartitionKey(gameId))
                                                            .CreateItem <GameBall>(GameBall.Create(gameId, Color.Gold, 2, 2))
                                                            .CreateItem <GameBall>(GameBall.Create(gameId, Color.Gold, 6, 3))
                                                            // oops - there is already a ball at 8, 7
                                                            .CreateItem <GameBall>(GameBall.Create(gameId, Color.Gold, 8, 7))
                                                            .ExecuteAsync();

            using (goldenBallResponse)
            {
                // If an operation within the TransactionalBatch fails during execution, the TransactionalBatchResponse will have a status code of the failing operation.
                // The TransactionalBatchOperationResult entries within the response can be read to get details about the specific operation that failed.
                // The failing operation (for example if we have a conflict because we are trying to create an item
                // that already exists) will have the StatusCode on its corresponding TransactionalBatchOperationResult set to the actual failure status
                // (HttpStatusCode.Conflict in this example). All other result entries will have a status code of HTTP 424 Failed Dependency.
                // In case any operation within a TransactionalBatch fails, no changes from the batch will be committed.
                // Other status codes such as HTTP 429 (Too Many Requests) and HTTP 5xx on server errors may also be returned on the TransactionalBatchResponse.
                if (!goldenBallResponse.IsSuccessStatusCode)
                {
                    if (goldenBallResponse.StatusCode == HttpStatusCode.Conflict)
                    {
                        for (int index = 0; index < goldenBallResponse.Count; index++)
                        {
                            TransactionalBatchOperationResult operationResult = goldenBallResponse[index];
                            if ((int)operationResult.StatusCode == 424)
                            {
                                // This operation failed because it was in a TransactionalBatch along with another operation where the latter was the actual cause of failure.
                                continue;
                            }
                            else if (operationResult.StatusCode == HttpStatusCode.Conflict)
                            {
                                Console.WriteLine("Creation of the {0}rd golden ball failed because there was already an existing ball at that position.", index + 1);
                            }
                        }
                    }
                    else
                    {
                        // Log and handle other failures
                        LogFailure(goldenBallResponse);
                        return;
                    }
                }
            }

            PrintState(players, balls);

            Console.WriteLine("We need to end the game now; determining the winner as the player with highest balls ...");

            // Batch requests may also be used to atomically read multiple items with the same partition key.
            TransactionalBatchResponse playersResponse = await gamesContainer.CreateTransactionalBatch(new PartitionKey(gameId))
                                                         .ReadItem(alice.Nickname)
                                                         .ReadItem(bob.Nickname)
                                                         .ReadItem(carla.Nickname)
                                                         .ExecuteAsync();

            GameParticipant winner = null;
            bool            isTied = false;

            using (playersResponse)
            {
                if (!playersResponse.IsSuccessStatusCode)
                {
                    // Log and handle failure
                    LogFailure(playersResponse);
                    return;
                }

                for (int index = 0; index < playerCount; index++)
                {
                    GameParticipant current;

                    if (index == 0)
                    {
                        // The item returned can be made available as the required POCO type using GetOperationResultAtIndex.
                        // A single batch request can be used to read items that can be deserialized to different POCOs as well.
                        current = playersResponse.GetOperationResultAtIndex <GameParticipant>(index).Resource;
                    }
                    else
                    {
                        // The item returned can also instead be accessed directly as a Stream (for example to pass as-is to another component).
                        Stream aliceInfo = playersResponse[index].ResourceStream;

                        current = Program.FromStream <GameParticipant>(aliceInfo);
                    }

                    if (winner == null || current.TotalCount > winner.TotalCount)
                    {
                        winner = current;
                        isTied = false;
                    }
                    else if (current.TotalCount == winner.TotalCount)
                    {
                        isTied = true;
                    }
                }
            }

            if (!isTied)
            {
                Console.WriteLine($"{winner.Nickname} has won the game!\n");
            }
            else
            {
                Console.WriteLine("The game is a tie; there is no clear winner.\n");
            }
        }
Exemplo n.º 31
0
 public void SetGameBall(GameBall ball)
 {
     m_target = ball.GetBallInstance().transform;
 }
Exemplo n.º 32
0
 // Use this for initialization
 void Start()
 {
     gameBall = GameObject.FindObjectOfType<GameBall> ();
 }