Beispiel #1
0
        public IGameQueue QueueChallenge(string language, int boardId, string challengerName, string challengedNamed)
        {
            if (challengerName == null || challengerName == challengedNamed)
            {
                throw new InvalidOperationException("Invalid Challenge");
            }

            /*
             * Does the queue has player2 ?
             * If it does game hub will send a game request to player2
             * If player 2 accepts the challenge gamehub will receive an OK with the Queue ID and the that will start
             * Otherwise the queue will removed and the game will be canceled
             *
             * If the queue doesn't have a player2 search the queue for an awaiting game with the same characteristics
             * if a match is found then start the game
             * if not this stays in queue until a new match is found
             */

            var newQueue = new GameQueue
            {
                Id        = Guid.NewGuid().ToString(),
                Language  = language,
                Player1   = challengerName,
                Player2   = challengedNamed,
                BoardId   = boardId,
                QueueDate = DateTime.UtcNow
            };

            logger.Info($"Nem game in queue. P1:{challengerName} P2:{challengedNamed} Language:{language} Board:{boardId}");

            ProcessQueue(newQueue);
            return(newQueue);
        }
        public void JoinGameTwice()
        {
            string userID = "jhonny";

            var userRepository = this.CreateUserRepository();
            var gameRepository = this.CreateGameRepository();

            this.CreateUser(userRepository, userID);

            GameService gameService = this.CreateGameService(gameRepository, userRepository, userID);

            var response = gameService.Create();
            var id       = response.Content.ReadAsStringAsync().Result;
            var gameId   = Guid.Parse(id);

            var response2 = gameService.Join(gameId);

            Assert.IsTrue(response2.IsSuccessStatusCode);

            GameQueue gameQueue = this.gameQueueContainer.Get(gameId.ToString());

            Assert.IsNotNull(gameQueue);
            Assert.AreEqual(1, gameQueue.Users.Count);
            Assert.AreEqual(userID, gameQueue.Users[0].UserId);
        }
Beispiel #3
0
        private void QueueList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var src = sender as ListBox;

            if (src.SelectedIndex < 0)
            {
                return;
            }
            var queue = (GameQueue)((ListBox)sender).SelectedItem;

            if (queue.Action1 != null)
            {
                QueueButton1.Visibility = Visibility.Visible;
                QueueButton1.Content    = queue.Action1;
            }
            else
            {
                QueueButton1.Visibility = Visibility.Collapsed;
            }

            if (queue.Action2 != null)
            {
                QueueButton2.Visibility = Visibility.Visible;
                QueueButton2.Content    = queue.Action2;
            }
            else
            {
                QueueButton2.Visibility = Visibility.Collapsed;
            }
            selected = queue;
        }
Beispiel #4
0
        public Game StartGame(Guid gameQueueId)
        {
            GameQueue queue = this.gameQueueContainer.Get(gameQueueId.ToString());

            if (queue == null)
            {
                throw new InvalidOperationException(string.Format("Game Queue does not exist: {0}", gameQueueId));
            }

            if (queue.Status != QueueStatus.Waiting)
            {
                throw new InvalidOperationException(string.Format("Game Queue Status is not Waiting: {0}", gameQueueId));
            }

            // Create game
            var game = new Game
            {
                Id         = Guid.NewGuid(),
                Users      = queue.Users,
                ActiveUser = queue.Users.First().UserId,
                Status     = GameStatus.Waiting,
                Seed       = new Random().Next(10000, int.MaxValue)
            };

            queue.Status = QueueStatus.Ready;
            queue.GameId = game.Id;

            this.gameContainer.Save(game.Id.ToString(), game);
            this.gameQueueContainer.Save(gameQueueId.ToString(), queue);

            return(game);
        }
        public void StartGame()
        {
            string userID = "jhonny";

            var userRepository = this.CreateUserRepository();
            var gameRepository = this.CreateGameRepository();

            this.CreateUser(userRepository, userID);

            GameService gameService = this.CreateGameService(gameRepository, userRepository, userID);

            var response = gameService.Create();

            var id     = response.Content.ReadAsStringAsync().Result;
            var gameId = Guid.Parse(id);

            gameService.Start(gameId);

            GameQueue gameQueue = this.gameQueueContainer.Get(gameId.ToString());

            Assert.IsNotNull(gameQueue);
            Assert.AreEqual(QueueStatus.Ready, gameQueue.Status);
            Assert.AreNotEqual(Guid.Empty, gameQueue.GameId);

            Game game = this.gameContainer.Get(gameQueue.GameId.ToString());

            Assert.IsNotNull(game);
            Assert.IsNotNull(game.Users);
            Assert.AreEqual(1, game.Users.Count);
            Assert.AreEqual(userID, game.Users[0].UserId);
        }
Beispiel #6
0
        private Mock <IWorkerContext> CreateMockWorkerContext(GameQueue gameQueue)
        {
            var workerContext = this.CreateMockWorkerContext();

            workerContext.Object.Context.TryAdd("currentGameQueueId", gameQueue.Id);

            return(workerContext);
        }
Beispiel #7
0
        private Mock <IGameRepository> CreateGameRepository(GameQueue gameQueue)
        {
            var gameRepository = new Mock <IGameRepository>();

            gameRepository.Setup(m => m.GetGameQueue(gameQueue.Id)).Returns(gameQueue);
            gameRepository.Setup(m => m.AddOrUpdateGameQueue(gameQueue));

            return(gameRepository);
        }
Beispiel #8
0
    public void Dequeue(GameQueue queue)
    {
        if (!isInQueue)
        {
            return;
        }

        isInQueue = false;
        queue.Remove(this);
    }
Beispiel #9
0
    public void Queue(GameQueue queue, List <int> modes)
    {
        if (isInQueue)
        {
            return;
        }

        isInQueue = true;
        queue.Add(this, modes);
    }
        public void AddUserToNewSkirmishGameWhenCurrentGameIsReadyTest()
        {
            var startingDateTime = DateTime.Parse("01/01/2001 00:00:00");
            var testUserId       = Guid.NewGuid().ToString();
            var testGameId2      = Guid.Empty;
            var testGameQueue1   = new GameQueue
            {
                Id    = Guid.NewGuid(),
                Users = new List <GameUser> {
                    new GameUser {
                        UserId = testUserId
                    }
                },
                Status       = QueueStatus.Ready,
                CreationTime = startingDateTime
            };

            var workerContext = new Mock <IWorkerContext>();
            var testContext   = new ConcurrentDictionary <string, object>();

            testContext.GetOrAdd("currentGameQueueId", testGameQueue1.Id);
            workerContext.SetupGet(p => p.Context).Returns(testContext);

            var gameRepository = new Mock <IGameRepository>();

            gameRepository.Setup(m => m.GetGameQueue(It.Is <Guid>(g => g == testGameQueue1.Id)))
            .Returns(testGameQueue1)
            .Verifiable();

            gameRepository.Setup(m => m.AddOrUpdateGameQueue(It.Is <GameQueue>(g => g.Id != Guid.Empty && g.Id != testGameQueue1.Id && g.Status == QueueStatus.Waiting && g.Users.Count == 1 && g.Users.First().UserId == testUserId)))
            .Callback(() => { testGameId2 = new Guid(workerContext.Object.Context["currentGameQueueId"].ToString()); })
            .Verifiable();

            var userRepository = new Mock <IUserRepository>();

            userRepository.Setup(m => m.GetUser(It.Is <string>(u => u == testUserId)))
            .Returns(new UserProfile {
                Id = testUserId
            })
            .Verifiable();
            userRepository.Setup(m => m.AddOrUpdateUserSession(It.Is <UserSession>(s => s.UserId == testUserId && s.ActiveGameQueueId == testGameId2)))
            .Verifiable();

            var command = new SkirmishGameQueueCommand(userRepository.Object, gameRepository.Object, workerContext.Object);
            var context = new Dictionary <string, object>
            {
                { "userId", testUserId }
            };

            command.Do(context);

            gameRepository.VerifyAll();
            userRepository.VerifyAll();
        }
Beispiel #11
0
        public void AddOrUpdateGameQueue(GameQueue gameQueue)
        {
            if (gameQueue == null)
            {
                throw new ArgumentNullException("gameQueue");
            }

            if (gameQueue.Id == Guid.Empty)
            {
                throw new ArgumentException("GameQueue Id cannot be empty");
            }

            this.gameQueueContainer.Save(gameQueue.Id.ToString(), gameQueue);
        }
Beispiel #12
0
        public void ShouldDoDoNothingIfGameQueueIdIsEmpty()
        {
            // Arrange: Create current game with empty ID
            var gameQueue = new GameQueue
            {
                Id    = Guid.Empty,
                Users = new List <GameUser> {
                    new GameUser {
                        UserId = "johnny"
                    }
                },
                Status       = QueueStatus.Waiting,
                CreationTime = DateTime.Parse("01/01/2011 13:00:00")
            };

            int usersCount = gameQueue.Users.Count();

            // Arrange: Create mock dependencies
            //          Set current game in repository and workerContext
            var gameRepository = new Mock <IGameRepository>();

            gameRepository.Setup(m => m.GetGameQueue(gameQueue.Id)).Returns(gameQueue);
            gameRepository.Setup(m => m.AddOrUpdateGameQueue(gameQueue));
            var workerContext = this.CreateMockWorkerContext();

            workerContext.Object.Context.TryAdd("currentGameQueueId", gameQueue.Id);

            // Arrange: Create the command
            TimeSpan timeout            = TimeSpan.FromSeconds(30);
            int      maxNumberOfPlayers = 3;
            var      command            = new GameQueueAutoStartCommand(
                gameRepository.Object,
                workerContext.Object,
                timeout,
                maxNumberOfPlayers);

            // Arrange: Set current date time to timeout the game
            TimeProvider.Current = new FixedTimeProvider()
            {
                CurrentDateTime = gameQueue.CreationTime + timeout
            };

            // Act: Execute the command. It should do nothing as the game ID is empty
            command.Do(null);

            // Assert: Verify that the game wasn't modified
            Assert.AreEqual(gameQueue.Status, QueueStatus.Waiting);
            Assert.AreEqual(gameQueue.Users.Count(), usersCount);
        }
Beispiel #13
0
        public void LeaveGameQueueTest()
        {
            var testUserId    = Guid.NewGuid().ToString();
            var testGameQueue = new GameQueue
            {
                Id    = Guid.NewGuid(),
                Users = new List <GameUser>
                {
                    new GameUser {
                        UserId = Guid.NewGuid().ToString()
                    },
                    new GameUser {
                        UserId = testUserId
                    },
                    new GameUser {
                        UserId = Guid.NewGuid().ToString()
                    }
                }
            };

            var gameRepository = new Mock <IGameRepository>();

            gameRepository.Setup(m => m.GetGame(It.Is <Guid>(g => g == testGameQueue.Id)))
            .Returns((Game)null)
            .Verifiable();
            gameRepository.Setup(m => m.GetGameQueue(It.Is <Guid>(g => g == testGameQueue.Id)))
            .Returns(testGameQueue)
            .Verifiable();

            gameRepository.Setup(m => m.AddOrUpdateGameQueue(It.Is <GameQueue>(g => g.Id == testGameQueue.Id && g.Users.Count == 2 && !g.Users.Any(u => u.UserId == testUserId))))
            .Verifiable();

            var userRepository = new Mock <IUserRepository>();

            userRepository.Setup(m => m.AddOrUpdateUserSession(It.Is <UserSession>(s => s.UserId == testUserId && s.ActiveGameQueueId == Guid.Empty)))
            .Verifiable();

            var command = new LeaveGameCommand(userRepository.Object, gameRepository.Object);
            var context = new Dictionary <string, object>
            {
                { "gameId", testGameQueue.Id },
                { "userId", testUserId }
            };

            command.Do(context);

            gameRepository.VerifyAll();
            userRepository.VerifyAll();
        }
Beispiel #14
0
        void Awake()
        {
            if (Instance == null)
            {
                Instance = this;
            }
            else
            {
                Destroy(this);
            }

            CardManager.Initialize();
            Settings = new GameSettings();
            GameQueue.Start();
        }
Beispiel #15
0
        /// <summary>
        /// Enqueues a start of a player turn.
        /// A card(s) is drawn for player, turn start event is called and player is given control over his hand and board.
        /// </summary>
        public void StartPlayerTurn()
        {
            PlayerTurnCount++;

            int resourcesIncrease = Settings.TurnStartResourceIncreaseSetting(PlayerTurnCount, true,
                                                                              MatchInfo.PlayerGoesFirst, PlayerResources.ResourcesCount);

            PlayerResources.TurnStart(resourcesIncrease);

            int cardsToDraw = Settings.TurnStartCardDrawSetting(PlayerTurnCount, true, MatchInfo.PlayerGoesFirst);

            GameQueue.PlayerDrawCards(cardsToDraw);
            Debug.Log("Started player turn " + PlayerTurnCount + ". " + cardsToDraw + " card(s) drawn. Now has " +
                      PlayerResources.ResourcesCount + " resources.");
        }
Beispiel #16
0
        public void AutoStartSkirmishGameTest()
        {
            var startingDateTime   = DateTime.Parse("01/01/2001 00:00:00");
            var testTimeout        = TimeSpan.FromSeconds(30);
            var maxNumberOfPlayers = 3;
            var testUser1Id        = Guid.NewGuid().ToString();
            var testUser2Id        = Guid.NewGuid().ToString();
            var testGameQueue      = new GameQueue
            {
                Id    = Guid.NewGuid(),
                Users = new List <GameUser> {
                    new GameUser {
                        UserId = testUser1Id
                    }, new GameUser {
                        UserId = testUser2Id
                    }
                },
                Status       = QueueStatus.Waiting,
                CreationTime = startingDateTime
            };

            var workerContext = new Mock <IWorkerContext>();
            var testContext   = new ConcurrentDictionary <string, object>();

            testContext.GetOrAdd("currentGameQueueId", testGameQueue.Id);
            workerContext.SetupGet(p => p.Context).Returns(testContext);

            var gameRepository = new Mock <IGameRepository>();

            gameRepository.Setup(m => m.GetGameQueue(It.Is <Guid>(g => g == testGameQueue.Id)))
            .Returns(testGameQueue)
            .Callback(() => { timeProvider.CurrentDateTime = startingDateTime + testTimeout; })
            .Verifiable();

            gameRepository.Setup(m => m.AddOrUpdateGameQueue(It.Is <GameQueue>(g => g.Id == testGameQueue.Id && g.Status == QueueStatus.Ready && g.Users.Count == maxNumberOfPlayers && g.Users.ElementAt(0).UserId == testUser1Id && g.Users.ElementAt(1).UserId == testUser2Id && g.Users.ElementAt(2).UserId.StartsWith("Bot-"))))
            .Callback(() => { testGameQueue.Id = new Guid(workerContext.Object.Context["currentGameQueueId"].ToString()); })
            .Verifiable();

            var command = new GameQueueAutoStartCommand(gameRepository.Object, workerContext.Object, testTimeout, maxNumberOfPlayers);
            var context = new Dictionary <string, object>
            {
                { "userId", testUser1Id }
            };

            command.Do(context);

            gameRepository.VerifyAll();
        }
Beispiel #17
0
        public void ShouldDoNotStartSameGameTwiceIfWeExecuteTwoCommands()
        {
            // Arrange: Create current game and Mock Dependencies
            var johnnyId = "johnny";
            var peterId  = "peter";

            var gameQueue = new GameQueue
            {
                Id    = Guid.NewGuid(),
                Users = new List <GameUser> {
                    new GameUser {
                        UserId = johnnyId
                    }, new GameUser {
                        UserId = peterId
                    }
                },
                Status       = QueueStatus.Waiting,
                CreationTime = DateTime.Parse("01/01/2011 13:00:00")
            };

            var gameRepository = this.CreateGameRepository(gameQueue);
            var workerContext  = this.CreateMockWorkerContext(gameQueue);

            // Arrange: Create the command
            TimeSpan timeout            = TimeSpan.FromSeconds(30);
            int      maxNumberOfPlayers = 3;
            var      command            = new GameQueueAutoStartCommand(gameRepository.Object, workerContext.Object, timeout, maxNumberOfPlayers);

            // Arrange: Set current date time to timeout the game
            this.SetCurrentDateTime(gameQueue.CreationTime + timeout);

            // Arrange: We execute the command for the first time
            command.Do(null);

            // Arrange: We simulate some play has been done, and peter decided to quit
            gameQueue.Users.RemoveAll(u => u.UserId == peterId);
            Assert.AreEqual(gameQueue.Users.Count(), 1);

            // Act: The command shouldn't find any current game, and should do nothing
            command.Do(null);

            // Assert: We verify that our game still has only 1 player (as peter quit)
            Assert.AreEqual(gameQueue.Status, QueueStatus.Ready);
            Assert.AreEqual(gameQueue.Users.Count(), 1);
            Assert.IsTrue(gameQueue.Users.Any(u => u.UserId == johnnyId));
            Assert.IsFalse(gameQueue.Users.Any(u => u.UserId == peterId));
            Assert.AreEqual(this.BotsCount(gameQueue), 0);
        }
Beispiel #18
0
        /// <summary>
        /// Immediately cleans-up the match, destroying all cards in hands, decks and boards.
        /// Prepares everything for new match.
        /// </summary>
        public void CleanUpMatch()
        {
            GameQueue.CleanUp();

            PlayerHand.CleanUp();
            EnemyHand.CleanUp();

            PlayerDeck.CleanUp();
            EnemyDeck.CleanUp();

            CardManager.CleanUp();

            MatchInfo       = null;
            PlayerTurnCount = 0;
            EnemyTurnCount  = 0;
        }
Beispiel #19
0
        // Function to initialize a new battle, for trainers and wild Delts
        public void InitializeBattle()
        {
            GameQueue.QueueImmediate(action: () => GameQueue.Inst.ChangeQueueType(GameQueue.QueueType.Battle));

            BattleManager.Inst.BattleUI.InitializeNewBattle();

            PlayBattleMusic();

            State.PlayerState.Delts = GameManager.Inst.deltPosse;

            // Select current battling Delts, update UI
            InitialSwitchIn(isPlayer: true);
            InitialSwitchIn(isPlayer: false);

            PromptDeltItemBuffs(isPlayer: true);
            PromptDeltItemBuffs(isPlayer: false);
        }
Beispiel #20
0
        public void ShouldDoNotAutoStartIfEnoughtPlayers()
        {
            // Arrange: Create current game and Mock Dependencies
            var johnnyId  = "johnny";
            var peterId   = "peter";
            var lanaId    = "lana";
            var gameQueue = new GameQueue
            {
                Id    = Guid.NewGuid(),
                Users = new List <GameUser> {
                    new GameUser {
                        UserId = johnnyId
                    }, new GameUser {
                        UserId = peterId
                    }, new GameUser {
                        UserId = lanaId
                    }
                },
                Status       = QueueStatus.Waiting,
                CreationTime = DateTime.Parse("01/01/2011 13:00:00")
            };

            var gameRepository    = this.CreateGameRepository(gameQueue);
            var workerContext     = this.CreateMockWorkerContext(gameQueue);
            var humanPlayersCount = gameQueue.Users.Count();

            // Arrange: Create the command
            TimeSpan timeout            = TimeSpan.FromSeconds(30);
            int      maxNumberOfPlayers = 3;
            var      command            = new GameQueueAutoStartCommand(gameRepository.Object, workerContext.Object, timeout, maxNumberOfPlayers);

            // Arrange: Set current date time to timeout the game
            this.SetCurrentDateTime(gameQueue.CreationTime + timeout);

            // Act: Execute the command
            command.Do(null);

            // Assert: Verify that the game was modified to start with bots but still has johnny and peter
            Assert.AreEqual(gameQueue.Status, QueueStatus.Waiting);
            Assert.AreEqual(gameQueue.Users.Count(), maxNumberOfPlayers);
            Assert.IsTrue(gameQueue.Users.Any(u => u.UserId == johnnyId));
            Assert.IsTrue(gameQueue.Users.Any(u => u.UserId == peterId));
            Assert.IsTrue(gameQueue.Users.Any(u => u.UserId == lanaId));
            Assert.AreEqual(this.BotsCount(gameQueue), 0);
        }
Beispiel #21
0
        /// <summary>
        /// Card was played from hand.
        /// </summary>
        /// <param name="card">Played card.</param>
        public void CardPlayedFromHand(GameObject card)
        {
            card.GetComponent <CanBeInteractedWith>().InteractionAllowed = false;
            bool player = card.GetComponent <CanBeOwned>().PlayerOwned;
            Hand hand   = player ? PlayerHand : EnemyHand;

            hand.Remove(card.GetComponent <CanBeInHand>());

            GameResources resources = player ? PlayerResources : EnemyResources;
            int           cost      = card.GetComponent <HasCost>().CurrentCost;

            resources.Pay(cost);

            Debug.Log("Playing card from hand. It cost " + cost + ".");

            GameQueue.PlayCard(card);
            GameQueue.DestroyCard(card);
        }
Beispiel #22
0
        public void ShouldDoDoNothingIfCurrentGameDoesntHaveAnyUser()
        {
            // Arrange: Create current game
            var gameQueue = new GameQueue
            {
                Id           = Guid.NewGuid(),
                Users        = new List <GameUser> {
                },
                Status       = QueueStatus.Waiting,
                CreationTime = DateTime.Parse("01/01/2011 13:00:00")
            };

            int usersCount = gameQueue.Users.Count();

            // Arrange: Create mock dependencies
            //          Set current game in repository
            var gameRepository = new Mock <IGameRepository>();

            gameRepository.Setup(m => m.GetGameQueue(gameQueue.Id)).Returns(gameQueue);
            gameRepository.Setup(m => m.AddOrUpdateGameQueue(gameQueue));
            var workerContext = this.CreateMockWorkerContext();

            // Arrange: Intentionally we are NOT doing the next step
            workerContext.Object.Context.TryAdd("currentGameQueueId", gameQueue.Id);

            // Arrange: Create the command
            TimeSpan timeout            = TimeSpan.FromSeconds(30);
            int      maxNumberOfPlayers = 3;
            var      command            = new GameQueueAutoStartCommand(gameRepository.Object, workerContext.Object, timeout, maxNumberOfPlayers);

            // Arrange: Set current date time so the game has timed out
            TimeProvider.Current = new FixedTimeProvider()
            {
                CurrentDateTime = gameQueue.CreationTime + timeout
            };

            // Act: Execute the command. It should do nothing as the current game isn't in the worker context
            command.Do(null);

            // Assert: Verify that the game wasn't modified
            Assert.AreEqual(gameQueue.Status, QueueStatus.Waiting);
            Assert.AreEqual(gameQueue.Users.Count(), usersCount);
        }
Beispiel #23
0
        // Function to initialize a new battle, for trainers and wild Delts
        public void InitializeBattle()
        {
            GameQueue.WorldAdd(action: () => GameQueue.Inst.ChangeQueueType(GameQueue.QueueType.Battle));

            BattleManager.Inst.BattleUI.LoadBackgroundAndPodium();

            PlayBattleMusic();

            // Clear temp battle stats for player and opponent
            State.PlayerState.ResetStatAdditions();
            State.OpponentState.ResetStatAdditions();

            State.PlayerState.Delts = GameManager.Inst.deltPosse;

            // Select current battling Delts, update UI
            DeltemonClass startingDelt = State.PlayerState.Delts.Find(delt => delt.curStatus != statusType.DA);

            State.RegisterAction(true, new SwitchDeltAction(State, startingDelt));
            State.PlayerState.ChosenAction.ExecuteAction();
        }
Beispiel #24
0
        public string Create()
        {
            Guid   gameQueueId = Guid.NewGuid();
            string userId      = this.CurrentUserId;

            if (string.IsNullOrEmpty(userId))
            {
                throw new ServiceException("User does not exist. User Id: " + userId);
            }

            UserProfile profile = this.userRepository.GetUser(CurrentUserId);

            if (profile == null)
            {
                throw new ServiceException("User does not exist. User Id: " + userId);
            }

            GameUser user = new GameUser()
            {
                UserId   = profile.Id,
                UserName = profile.DisplayName,
                Weapons  = new List <Guid>()
            };

            GameQueue gameQueue = new GameQueue()
            {
                Id           = gameQueueId,
                CreationTime = DateTime.UtcNow,
                Status       = QueueStatus.Waiting,
                Users        = new List <GameUser>()
                {
                    user
                }
            };

            this.gameRepository.AddOrUpdateGameQueue(gameQueue);

            return(gameQueueId.ToString());
        }
        public void JoinGame()
        {
            string userID    = "jhonny";
            string newUserID = "joe";

            var userRepository = this.CreateUserRepository();
            var gameRepository = this.CreateGameRepository();

            this.CreateUser(userRepository, userID);
            this.CreateUser(userRepository, newUserID);

            GameService gameService = this.CreateGameService(gameRepository, userRepository, userID);

            var response = gameService.Create();
            var id       = response.Content.ReadAsStringAsync().Result;
            var gameId   = Guid.Parse(id);

            GameService newGameService = this.CreateGameService(gameRepository, userRepository, newUserID);

            var response2 = newGameService.Join(gameId);

            Assert.IsTrue(response2.IsSuccessStatusCode);

            GameQueue gameQueue = this.gameQueueContainer.Get(gameId.ToString());

            Assert.IsNotNull(gameQueue);
            Assert.AreEqual(2, gameQueue.Users.Count);
            Assert.AreEqual(userID, gameQueue.Users[0].UserId);
            Assert.AreEqual(newUserID, gameQueue.Users[1].UserId);

            var friends1 = userRepository.GetFriends(userID);
            var friends2 = userRepository.GetFriends(newUserID);

            Assert.IsTrue(friends1.Any(f => f == newUserID));
            Assert.IsTrue(friends2.Any(f => f == userID));
        }
Beispiel #26
0
 public static double TimeElapsed(this GameQueue gameQueue)
 {
     return((TimeProvider.Current.CurrentDateTime - gameQueue.CreationTime).TotalSeconds);
 }
Beispiel #27
0
        public void TestJoningAndLeavingGameQueues()
        {
            FixedTimeProvider timeProvider = new FixedTimeProvider();

            TimeProvider.Current = timeProvider;
            DateTime startingDateTime = DateTime.Parse("01/01/2001 00:00:00");

            timeProvider.CurrentDateTime = startingDateTime;

            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;

            IGameRepository gameRepository = new GameRepository(null, null, null, null, null, null);

            UserProfile firstUser = new UserProfile()
            {
                Id = Guid.NewGuid().ToString(), DisplayName = "John"
            };
            UserProfile secondUser = new UserProfile()
            {
                Id = Guid.NewGuid().ToString(), DisplayName = "Peter"
            };

            var users          = new AzureBlobContainer <UserProfile>(CloudStorageAccount.DevelopmentStorageAccount);
            var sessions       = new AzureBlobContainer <UserSession>(CloudStorageAccount.DevelopmentStorageAccount);
            var friends        = new AzureBlobContainer <Friends>(CloudStorageAccount.DevelopmentStorageAccount);
            var userRepository = new UserRepository(users, sessions, friends);

            userRepository.AddOrUpdateUser(firstUser);
            userRepository.AddOrUpdateUser(secondUser);

            gameRepository.AddUserToSkirmishGameQueue(firstUser);

            GameQueue gameQueue = null;

            //// gameQueue = MagicallyGetGameQueues();
            Assert.AreEqual(gameQueue, new Game {
                CreationTime = startingDateTime, Id = gameQueue.Id, Users = new List <GameUser> {
                    new GameUser {
                        UserId = firstUser.Id
                    }
                }
            });
            Assert.AreEqual(gameQueue.TimeElapsed(), 60);

            timeProvider.CurrentDateTime = startingDateTime.AddSeconds(10);
            Assert.AreEqual(gameQueue.TimeElapsed(), 50);

            gameRepository.AddUserToSkirmishGameQueue(secondUser);
            //// gameQueue = MagicallyGetGameQueues();
            Assert.AreEqual(gameQueue, new Game {
                CreationTime = startingDateTime, Id = gameQueue.Id, Users = new List <GameUser> {
                    new GameUser {
                        UserId = firstUser.Id
                    }, new GameUser {
                        UserId = secondUser.Id
                    }
                }
            });
            Assert.AreEqual(gameQueue.TimeElapsed(), 50);

            timeProvider.CurrentDateTime = startingDateTime.AddSeconds(20);
            Assert.AreEqual(gameQueue, new Game {
                CreationTime = startingDateTime, Id = gameQueue.Id, Users = new List <GameUser> {
                    new GameUser {
                        UserId = firstUser.Id
                    }, new GameUser {
                        UserId = secondUser.Id
                    }
                }
            });

            Assert.AreEqual(gameQueue.TimeElapsed(), 40);

            // gameRepository.RemoveUserFromGameQueue(firstUser, gameQueue, "Bored");
            // gameQueue = MagicallyGetGameQueues();
            Assert.AreEqual(gameQueue, new Game {
                CreationTime = startingDateTime, Id = gameQueue.Id, Users = new List <GameUser> {
                    new GameUser {
                        UserId = secondUser.Id
                    }
                }
            });
            Assert.AreEqual(gameQueue.TimeElapsed(), 40);

            timeProvider.CurrentDateTime = startingDateTime.AddSeconds(30);
            Assert.AreEqual(gameQueue.TimeElapsed(), 30);

            // gameRepository.RemoveUserFromGameQueue(secondUser, gameQueue, "Also Bored");
            // gameQueue = MagicallyGetGameQueues();
            Assert.AreEqual(gameQueue, new Game {
                CreationTime = startingDateTime, Id = gameQueue.Id, Users = new List <GameUser>()
            });
        }
    private void QueueList_SelectionChanged(object sender, SelectionChangedEventArgs e) {
      var src = sender as ListBox;
      if (src.SelectedIndex < 0) return;
      var queue = (GameQueue) ((ListBox) sender).SelectedItem;

      if (queue.Action1 != null) {
        QueueButton1.Visibility = Visibility.Visible;
        QueueButton1.Content = queue.Action1;
      } else QueueButton1.Visibility = Visibility.Collapsed;

      if (queue.Action2 != null) {
        QueueButton2.Visibility = Visibility.Visible;
        QueueButton2.Content = queue.Action2;
      } else QueueButton2.Visibility = Visibility.Collapsed;
      selected = queue;
    }
Beispiel #29
0
        static void Main(string[] args)
        {
            GameStack gameStack = new GameStack();
            GameQueue gameQueue = new GameQueue();

            #region Part 1
            //add spells to the stack and then pop them
            #region stack section

            //add the spells to the stack
            #region spells
            Console.WriteLine("Adding spells to the stack:");

            gameStack.Push("Lightning Bolt");
            Console.WriteLine(gameStack.Peek());

            gameStack.Push("Snapcaster Mage");
            Console.WriteLine(gameStack.Peek());

            gameStack.Push("CounterSpell");
            Console.WriteLine(gameStack.Peek());

            gameStack.Push("TwinBolt");
            Console.WriteLine(gameStack.Peek());

            gameStack.Push("Daze");
            Console.WriteLine(gameStack.Peek());
            #endregion

            Console.WriteLine();
            Console.WriteLine("Spells resolving in reverse order:");
            //while loop to pop each item in the list while it has items in it
            while (gameStack.IsEmpty == false)
            {
                Console.WriteLine(gameStack.Pop());
            }
            #endregion

            //spacing lines
            Console.WriteLine();
            Console.WriteLine();

            //add people to a queue and then dequeue them
            #region queue section

            //adding people to a queue
            #region people
            Console.WriteLine("People being queued a server");
            gameQueue.Enqueue("Nick");
            gameQueue.Enqueue("Briana");
            gameQueue.Enqueue("Drake");
            gameQueue.Enqueue("Nico");
            gameQueue.Enqueue("Some other nerd");

            //displays each of the people in the queue
            for (int i = 0; i < gameQueue.Count - 1; i++)
            {
                Console.WriteLine(gameQueue.Queue[i]);
            }
            #endregion

            //while the queue has people in it, dequeue until the list is empty
            Console.WriteLine();
            Console.WriteLine("Adding the queued people to the server:");
            while (gameQueue.IsEmpty == false)
            {
                Console.WriteLine(gameQueue.Dequeue() + " Has joined the server: " + (gameQueue.Count - 1) + " player(s) left in the queue");
            }
            #endregion
            #endregion

            //spacing for part 2
            Console.WriteLine("\n\n\n\n");

            #region Part 2
            //part 2 stacks

            //store the current page as a string, defaults to Google on startup
            while (true)
            {
                Console.WriteLine();
                Console.WriteLine("Here are your possible controls:");
                Console.WriteLine("1. visit a new webpage");
                Console.WriteLine("2. move forward to the next page");
                Console.WriteLine("3. navigate back to the previous page");
                Console.WriteLine("4. print the current page, as well as the backward stack and forward stack");
                Console.WriteLine("5. quit the loop");

                string answer    = Console.ReadLine();
                int    answerInt = 0;
                int.TryParse(answer, out answerInt);

                switch (answerInt)
                {
                case 1:
                    currentPage = VisitPage(currentPage);
                    break;

                case 2:
                    currentPage = NextPage(currentPage);
                    break;

                case 3:
                    currentPage = PreviousPage(currentPage);
                    break;

                case 4:
                    PrintEverything(currentPage);
                    break;

                case 5:
                    return;

                default:
                    Console.WriteLine("Invalid Entry, please try again");
                    Console.WriteLine("--------------------");
                    Console.WriteLine();
                    break;
                }
            }

            #endregion
        }
Beispiel #30
0
 // REFACTOR_TODO: This should be overloaded with text, action, and IEnumerators
 public static void AddToBattleQueue(string message = null, Action action = null, IEnumerator enumerator = null)
 {
     GameQueue.BattleAdd(message, action, enumerator);
 }
Beispiel #31
0
 private int BotsCount(GameQueue gameQueue)
 {
     return(gameQueue.Users.Where(player => player.UserId.StartsWith(ConfigurationConstants.BotUserIdPrefix)).Count());
 }