Esempio n. 1
0
        protected override void OnRemove(GUnit unit)
        {
            base.OnRemove(unit);

            _stateData.currentState.Dispose();
            _stateData = null;
        }
Esempio n. 2
0
        public GameStateData Get()
        {
            var questions   = new Dictionary <string, TriviaInfo>();
            var emo         = GetQuestions(GroupName.Emo);
            var hipster     = GetQuestions("hipsters");
            var jock        = GetQuestions("jocks");
            var nerd        = GetQuestions("nerds");
            var popularGirl = GetQuestions("popular-girls");

            questions.Add(GroupName.Emo, new TriviaInfo {
                Questions = emo
            });
            questions.Add(GroupName.Hipster, new TriviaInfo {
                Questions = hipster
            });
            questions.Add(GroupName.Jock, new TriviaInfo {
                Questions = jock
            });
            questions.Add(GroupName.Nerd, new TriviaInfo {
                Questions = nerd
            });
            questions.Add(GroupName.PopularGirl, new TriviaInfo {
                Questions = popularGirl
            });
            var model = new GameStateData
            {
                UserId    = 0,
                questions = questions
            };

            return(model);
        }
    public static void SaveGameState()
    {
        GameStateData data = new GameStateData();

        data.gameCurrentLevelLastCheckPoint = GameController.gameCurrentLevelLastCheckPoint;
        data.gameLastLevel    = GameController.gameLastLevel;
        data.gameCurrentLevel = GameController.gameCurrentLevel;

        string filePath = GetGameStatePath();

        Stream stream = null;

        try
        {
            stream = File.Open(filePath, FileMode.Create);

            BinaryFormatter bformatter = new BinaryFormatter();
            bformatter.Binder = new VersionDeserializationBinder();
            bformatter.Serialize(stream, data);
        }
        catch
        {
            //<Test>
            Debug.LogError("Saving game state error!!!");
            //</Test>
        }
        finally
        {
            if (stream != null)
            {
                stream.Close();
            }
        }
    }
Esempio n. 4
0
 public override bool isMessageStillValid(String eventSubType, GameStateData currentGameState, Dictionary <String, Object> validationData)
 {
     if (base.isMessageStillValid(eventSubType, currentGameState, validationData))
     {
         if (eventSubType == folderPossibleTrackLimitsViolation)
         {
             return(true);
         }
         // When a new penalty is given we queue a 'three laps left to serve' delayed message.
         // If, the moment message is about to play, the player has started a new lap, this message is no longer valid so shouldn't be played
         if (eventSubType == folderThreeLapsToServe)
         {
             Console.WriteLine("Checking penalty validity, pen lap = " + penaltyLap + ", completed =" + lapsCompleted);
             return(hasOutstandingPenalty && lapsCompleted == penaltyLap && currentGameState.SessionData.SessionPhase != SessionPhase.Finished);
         }
         else if (eventSubType == folderCutTrackInRace)
         {
             return(!hasOutstandingPenalty && currentGameState.SessionData.SessionPhase != SessionPhase.Finished && !currentGameState.PitData.InPitlane);
         }
         else if (eventSubType == folderCutTrackPracticeOrQual || eventSubType == folderCutTrackPracticeOrQualNextLapInvalid || eventSubType == folderLapDeleted)
         {
             return(currentGameState.SessionData.SessionPhase != SessionPhase.Finished && !currentGameState.PitData.InPitlane);
         }
         else
         {
             return(hasOutstandingPenalty && currentGameState.SessionData.SessionPhase != SessionPhase.Finished);
         }
     }
     else
     {
         return(false);
     }
 }
Esempio n. 5
0
        // returns true if the dialogue should block entry
        private bool GetDialogueForState(GameStateData state, out SerializedDialogue res)
        {
            Func <LocationDialogueForState, bool> filter =
                (LocationDialogueForState dialogue) => dialogue.gameStateData == state;

            res = entryDialogue.FirstOrDefault(filter)?.locationDialogue;
            if (res != null)
            {
                return(false);
            }

            res = uniqueStateBlockingDialogue.FirstOrDefault(filter)?.locationDialogue;
            if (res != null)
            {
                return(true);
            }

            if (defaultBlockingDialogue.Count > 0)
            {
                int index = ((defaultDialogueIdx + 1) < defaultBlockingDialogue.Count)
          ? defaultDialogueIdx++ : (defaultBlockingDialogue.Count - 1);
                res = defaultBlockingDialogue[index];
                return(true);
            }

            return(false);
        }
        public bool ForwardServerDataToGame(GameStateData gameStateData)
        {
            //build it
            return(GameSectorLayerServices
                   .Values
                   .ToList()
                   .Any(sector =>
            {
                var currentPlayer = sector
                                    .SharedContext
                                    .DataLayer
                                    .Players
                                    .FirstOrDefault(player => player.LoginToken == gameStateData.LoginToken);

                if (currentPlayer == null)
                {
                    return false;
                }

                return sector
                .SharedContext
                .IODataLayer
                .ForwardServerDataToGame(gameStateData);
            }));
        }
Esempio n. 7
0
        /// <summary>
        /// Sort objects if already loaded
        /// </summary>
        /// <param name="objects"></param>
        /// <returns></returns>
        public List <PrefabObject> GetRequiredObjects(List <PrefabObject> objects)
        {
            List <PrefabObject> result        = new List <PrefabObject>(objects);
            List <PrefabObject> alreadyLoaded = GameStateData.GetPrefabsData();
            List <PrefabObject> resultRemove  = new List <PrefabObject>();

            foreach (PrefabObject o in result)
            {
                PrefabObject found = alreadyLoaded.Find(prefabObject => prefabObject.Id == o.Id);

                if (found != null)
                {
                    var loaded = result.Find(prefabObject => prefabObject.Id == o.Id);
                    resultRemove.Add(loaded);
                    Debug.Log(o.Config.i18n.en + " is already loaded");
                }

                else
                {
                    Debug.Log(o.Config.i18n.en + " is required");
                }

                Debug.Log(o.Config.i18n.en + "was added to WorldStructure.SceneObjects");
            }

            foreach (PrefabObject o in resultRemove)
            {
                result.Remove(o);
            }

            return(result);
        }
Esempio n. 8
0
        public override void OnUpdate()
        {
            if (GameStateData.GetWrapperCollection() == null)
            {
                return;
            }

            var group = Contexts.sharedInstance.game.GetGroup(GameMatcher.AllOf(GameMatcher.Wrapper, GameMatcher.IdObject));

            foreach (var gameEntity in group.GetEntities())
            {
                if (gameEntity.idObject.Value != StateMachine.SpawningObjectId)
                {
                    continue;
                }

                StateMachine.ButtonGameObject = gameEntity.gameObject.Value;
                StateMachine.ButtonInstanceId = gameEntity.id.Value;
                StateMachine.ChangeState(new ButtonMoveState(StateMachine));

                return;
            }

            if (ProjectData.SelectedObjectIdToSpawn == 0)
            {
                StateMachine.SpawningObjectId = 0;
                StateMachine.ChangeState(new MenuOpeningState(StateMachine, MenuOpeningState.TargetObject.Button));

                return;
            }
        }
Esempio n. 9
0
 private void Awake()
 {
     playerData       = GameFacade.GetInstance().playerData;
     levelData        = GameFacade.GetInstance().levelData;
     gameUIController = GameFacade.GetInstance().GameUIController;
     gameStateData    = GameFacade.GetInstance().gameStateData;
 }
Esempio n. 10
0
    public void SaveGame()
    {
        GameStateData gsd = new GameStateData();

        //put all tree data into an array of FruitTreeData
        GameObject []   trees    = GameObject.FindGameObjectsWithTag("Tree");
        FruitTreeData[] treeData = new FruitTreeData[trees.Length];
        for (int i = 0; i < treeData.Length; i++)
        {
            treeData[i] = trees[i].GetComponent <FruitTree>().Serialize();
        }
        //create a new GameStateData
        gsd.trees = treeData;
        ItemSelector item = GameObject.FindGameObjectWithTag("Inventory").GetComponent <ItemSelector>();

        //fill in da blanks
        gsd.seedCount    = item.numSeeds;
        gsd.fruitCount   = item.numFruit;
        gsd.playerEnergy = transform.GetComponent <DirectionalMovement>().energy;
        gsd.playerPos    = transform.parent.position;
        gsd.playerRot    = Camera.main.transform.rotation;
        DayCycle day = GameObject.FindGameObjectWithTag("Sun").GetComponent <DayCycle>();

        gsd.seasonCode = day.seasonCode;
        gsd.dayCode    = day.dayCode;
        //serialize GameStateData to json
        string path = Application.persistentDataPath + "/saveData.json";

        //write json string to file in persistantDataPath
        File.WriteAllText(path, JsonUtility.ToJson(gsd));
        Debug.Log("Save success");
    }
Esempio n. 11
0
    public void SetItem(GameStateData gameState, int index, string _text, Sprite _image)
    {
        GameObject textObj  = new GameObject("Text");
        GameObject imageObj = new GameObject("Image");

        textObj.transform.parent  = this.transform;
        imageObj.transform.parent = this.transform;

        image = imageObj.AddComponent <Image>();
        text  = textObj.AddComponent <TextMeshProUGUI>();

        // Set ActionItem Position
        this.GetComponent <RectTransform>().anchoredPosition = new Vector3(0, -100.0F - index * 75.0F, 0);

        // Set image properties
        image.transform.localScale = Vector3.one;
        image.GetComponent <RectTransform>().anchoredPosition = new Vector3(-229, 23, 0);
        image.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 50);
        image.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 50);
        image.sprite = _image;

        // Set text properties
        text.transform.localScale = Vector3.one;
        text.GetComponent <RectTransform>().anchoredPosition = new Vector3(62, 0, 0);
        text.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 500);
        text.GetComponent <RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 100);
        text.GetComponent <TextMeshProUGUI>().font         = gameState.actionItemFont;
        text.GetComponent <TextMeshProUGUI>().fontMaterial = gameState.actionItemMaterial;
        text.fontSize = 55;
        text.text     = _text;
    }
Esempio n. 12
0
        override protected void triggerInternal(GameStateData previousGameState, GameStateData currentGameState)
        {
            if (engineData == null)
            {
                clearState();
            }
            if (maxSafeWaterTemp == 0)
            {
                maxSafeWaterTemp = currentGameState.carClass.maxSafeWaterTemp;
            }
            if (maxSafeOilTemp == 0)
            {
                maxSafeOilTemp = currentGameState.carClass.maxSafeOilTemp;
            }
            if (currentGameState.SessionData.SessionRunningTime > 60 * currentGameState.EngineData.MinutesIntoSessionBeforeMonitoring)
            {
                engineData.addSample(currentGameState.EngineData.EngineOilTemp, currentGameState.EngineData.EngineWaterTemp,
                                     currentGameState.EngineData.EngineOilPressure);

                if (currentGameState.SessionData.SessionRunningTime > gameTimeAtLastStatusCheck + statusMonitorWindowLength)
                {
                    EngineStatus currentEngineStatus = engineData.getEngineStatusFromAverage(maxSafeWaterTemp, maxSafeOilTemp);
                    if (currentEngineStatus != lastStatusMessage)
                    {
                        switch (currentEngineStatus)
                        {
                        case EngineStatus.ALL_CLEAR:
                            lastStatusMessage = currentEngineStatus;
                            audioPlayer.playMessage(new QueuedMessage(folderAllClear, 0, this));
                            break;

                        case EngineStatus.HOT_OIL:
                            // don't play this if the last message was about hot oil *and* water - wait for 'all clear'
                            if (lastStatusMessage != EngineStatus.HOT_OIL_AND_WATER)
                            {
                                lastStatusMessage = currentEngineStatus;
                                audioPlayer.playMessage(new QueuedMessage(folderHotOil, 0, this));
                            }
                            break;

                        case EngineStatus.HOT_WATER:
                            // don't play this if the last message was about hot oil *and* water - wait for 'all clear'
                            if (lastStatusMessage != EngineStatus.HOT_OIL_AND_WATER)
                            {
                                lastStatusMessage = currentEngineStatus;
                                audioPlayer.playMessage(new QueuedMessage(folderHotWater, 0, this));
                            }
                            break;

                        case EngineStatus.HOT_OIL_AND_WATER:
                            lastStatusMessage = currentEngineStatus;
                            audioPlayer.playMessage(new QueuedMessage(folderHotOilAndWater, 0, this));
                            break;
                        }
                    }
                    gameTimeAtLastStatusCheck = currentGameState.SessionData.SessionRunningTime;
                    engineData = new EngineData();
                }
            }
        }
Esempio n. 13
0
        public void UpdateGroupLogic(Type newLogic)
        {
            if (newLogic == null)
            {
                LogManager.GetCurrentClassLogger().Info($"Scene template {_worldLocationId} logic is empty!");
                Clear();
                return;
            }

            _myItems = GameStateData.GetWrapperCollection();

            var logic = Activator.CreateInstance(newLogic) as ILogic;

            if (logic == null)
            {
                LogManager.GetCurrentClassLogger().Error($"Initialize location logic error! SceneId = {_worldLocationId}. Message: Logic is null!");
                VRErrorManager.Instance.Show(ErrorHelper.GetErrorDescByCode(Errors.ErrorCode.LogicInitError));

                return;
            }

            Logic = logic;

            try
            {
                LogManager.GetCurrentClassLogger().Info($"Scene template {_worldLocationId} logic initialize started...");
                InitializeLogic();
                LogManager.GetCurrentClassLogger().Info($"Scene template {_worldLocationId} logic initialize successful");
            }
            catch (Exception e)
            {
                ShowLogicExceptionError(Errors.ErrorCode.LogicInitError, "Initialize scene template logic error!", e);
                Logic = null;
            }
        }
Esempio n. 14
0
 private void triggerEvent(String eventName, AbstractEvent abstractEvent, GameStateData previousGameState, GameStateData currentGameState)
 {
     try
     {
         abstractEvent.trigger(previousGameState, currentGameState);
     }
     catch (Exception e)
     {
         if (faultingEventsCount.ContainsKey(eventName))
         {
             faultingEventsCount[eventName]++;
             if (faultingEventsCount[eventName] > 5)
             {
                 Console.WriteLine("Event " + eventName +
                                   " has failed > 5 times in this session");
             }
         }
         if (!faultingEvents.ContainsKey(eventName))
         {
             Console.WriteLine("Event " + eventName + " threw exception " + e.Message);
             Console.WriteLine("This is the first time this event has failed in this session");
             faultingEvents.Add(eventName, e.Message);
             faultingEventsCount.Add(eventName, 1);
         }
         else if (faultingEvents[eventName] != e.Message)
         {
             Console.WriteLine("Event " + eventName + " threw a different exception: " + e.Message);
             faultingEvents[eventName] = e.Message;
         }
     }
 }
Esempio n. 15
0
        public LevelFinishController(GameStateData gameStateData)
        {
            _gameStateData = gameStateData;

            Collectable.OnCollected     += Collectable_OnCollected;
            AiBehaviour.OnPlayerCatched += AiBehaviour_OnPlayerCatched;
        }
Esempio n. 16
0
 void Awake()
 {
     enemyLogic = this.gameObject.GetComponent<EnemyLogic>();
     enemyData = this.gameObject.GetComponent<EnemyData>();
     playerData = GameObject.Find("Player").GetComponent<PlayerData>();
     gameStateData = GameObject.Find("GameState").GetComponent<GameStateData>();
 }
        /*
         * IMPORTANT: This method is called twice - when the message becomes due, and immediately before playing it (which may have a
         * delay caused by the length of the queue at the time). So be *very* careful when checking and updating local state in here.
         */
        public override bool isMessageStillValid(string eventSubType, GameStateData currentGameState, Dictionary <String, Object> validationData)
        {
            if (base.isMessageStillValid(eventSubType, currentGameState, validationData))
            {
                if (currentGameState.PitData.InPitlane)
                {
                    return(false);
                }

                if (validationData == null)
                {
                    return(true);
                }

                if ((string)validationData[FrozenOrderMonitor.validateMessageTypeKey] == FrozenOrderMonitor.validateMessageTypeAction)
                {
                    var queuedAction           = (FrozenOrderAction)validationData[FrozenOrderMonitor.validationActionKey];
                    var queuedAssignedPosition = (int)validationData[FrozenOrderMonitor.validationAssignedPositionKey];
                    var queuedDriverToFollow   = (string)validationData[FrozenOrderMonitor.validationDriverToFollowKey];
                    if (queuedAction == currentGameState.FrozenOrderData.Action &&
                        queuedAssignedPosition == currentGameState.FrozenOrderData.AssignedPosition &&
                        queuedDriverToFollow == currentGameState.FrozenOrderData.DriverToFollowRaw)
                    {
                        return(true);
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Frozen Order: message invalidated.  Was {0} {1} {2} is {3} {4} {5}", queuedAction, queuedAssignedPosition, queuedDriverToFollow,
                                                        currentGameState.FrozenOrderData.Action, currentGameState.FrozenOrderData.AssignedPosition, currentGameState.FrozenOrderData.DriverToFollowRaw));
                        return(false);
                    }
                }
            }
            return(false);
        }
Esempio n. 18
0
 private void checkForNewOvertakes(GameStateData previousGameState, GameStateData currentGameState)
 {
     if (currentGameState.SessionData.SessionPhase == SessionPhase.Green &&
         currentGameState.SessionData.SessionType == SessionType.Race && currentGameState.SessionData.CompletedLaps > 0)
     {
         if (currentGameState.Now > lastPassCheck.Add(passCheckInterval))
         {
             lastPassCheck = currentGameState.Now;
             if (currentGameState.SessionData.TimeDeltaFront > 0)
             {
                 gapsAhead.Add(currentGameState.SessionData.TimeDeltaFront);
             }
             if (currentGameState.SessionData.TimeDeltaBehind > 0)
             {
                 gapsBehind.Add(currentGameState.SessionData.TimeDeltaBehind);
             }
             string currentOpponentAheadKey  = currentGameState.getOpponentKeyInFront(true);
             string currentOpponentBehindKey = currentGameState.getOpponentKeyBehind(true);
             // seems like belt and braces, but as Raceroom names aren't unique we need to double check a pass actually happened here:
             if (frequencyOfOvertakingMessages > 0 && currentOpponentAheadKey != opponentAheadKey)
             {
                 if (currentGameState.SessionData.CurrentLapIsValid && !currentGameState.PitData.InPitlane &&
                     currentOpponentBehindKey == opponentAheadKey && isPassMessageCandidate(gapsAhead, passCheckSamplesToCheck, minAverageGapForPassMessage))
                 {
                     OpponentData carWeJustPassed = currentGameState.OpponentData[currentOpponentBehindKey];
                     if (carWeJustPassed.CompletedLaps == currentGameState.SessionData.CompletedLaps &&
                         CarData.IsCarClassEqual(carWeJustPassed.CarClass, currentGameState.carClass))
                     {
                         timeWhenWeMadeAPass           = currentGameState.Now;
                         opponentKeyForCarWeJustPassed = currentOpponentBehindKey;
                         lastOvertakeWasClean          = true;
                         if (currentGameState.CarDamageData.LastImpactTime > 0 && (currentGameState.SessionData.SessionRunningTime - currentGameState.CarDamageData.LastImpactTime) < secondsToCheckForDamageOnPass)
                         {
                             lastOvertakeWasClean = false;
                         }
                     }
                 }
                 gapsAhead.Clear();
             }
             if (frequencyOfBeingOvertakenMessages > 0 && opponentBehindKey != currentOpponentBehindKey)
             {
                 if (!currentGameState.PitData.InPitlane && currentOpponentAheadKey == opponentBehindKey && isPassMessageCandidate(gapsBehind, beingPassedCheckSamplesToCheck, minAverageGapForBeingPassedMessage))
                 {
                     // TODO: check if we need to do a pit check here - don't think so
                     OpponentData carThatJustPassedUs = currentGameState.OpponentData[currentOpponentAheadKey];
                     if (carThatJustPassedUs.CompletedLaps == currentGameState.SessionData.CompletedLaps &&
                         CarData.IsCarClassEqual(carThatJustPassedUs.CarClass, currentGameState.carClass))
                     {
                         timeWhenWeWerePassed = currentGameState.Now;
                         opponentKeyForCarThatJustPassedUs = currentOpponentAheadKey;
                     }
                 }
                 gapsBehind.Clear();
             }
             opponentAheadKey  = currentOpponentAheadKey;
             opponentBehindKey = currentOpponentBehindKey;
         }
     }
 }
Esempio n. 19
0
        public override void trigger(Object lastStateObj, Object currentStateObj, GameStateData currentGameState)
        {
            F12018StructWrapper currentWrapper = (F12018StructWrapper)currentStateObj;

            if (currentWrapper.packetLapData.m_lapData == null || currentWrapper.packetMotionData.m_carMotionData == null || currentWrapper.packetCarTelemetryData.m_carTelemetryData == null)
            {
                return;
            }
            Boolean inPits       = currentWrapper.packetLapData.m_lapData[currentWrapper.packetLapData.m_header.m_playerCarIndex].m_pitStatus != 0;
            Boolean isSpectating = currentWrapper.packetSessionData.m_isSpectating != 0;

            if (inPits || isSpectating)
            {
                return;
            }

            DateTime now = new DateTime(currentWrapper.ticksWhenRead);

            if (enabled && currentWrapper.packetMotionData.m_carMotionData.Length > 1)
            {
                int playerIndex = currentWrapper.packetMotionData.m_header.m_playerCarIndex;

                CarMotionData playerData = currentWrapper.packetMotionData.m_carMotionData[playerIndex];

                float[] currentPlayerPosition = new float[] { playerData.m_worldPositionX, playerData.m_worldPositionZ };

                List <float[]> currentOpponentPositions    = new List <float[]>();
                List <float[]> currentOpponentVelocityData = new List <float[]>();
                float[]        playerVelocityData          = new float[3];
                playerVelocityData[0] = (float)currentWrapper.packetCarTelemetryData.m_carTelemetryData[currentWrapper.packetCarTelemetryData.m_header.m_playerCarIndex].m_speed * 0.277778f;
                playerVelocityData[1] = playerData.m_worldVelocityX;
                playerVelocityData[2] = playerData.m_worldVelocityZ;

                for (int i = 0; i < currentWrapper.packetMotionData.m_carMotionData.Length; i++)
                {
                    if (i == playerIndex)
                    {
                        continue;
                    }
                    CarMotionData opponentData     = currentWrapper.packetMotionData.m_carMotionData[i];
                    float[]       currentPositions = new float[] { opponentData.m_worldPositionX, opponentData.m_worldPositionZ };
                    currentOpponentPositions.Add(currentPositions);
                    currentOpponentVelocityData.Add(new float[] { opponentData.m_worldVelocityX, opponentData.m_worldVelocityZ });
                }
                if (currentOpponentPositions.Count() > 0)
                {
                    float playerRotation = playerData.m_yaw;
                    if (playerRotation < 0)
                    {
                        playerRotation = playerRotation * -1;
                    }
                    else
                    {
                        playerRotation = twoPi - playerRotation;
                    }
                    internalSpotter.triggerInternal(playerRotation, currentPlayerPosition, playerVelocityData, currentOpponentPositions, currentOpponentVelocityData);
                }
            }
        }
Esempio n. 20
0
        public Intent Act(ref GameStateData gs, int id)
        {
            intent.actionIntent =
                (ActionsAvailable)rdm.NextInt((int)ActionsAvailable.NONE, (int)ActionsAvailable.BLOCK);
            intent.moveIntent = (ActionsAvailable)rdm.NextInt(0, (int)ActionsAvailable.NONE);

            return(intent);
        }
Esempio n. 21
0
        public override GameStateData mapToGameStateData(Object structWrapper, GameStateData previousGameState)
        {
            F12018StructWrapper wrapper = (F12018StructWrapper)structWrapper;
            long ticks = wrapper.ticksWhenRead;

            // TODO: one or two minor things here ;)
            return(new GameStateData(ticks));
        }
Esempio n. 22
0
 public override bool isMessageStillValid(string eventSubType, GameStateData currentGameState, Dictionary <string, object> validationData)
 {
     if (validationData != null && validationData.ContainsKey("position") && (int)validationData["position"] != currentGameState.SessionData.Position)
     {
         return(false);
     }
     return(true);
 }
Esempio n. 23
0
 public void Initialize(GameStateData gameStateData = null)
 {
     if (gameStateData == null)
     {
         CreateNewCardToPurchase("Wheat Field", 6);
         CreateNewCardToPurchase("Bakery", 6);
     }
 }
Esempio n. 24
0
        private bool ImmediateOpponentIsValidForDRSMessage(GameStateData currentGameState, bool inFront)
        {
            string       opponentKey = inFront ? currentGameState.getOpponentKeyInFront(currentGameState.carClass) : currentGameState.getOpponentKeyBehind(currentGameState.carClass);
            OpponentData opponent;

            return(opponentKey != null && currentGameState.OpponentData.TryGetValue(opponentKey, out opponent) &&
                   opponent != null && !opponent.isEnteringPits() && !opponent.isExitingPits() && !opponent.InPits && !opponent.isApporchingPits);
        }
Esempio n. 25
0
 public void Initialize(GameStateData gameStateData)
 {
     _gameStateData = gameStateData;
     
     _gameStateData.GameOver += OnGameOver;
     _gameStateData.OnReset += OnOnReset;
     gameObject.SetActive(false);
 }
 private void Awake()
 {
     Input.multiTouchEnabled = true;
     gameStateData           = GameFacade.GetInstance().gameStateData;
     audioController         = GameFacade.GetInstance().AudioController;
     enemyController         = GameFacade.GetInstance().EnemyController;
     gameUIController        = GameFacade.GetInstance().GameUIController;
 }
Esempio n. 27
0
    public void Load(string FileName = "GameData.xml")
    {
        XmlSerializer Serializer = new XmlSerializer(typeof(GameStateData));
        FileStream    Stream     = new FileStream(FileName, FileMode.Open);

        GameState = Serializer.Deserialize(Stream) as GameStateData;
        Stream.Close();
    }
Esempio n. 28
0
 private void Initialize()
 {
     EnemyController     = GetComponent <EnemyController>();
     GameStateController = GetComponent <GameStateController>();
     PlayerController    = GetComponent <PlayerController>();
     playerData          = new PlayerData();
     gameStateData       = new GameStateData();
 }
Esempio n. 29
0
 public override void trigger(Object lastStateObj, Object currentStateObj, GameStateData currentGameState)
 {
     if (enabled && !paused)
     {
         int currentState = (int)currentStateObj;
         internalSpotter.triggerInternal((int)currentState);
     }
     return;
 }
 private bool HasValidGameStateData(GameStateData gameStateData)
 {
     if (gameStateData == null ||
         string.IsNullOrWhiteSpace(gameStateData?.LoginToken))
     {
         return(false);
     }
     return(true);
 }
Esempio n. 31
0
        public ObjectController GetObject()
        {
            if (_saveIdGroup != 0)
            {
                return(GameStateData.GetObjectInLocation(_saveId));
            }

            return(null);
        }
    //-----------------------------------------------
    //Load game data from XML file
    public void Load(string FileName = "GameData.xml")
    {
        //Call load start notification
        GameManager.Notifications.PostNotification(this, "LoadGamePrepare");

        XmlSerializer Serializer = new XmlSerializer(typeof(GameStateData));
        FileStream Stream = new FileStream(FileName, FileMode.Open);
        GameState = Serializer.Deserialize(Stream) as GameStateData;
        Stream.Close();

        //Call load end notification
        GameManager.Notifications.PostNotification(this, "LoadGameComplete");
    }
     public void Load(string FileName = "GameData.xml")
     {
          XmlSerializer Serializer = new XmlSerializer(typeof(GameStateData));
          try
          {
               FileStream FStream = new FileStream(FileName, FileMode.Open);
               GameState = Serializer.Deserialize(FStream) as GameStateData;
               FStream.Close();
          }

          catch (FileNotFoundException)
          {

          }
     }
Esempio n. 34
0
 public void Init(GameStateData gameState)
 {
     gameStateData = gameState;
 }
Esempio n. 35
0
    /// <summary>
    /// Save Game
    /// </summary>
    public void Save()
    {
        // Create new Save file.
        GameStateData stateData = new GameStateData();
        GameLevelData levelData = new GameLevelData();

        // Write State Data
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(PersistentGameState());
        bf.Serialize(file, stateData);
        file.Close();

        // Write Level Data
        file = File.Create(PersistentLevelState());
        bf.Serialize(file, levelData);
        file.Close();
    }
        /// <summary>
        /// Starts the playing.
        /// This entails creating a new game state, initializing the
        /// type of game manager needed and loading the game scene (level 1)
        /// </summary>
        /// <param name="type">Type of game</param>
        public void StartPlaying(GameType type)
        {
            Debug.Log("Let the " + type + " game begin!");

            gameState = new GameStateData();

            this.gameType = type;

            // Run as a local manager or remote
            if (gameType == GameType.MultiplayerLocal ||
                gameType == GameType.SinglePlayer)
            {
                RunAsLocalManager();
            }
            else
            {
                RunAsRemoteManager();
            }

            // 1 is the game, 0 is the main menu
            SceneManager.LoadScene(1);
        }
        /// <summary>
        /// Gets the state of the game serialized so it can be sent to others.
        /// </summary>
        /// <param name="phase">The phase of games state to generate.</param>
        /// <returns>The game state.</returns>
        internal byte[] GetGameStateData(GameStateData.Phase phase)
        {
            gameState.SerialNumber = gameState.SerialNumber + 1;
            gameState.CurrentPhase = phase;
            Debug.Log("Serializing Game state: " + phase + " " + gameState.SerialNumber);
            gameState.Players.Clear();
            foreach (PlayerInfo p in PlayerInfo.AllPlayers)
            {
                gameState.Players.Add(p.DataState);
                if (phase == GameStateData.Phase.Initializing ||
                    phase == GameStateData.Phase.Connecting)
                {
                    GameObject playerObj = levelmanager.GetPlayerObject(p.DeviceId);
                    if (playerObj != null)
                    {
                        OnObjectChanged(playerObj.GetComponent<Shareable>());
                    }
                }
            }

            GameDataMessage msg = new GameDataMessage();
            if (gameType == GameType.MultiplayerLocal)
            {
                msg.GameState = gameState;
            }

            msg.Changes = new List<ItemState>();
            msg.Changes.AddRange(changesToShare.Values);

            MemoryStream m = new MemoryStream();
            bf.Serialize(m, msg);
            m.Flush();
            return m.ToArray();
        }
Esempio n. 38
0
    private void LoadGameStateData(GameStateData stateData)
    {
        // If Game State Date
        if (stateData != null)
        {
            // Load Player
            LoadPlayer(stateData.playerSave);

            // Set Main Camera Position
            LoadCamera(stateData.cameraSave);

            // Load Enemies
            LoadEnemies(stateData.enemyState);

            // Load NPCs
            LoadNPCs(stateData.npcState);

            // Read in saved items.
            //for (int i = 0; i < data.items.Count; i++)
            //{
            //    ItemDatabase.itemDatabase.AddItem(data.items[i]);
            //}
        }
    }
Esempio n. 39
0
    void Start()
    {
        GameState gameState = Camera.main.GetComponent<GameState>();
        if (gameState == null) {
            throw new MissingComponentException("Unable to find GameState. The 'GameState' script needs to be attached to the main Camera.");
        }
        gameStateData = gameState.gameStateData;
        if (gameStateData == null) {
            throw new MissingReferenceException("The gameStateData has not been initialised yet.");
        }

        InitEventSubscriptions();
    }
Esempio n. 40
0
    void InitialiseNewGame(bool generateRandomMap, int fogOfWar)
    {
        Debug.Log("Generating new game...");
        GameStateData gameStateData = new GameStateData();
        gameState.Init(gameStateData);

        AirTrafficData airTrafficData = new AirTrafficData();
        airTrafficControl.Init(gameStateData.CurrentDay, fogOfWar, airTrafficData);

        SpaceData spaceData;
        if (generateRandomMap) {
            spaceData = MapGenerator.GenerateRandomMap(SettingsController.GetInstance().planetCount);
        } else {
            spaceData = MapGenerator.GenerateDefaultMap();
        }
        space.Init(spaceData);

        // Handling players...
        PlaceNewPlayersOnMap(SettingsController.GetInstance().playerFile, SettingsController.GetInstance().kiCount);
        SettingsController.GetInstance().map.playerListData = playerManager.PlayerListData;
    }