public void Analize_MustGiveAdvicesToWin()
        {
            State = new GameStateModel("hell");
            var analysis = Utilities.PostData <GameAnalysisModel, GameStateModel>(ResourcePath, State);

            Assert.IsTrue(analysis.Help.Contains("win going for"));
        }
Example #2
0
 public void DisplayStartMenu()
 {
     Console.WriteLine("Start menu: ");
     Console.WriteLine("Input start game parameters: ");
     gameStateModel   = new GameStateModel();
     playerStateModel = GetPlayerStateParameters();
 }
        public void Analize_ResponseMustNotBeNull()
        {
            State = new GameStateModel("hello");
            var analysis = Utilities.PostData <GameAnalysisModel, GameStateModel>(ResourcePath, State);

            Assert.IsNotNull(analysis);
        }
        public SystemClockBehavior(
            GameStateModel gameState)
        {
            _gameState = gameState;

            _utcNow = new ObservableValue <DateTimeOffset>(DateTimeOffset.Now);
        }
Example #5
0
        private GameStateModel UpdateDeploymentAndStartAllowed(GameStateModel game)
        {
            game.IsDeploymentAllowed = IsDeploymentAllowed(game.Players);
            game.IsStartAllowed      = IsStartAllowed(game.Players);

            return(game);
        }
        public void Inject(SignalBus signalBus, GameStateModel gameStateModel)
        {
            this.gameStateModel = gameStateModel;
            this.signalBus      = signalBus;

            InitButtons();
        }
        public PauseController(PauseView view, GameStateModel gameStateModel, SettingsModel settingsModel, UserInputModel userInputModel, SceneTransitionService sceneTransitionService)
            : base(view)
        {
            _view = view;

            _gameStateModel         = gameStateModel;
            _settingsModel          = settingsModel;
            _userInputModel         = userInputModel;
            _sceneTransitionService = sceneTransitionService;

            _gameStateModel.IsPaused
            .Subscribe(OnPauseChanged)
            .AddTo(Disposer);

            _userInputModel.OnPause
            .Subscribe(_ => OnUserInputPause())
            .AddTo(Disposer);

            _view.IsMusicMuted   = _settingsModel.IsMusicMuted;
            _view.IsEffectsMuted = _settingsModel.IsEffectsMuted;

            _view.OnCloseCompleted
            .Subscribe(_ => _gameStateModel.IsPaused.Value = false)
            .AddTo(Disposer);

            _view.OnRetryClicked
            .Subscribe(_ => OnRetryClicked())
            .AddTo(Disposer);

            _view.Initialize();
        }
        public static GameStateModel GetGameState(int gameId, int userId)
        {
            var context = new BullsAndCowsEntities();

            using (context)
            {
                var user = GetUser(userId, context);
                var game = GetGame(gameId, context);

                if (game.GameStatus != context.GameStatuses.First((st) => st.Status == GameStatusInProgress))
                {
                    throw new ServerErrorException("Game is not in progress", "INV_OP_GAME_STAT");
                }

                if (game.RedUser != user && game.BlueUser != user)
                {
                    throw new ServerErrorException("User not in game", "ERR_NOT_IN_GAME");
                }

                var gameStateModel = new GameStateModel()
                {
                    Id                = (int)game.Id,
                    Title             = game.Title,
                    RedPlayer         = game.RedUser.Nickname,
                    BluePlayer        = game.BlueUser.Nickname,
                    PlayerInTurn      = (game.RedUser.Id == game.UserInTurn) ? "red" : "blue",
                    RedPlayerGuesses  = ParseGuessesToModels(game.Guesses.Where(g => g.User == game.RedUser)),
                    BluePlayerGuesses = ParseGuessesToModels(game.Guesses.Where(g => g.User == game.BlueUser))
                };
                return(gameStateModel);
            }
        }
Example #9
0
    protected void ButtonStartGame_Click(object sender, EventArgs e)
    {
        GameStateModel newGame = this.GameEngine.NewGame(User.Identity.Name);

        SaveGameState(newGame);
        RefreshView(newGame);
    }
Example #10
0
    private void Reset()
    {
        if (cubeController != null)
        {
            cubeController.Reset();
            cubeController = null;
        }
        if (elementsController != null)
        {
            elementsController.Reset();
            elementsController = null;
        }
        if (playerModel != null)
        {
            playerModel.Reset();
            playerModel = null;
        }
        if (gameStateModel != null)
        {
            gameStateModel.Reset();
            gameStateModel = null;
        }
        if (gameStateModel != null)
        {
            gameStateModel.Reset();
            gameStateModel = null;
        }

        RemoveEventListeners();
    }
Example #11
0
        public void Analize_MustGiveAdvicesToWin()
        {
            State = new GameStateModel("hell");
            var analysis = Controller.Post(State);

            Assert.IsTrue(analysis.Help.Contains("win going for"));
        }
Example #12
0
        public GameState(
            GameRoundEntity owner,
            GameStateModel model,
            UserInputModel userInputModel,
            JesterEntity jesterEntity,
            AudioService audioService,
            ParticleService particleService)
            : base(owner)
        {
            _model           = model;
            _userInputModel  = userInputModel;
            _jesterEntity    = jesterEntity;
            _audioService    = audioService;
            _particleService = particleService;

            _audioService.ResetPausedSlots();
            _particleService.ResetPausedSlots();

            _userInputModel.OnPause
            .Subscribe(_ => model.IsPaused.Value = !model.IsPaused.Value)
            .AddTo(owner);

            _jesterEntity.OnKicked
            .Subscribe(_ => model.OnRoundStart.Execute())
            .AddTo(owner);

            _jesterEntity.OnLanded
            .Subscribe(_ => model.OnRoundEnd.Execute())
            .AddTo(owner);

            _model.IsPaused
            .Subscribe(OnPauseChanged)
            .AddTo(owner);
        }
Example #13
0
 public void Inject(EntityManager entityManager, SignalBus signalBus, DiContainer diContainer, GameStateModel gameStateModel, BoardModel boardModel)
 {
     this.gameStateModel = gameStateModel;
     this.entityManager  = entityManager;
     this.signalBus      = signalBus;
     this.boardModel     = boardModel;
 }
Example #14
0
    /// <summary>
    /// Initialize new game state for authenticated user.
    /// </summary>
    /// <param name="userDto">authenticated user</param>
    /// <param name="characterDto">associated character</param>
    private void InitializeNewGame(UserDTO userDto, CharacterDTO characterDto)
    {
        if (userDto == null)
        {
            throw new ArgumentNullException("userDto");
        }

        if (characterDto == null)
        {
            throw new ArgumentNullException("characterDto");
        }

        // Create game safe point
        var created   = DateTime.UtcNow;
        var gameState = new GameStateModel(
            Guid.NewGuid().ToString(),
            userDto.Login,
            GeneralName.InitialGameSceneId,
            string.Format("Autosave for {0} at {1}", userDto.Login, created.ToLocalTime()),
            created);
        var gameStateDto = gameState.ConvertToDTO <GameStateDTO>();

        // Create main character safe point state
        var gameStateCharacterDto = new CharacterStateDTO(gameStateDto.GameStateId, characterDto);

        // todo: save all objects to Database in transaction
        _connection.Insert(gameStateDto);
        _connection.Insert(gameStateCharacterDto);
    }
Example #15
0
    public override void OnEvent(EventData eventData)
    {
        SubCode subCode = ParameterTool.GetSubcode(eventData.Parameters);

        switch (subCode)
        {
        case SubCode.GetTeam:
            List <Role> roles = ParameterTool.GetParameter <List <Role> >(eventData.Parameters,
                                                                          ParameterCode.RoleList);
            int masterRoleID = ParameterTool.GetParameter <int>(eventData.Parameters, ParameterCode.MasterRoleID,
                                                                false);
            if (OnGetTeam != null)
            {
                OnGetTeam(roles, masterRoleID);
            }
            break;

        case SubCode.SyncPositionAndRotation:
            int     roleID = ParameterTool.GetParameter <int>(eventData.Parameters, ParameterCode.RoleID, false);
            Vector3 pos    =
                ParameterTool.GetParameter <Vector3Obj>(eventData.Parameters, ParameterCode.Position).ToVector3();
            Vector3 eulerAngles = ParameterTool.GetParameter <Vector3Obj>(eventData.Parameters,
                                                                          ParameterCode.EulerAngles).ToVector3();
            if (OnSyncPositionAndRotation != null)
            {
                OnSyncPositionAndRotation(roleID, pos, eulerAngles);
            }
            break;

        case SubCode.SyncMoveAnimation:
            int roleID2 = ParameterTool.GetParameter <int>(eventData.Parameters, ParameterCode.RoleID, false);
            PlayerMoveAnimationModel model =
                ParameterTool.GetParameter <PlayerMoveAnimationModel>(eventData.Parameters,
                                                                      ParameterCode.PlayerMoveAnimationModel);
            if (OnSyncMoveAnimation != null)
            {
                OnSyncMoveAnimation(roleID2, model);
            }
            break;

        case SubCode.SyncAnimation:
            int roleID3 = ParameterTool.GetParameter <int>(eventData.Parameters, ParameterCode.RoleID, false);
            PlayerAnimationModel model2 = ParameterTool.GetParameter <PlayerAnimationModel>(eventData.Parameters,
                                                                                            ParameterCode.PlayerAnimationModel);
            if (OnSyncPlayerAnimation != null)
            {
                OnSyncPlayerAnimation(roleID3, model2);
            }
            break;

        case SubCode.SendGameState:
            GameStateModel model3 = ParameterTool.GetParameter <GameStateModel>(eventData.Parameters,
                                                                                ParameterCode.GameStateModel);
            if (OnGameStateChange != null)
            {
                OnGameStateChange(model3);
            }
            break;
        }
    }
Example #16
0
    private void AnswerQuestion(bool answer)
    {
        GameStateModel newGameState = this.GameEngine.AnswerFirstQuestion(GetCurrentGame(), answer);

        SaveGameState(newGameState);
        RefreshView(newGameState);
    }
Example #17
0
        private GameStateModel GetGameStateBySnapshot(GameAggregate gameSnapshot)
        {
            GameStateModel result = new GameStateModel
            {
                Id                     = gameSnapshot.Id,
                Status                 = gameSnapshot.Status,
                UserId                 = gameSnapshot.UserId,
                UserHeroId             = gameSnapshot.UserHeroId,
                OpponentId             = gameSnapshot.OpponentId,
                OpponentHeroId         = gameSnapshot.OpponentHeroId,
                SelfPlaying            = gameSnapshot.SelfPlaying,
                Speed                  = gameSnapshot.Speed,
                Difficulty             = gameSnapshot.Difficulty,
                UserCoins              = gameSnapshot.UserCoins,
                OpponentCoins          = gameSnapshot.OpponentCoins,
                Castles                = new List <CastleStateModel>(),
                UserProducedTroopTypes = gameSnapshot.UserProducedTroopTypes,
                UserSoldiers           = Mapper.Map <List <SoldierModel> >(gameSnapshot.UserSoldiers),
                OpponentSoldiers       = Mapper.Map <List <SoldierModel> >(gameSnapshot.OpponentSoldiers)
            };

            foreach (var castle in gameSnapshot.Castles)
            {
                CastleStateModel castleModel = Mapper.Map <CastleStateModel>(castle);
                result.Castles.Add(castleModel);
            }
            return(result);
        }
Example #18
0
    GameStateModel LoadGame(string name)
    {
        GameStateModel game = new GameStateModel();

        game = (GameStateModel)JsonConvert.DeserializeObject(System.IO.File.ReadAllText(name + ".txt"), typeof(GameStateModel));
        return(game);
    }
        private async Task RemoveGameIfEmpty_OnUserNameValues_ReturnsListItems(bool isGameEmpty, int gameNotEmpty, int gameEmpty)
        {
            string         user0Name = "player_0_userName";
            string         user1Name = "player_1_userName";
            GameStateModel game      = new GameStateModel()
            {
                Players = new Player[] { new Player()
                                         {
                                             UserName = user0Name
                                         }, new Player()
                                         {
                                             UserName = user1Name
                                         } }, GameId = 666
            };
            Mock <IHubCallerClients> clientsMock = new Mock <IHubCallerClients>();

            string[] players = new string[] { game.Players[0].UserName, game.Players[1].UserName };
            _nameValidatorMock.Setup(mock => mock.IsGameEmpty(players)).Returns(isGameEmpty);

            await _service.RemoveGameIfEmpty(game, clientsMock.Object);

            _cacheMock.Verify(mock => mock.RemoveGameFromMemory(game.GameId), Times.Exactly(gameEmpty));
            _cacheMock.Verify(mock => mock.UpdateGame(game), Times.Exactly(gameNotEmpty));
            _messengerMock.Verify(mock => mock.SendGameStateToUsersInGame(game, clientsMock.Object), Times.Exactly(gameNotEmpty));
        }
    public TModel CreateModel <TModel>()
        where TModel : GameStateModel, new()
    {
        GameStateModel model = ScriptableObject.CreateInstance <TModel>();

        return(model as TModel);
    }
        public IHttpActionResult AddGameState(GameStateModel model)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                try
                {
                    var gameStates = db.GameStates.Where(g => g.Username == model.Username).OrderBy(g => g.DateTime).ToList();

                    if (gameStates.Count < 3)
                    {
                        db.GameStates.Add(model);
                        db.SaveChanges();
                        return(Ok());
                    }
                    else
                    {
                        var oldGameState    = gameStates[0];
                        var oldestGameState = db.GameStates.Where(g => g.ID == oldGameState.ID).First();
                        db.GameStates.Remove(oldestGameState);
                        db.GameStates.Add(model);
                        db.SaveChanges();
                        return(Ok());
                    }
                }
                catch (Exception e)
                {
                    return(BadRequest(e.ToString()));
                }
            }
        }
Example #22
0
#pragma warning disable 1998
        public async Task <GameStateModel> GetState(Guid id, int streamVersion)
#pragma warning restore 1998
        {
            GameStateModel result = new GameStateModel
            {
                Id       = id,
                HasError = false
            };
            ISnapshot     latestSnapshot = _store.Advanced.GetSnapshot(id, streamVersion);
            GameAggregate gameSnapshot   = latestSnapshot?.Payload as GameAggregate;

            if (gameSnapshot == null)
            {
                return(null);
            }
            result.Status         = gameSnapshot.Status;
            result.UserId         = gameSnapshot.UserId;
            result.UserHeroId     = gameSnapshot.UserHeroId;
            result.OpponentId     = gameSnapshot.OpponentId;
            result.OpponentHeroId = gameSnapshot.OpponentHeroId;
            result.StreamRevision = latestSnapshot.StreamRevision;
            result.SelfPlaying    = gameSnapshot.SelfPlaying;
            result.Castles        = new List <CastleStateModel>();
            foreach (var castle in gameSnapshot.Castles)
            {
                CastleStateModel castleModel = Mapper.Map <CastleStateModel>(castle);
                //var events = _domain.GetNotExecuteEvents<CreateSoldierEvent>(id);
                //var latestEvent = events.FirstOrDefault(e => e.CastleId == castle.Id);
                //if (latestEvent != null)
                //    castleModel.ProduceExecuteAt = latestEvent.ExecuteAt;
                result.Castles.Add(castleModel);
            }
            return(result);
        }
Example #23
0
        //                                                                                     GAME LOBBY
        public ActionResult GameLobby(FormCollection collection)
        {
            string id = Session.SessionID;

            ViewBag.Id = id;
            GameLobby thisLobby = FindGameLobby(FindUser(id).InGameId.ToString());

            // start game button pressed
            if (collection["formType"] == "newGame")
            {
                GameInstruction instruction = CreateGameInstruction(thisLobby);
                GameStateModel  model       = UpdateGame(instruction);
                //flag game as started
                thisLobby.Started = true;
                //go to game page
                return(View("Game", model));
            }
            //auto redirect when game starts
            if (collection["poke"] == "refresh")
            {
                if (!GameStarted(collection["gameId"]))
                {
                    return(View(thisLobby));
                    //return new HttpStatusCodeResult(304, "Not Modified"); does not work with explorer
                }
                else
                {
                    return(View("Game", SettlersOfCatan.FindGame(thisLobby.Id)));
                }
            }
            // joined lobby successfully
            return(View(thisLobby));
        }
Example #24
0
        public ActionResult Game(FormCollection collection)
        {
            ViewBag.Id = Session.SessionID;
            Guid ThisGame = FindUser(Session.SessionID).InGameId;

            if (collection["poke"] == "refresh")
            {
                if (FindUser(collection["PlayerId"]).NewGameContent)
                {
                    return(View(SettlersOfCatan.FindGame(ThisGame)));
                }
                return(new HttpStatusCodeResult(304, "Not Modified"));
            }

            GameInstruction instruction;

            if (collection["formType"] == "normal")
            {
                instruction = NormalGameInstruction(collection);
            }
            else
            {
                throw new Exception("something went wrong");
            }

            GameStateModel model = UpdateGame(instruction);

            SetGameChangeFlagsForAllParticipants(ThisGame);
            return(View(model));
        }
Example #25
0
        public HudController(
            HudView view,
            GameStateModel gameStateModel,
            FlightStatsModel flightStatsModel,
            ProfileModel profileModel,
            UserInputModel userInputModel,
            CameraConfig cameraConfig)
            : base(view)
        {
            _view = view;
            _view.Initialize();

            _gameStateModel   = gameStateModel;
            _flightStatsModel = flightStatsModel;
            _profileModel     = profileModel;
            _userInputModel   = userInputModel;
            _cameraConfig     = cameraConfig;

            _view.OnPauseButtonClicked
            .Subscribe(_ => _userInputModel.OnPause.Execute())
            .AddTo(Disposer);

            SetupGameStateModel();
            SetupFlightStatsModel();
            SetupProfileModel();
        }
Example #26
0
        //                                                                                     SANDBOX
        public ActionResult Sandbox()
        {
            ViewBag.Id         = Session.SessionID;
            ViewBag.Settlement = @"\\Content\\Images\\doodad\\Settlement.png"; //not in use
            ViewBag.City       = @"\\Content\\Images\\doodad\\City.png";       //not in use
            //set up fake game for testing
            //   ----- FAKE DATA -----
            GameInstruction instruction = new GameInstruction();

            instruction.Type          = GameInstruction.InstructionType.newGame;
            instruction.GameId        = Guid.NewGuid();
            instruction.BoardTemplate = BoardState.BoardOptions.tutorial;

            //populate game with players
            instruction.NewGamePlayers   = new List <string>();
            instruction.NewGamePlayersId = new List <string>();

            instruction.NewGamePlayers.Add("Frodo");
            instruction.NewGamePlayersId.Add(Session.SessionID);

            instruction.NewGamePlayers.Add("Sam");
            instruction.NewGamePlayersId.Add(Session.SessionID);

            instruction.NewGamePlayers.Add("Gandalf");
            instruction.NewGamePlayersId.Add(Session.SessionID);

            instruction.NewGamePlayers.Add("Gimli");
            instruction.NewGamePlayersId.Add(Session.SessionID);
            //   ----- FAKE DATA END -----

            GameStateModel model = UpdateGame(instruction);

            return(View("Game", model));
        }
    public void SendGameState(GameStateModel model)
    {
        Dictionary <byte, object> parameters = new Dictionary <byte, object>();

        ParameterTool.AddParameter(parameters, ParameterCode.GameState, model);
        PhotonEngine.Instance.SendRequest(OpCode, SubCode.SyncGameState, parameters);
    }
 public GameBuildingBehavior(
     IGameplayService gameplayService,
     GameStateModel gameState)
 {
     _gameplayService = gameplayService;
     _gameState       = gameState;
 }
Example #29
0
    private void Load()
    {
        byte[] save = File.ReadAllBytes(GameStateModel.GetSaveLocation(selectedPath));
        byte[] meta = File.ReadAllBytes(GameStateModel.GetSaveMetaLocation(selectedPath));

        inst_boot.RebootGameWithData(GameStateModel.Deserialize <GameStateModel>(save),
                                     GameStateModel.Deserialize <GameStateModel.SaveMeta>(meta));
    }
Example #30
0
    private void InitGameField(GameStateModel gameState)
    {
        var gameStateBounds = Rect.MinMaxRect(gameState.MoveBounds.Left, gameState.MoveBounds.Top, gameState.MoveBounds.Right, gameState.MoveBounds.Bottom);

        ExpandField(gameStateBounds);

        lastGameState = gameState;
    }
Example #31
0
 //游戏胜利的状态
 public void SendGameState(GameStateModel model)
 {
     Dictionary<byte, object> parameters = new Dictionary<byte, object>();
     ParameterTool.AddParameter(parameters, ParameterCode.GameStateModel, model);
     PhotonEngine.Instance.SendRequest(OpCode, SubCode.SendGameState, parameters);
 }
Example #32
0
 private void OnGameStateChange(GameStateModel model)
 {
     //胜利
     if (model.isSuccess)
     {
         OnVictory();
     }
     else
     {
         //失败
         GameOverPanel.Instance.Show("游戏失败");
         
     }
 }