Exemplo n.º 1
0
        public async Task <ActionResult <Game> > RegisterGame(JObject json)
        {
            // Get players from Db with ids from json object
            // NOTE: This is not the best way to do this
            Player playerOne = await _context.Players.FindAsync((int)json["players"][0]["id"]);

            Player playerTwo = await _context.Players.FindAsync((int)json["players"][1]["id"]);

            if (playerOne == null || playerTwo == null)
            {
                return(NotFound());
            }

            // Create new game with players
            Game newGame = new Game();

            newGame.PlayerOne = playerOne;
            newGame.PlayerTwo = playerTwo;

            // Deal out hands
            // Load cards into a deck
            List <Card> deck = await _context.Cards.ToListAsync();

            // Shuffle deck based on Fisher–Yates shuffle algorithm
            Random random = new Random();

            for (int i = deck.Count - 1; i > 1; i--)
            {
                int  rnd  = random.Next(i + 1);
                Card temp = deck[rnd];
                deck[rnd] = deck[i];
                deck[i]   = temp;
            }
            // Give each player hand (in game object) 5 cards from the same deck, removing the given card from the deck to avoid duplicates
            newGame.PlayerOneHand = new List <Card>();
            newGame.PlayerTwoHand = new List <Card>();
            for (int i = 0; i < 5; i++)
            {
                // Fake DeQueue (from front of list)
                newGame.PlayerOneHand.Add(deck[0]);
                deck.RemoveAt(0);
                newGame.PlayerTwoHand.Add(deck[0]);
                deck.RemoveAt(0);
            }
            // Add Game to Context
            _context.Games.Add(newGame);
            await _context.SaveChangesAsync();

            return(newGame);
        }