Esempio n. 1
0
        private async Task <UserGameState> GetGameStateFromDatabase(UserGameKey userGameKey)
        {
            using (var db = databaseManager.GetWritableDatabase())
            {
                var gameState = await db.GameStates.FindAsync(userGameKey.UserId, userGameKey.GameId);

                if (gameState == null)
                {
                    gameState = new GameState
                    {
                        UserId      = userGameKey.UserId,
                        GameId      = userGameKey.GameId,
                        Type        = GameStateType.SlotStateNormal,
                        LastRoundId = 0
                    };
                    db.GameStates.Add(gameState);
                    await db.SaveChangesAsync();
                }
                return(GameStateMapper.Map(gameState));
            }
        }
Esempio n. 2
0
        public static GameStateMapper GetGameState()
        {
            var board = GameBoard.GetBoard();

            var state = new GameStateMapper
            {
                Earth           = board.GetEarth(),
                Cards           = board.GetQueueOfGameCards(),
                UsedCards       = board.GetUsedCards(),
                TradedCardSets  = board.GetTradedCardSets(),
                Players         = board.GetPlayerList(),
                CurrentPlayer   = board.CurrentPlayer,
                PlayerTurnQueue = board.GetCurrentPlayerQueue()
            };

            foreach (var territory in state.Earth.Territories)
            {
                territory.Neighbours = null;
            }
            return(state);
        }
Esempio n. 3
0
        public Boolean Run(String filenameToRun, int interval, Boolean dumpToFile)
        {
            loadDataFromFile = false;
            audioPlayer.mute = false;
            if (filenameToRun != null && System.Diagnostics.Debugger.IsAttached)
            {
                loadDataFromFile = true;
                spotterEnabled = false;
                if (interval > 0)
                {
                    _timeInterval = TimeSpan.FromMilliseconds(interval);
                    audioPlayer.mute = false;
                }
                else
                {
                    _timeInterval = TimeSpan.Zero;
                    audioPlayer.mute = true;
                }
                dumpToFile = false;
            }

            gameStateMapper = GameStateReaderFactory.getInstance().getGameStateMapper(gameDefinition);
            gameStateMapper.setSpeechRecogniser(speechRecogniser);
            gameDataReader = GameStateReaderFactory.getInstance().getGameStateReader(gameDefinition);
            gameDataReader.dumpToFile = System.Diagnostics.Debugger.IsAttached && dumpToFile;
            if (gameDefinition.spotterName != null)
            {
                spotter = (Spotter)Activator.CreateInstance(Type.GetType(gameDefinition.spotterName),
                    audioPlayer, spotterEnabled);
            }
            else
            {
                Console.WriteLine("No spotter defined for game " + gameDefinition.friendlyName);
                spotter = null;
            }
            running = true;
            DateTime nextRunTime = DateTime.Now;
            if (!audioPlayer.initialised)
            {
                Console.WriteLine("Failed to initialise audio player");
                return false;
            }
            audioPlayer.startMonitor();
            Boolean attemptedToRunGame = false;

            int threadSleepTime = ((int)_timeInterval.Milliseconds / 10) + 1;
            Console.WriteLine("Polling for shared data every " + _timeInterval.Milliseconds + "ms, pausing " + threadSleepTime + "ms between invocations");
            Boolean sessionFinished = false;

            while (running)
            {
                DateTime now = DateTime.Now;
                if (now > nextRunTime)
                {
                    nextRunTime = DateTime.Now.Add(_timeInterval);
                    if (!loadDataFromFile)
                    {
                        if (gameDefinition.processName == null || Utilities.IsGameRunning(gameDefinition.processName))
                        {
                            if (!mapped)
                            {
                                mapped = gameDataReader.Initialise();
                            }
                        }
                        else if (UserSettings.GetUserSettings().getBoolean(gameDefinition.gameStartEnabledProperty) && !attemptedToRunGame)
                        {
                            Utilities.runGame(UserSettings.GetUserSettings().getString(gameDefinition.gameStartCommandProperty),
                                UserSettings.GetUserSettings().getString(gameDefinition.gameStartCommandOptionsProperty));
                            attemptedToRunGame = true;
                        }
                    }

                    if (loadDataFromFile || mapped)
                    {
                        stateCleared = false;
                        Object rawGameData;
                        if (loadDataFromFile)
                        {
                            rawGameData = gameDataReader.ReadGameDataFromFile(filenameToRun);
                            if (rawGameData == null)
                            {
                                Console.WriteLine("Reached the end of the data file, sleeping to clear queued messages");
                                Thread.Sleep(5000);
                                audioPlayer.purgeQueues();
                                running = false;
                                continue;
                            }
                        }
                        else
                        {
                            rawGameData = gameDataReader.ReadGameData(false);
                        }
                        gameStateMapper.versionCheck(rawGameData);

                        GameStateData nextGameState = null;
                        try
                        {
                            nextGameState = gameStateMapper.mapToGameStateData(rawGameData, currentGameState);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Error mapping game data: " + e.StackTrace);
                        }

                        if (nextGameState != null)
                        {
                            previousGameState = currentGameState;
                            currentGameState = nextGameState;
                            if (!sessionFinished && currentGameState.SessionData.SessionPhase == SessionPhase.Finished
                                && previousGameState != null)
                            {
                                audioPlayer.purgeQueues();
                                if (displaySessionLapTimes)
                                {
                                    Console.WriteLine("Session lap times:");
                                    Console.WriteLine(String.Join(";", currentGameState.SessionData.formattedPlayerLapTimes));
                                }
                                sessionEndMessages.trigger(previousGameState.SessionData.SessionRunningTime, previousGameState.SessionData.SessionType, currentGameState.SessionData.SessionPhase,
                                    previousGameState.SessionData.Position, previousGameState.SessionData.NumCarsAtStartOfSession, previousGameState.SessionData.CompletedLaps,
                                    previousGameState.SessionData.IsDisqualified);
                                audioPlayer.closeChannel();
                                sessionFinished = true;
                                audioPlayer.disablePearlsOfWisdom = false;
                                if (loadDataFromFile)
                                {
                                    Thread.Sleep(2000);
                                }
                            }
                            float prevTime = previousGameState == null ? 0 : previousGameState.SessionData.SessionRunningTime;
                            if (currentGameState.SessionData.IsNewSession)
                            {
                                audioPlayer.disablePearlsOfWisdom = false;
                                displayNewSessionInfo(currentGameState);
                                sessionFinished = false;
                                if (!stateCleared)
                                {
                                    Console.WriteLine("Clearing game state...");
                                    audioPlayer.purgeQueues();
                                    audioPlayer.closeChannel();
                                    foreach (KeyValuePair<String, AbstractEvent> entry in eventsList)
                                    {
                                        entry.Value.clearState();
                                    }
                                    faultingEvents.Clear();
                                    faultingEventsCount.Clear();
                                    stateCleared = true;
                                }
                                if (enableDriverNames)
                                {
                                    List<String> rawDriverNames = currentGameState.getRawDriverNames();
                                    if (currentGameState.SessionData.DriverRawName != null && currentGameState.SessionData.DriverRawName.Length > 0 &&
                                        !rawDriverNames.Contains(currentGameState.SessionData.DriverRawName))
                                    {
                                        rawDriverNames.Add(currentGameState.SessionData.DriverRawName);
                                    }
                                    if (rawDriverNames.Count > 0)
                                    {
                                        List<String> usableDriverNames = DriverNameHelper.getUsableDriverNames(rawDriverNames, audioPlayer.soundFilesPath);
                                        if (speechRecogniser != null && speechRecogniser.initialised)
                                        {
                                            speechRecogniser.addOpponentSpeechRecognition(usableDriverNames, enableDriverNames);
                                        }
                                        audioPlayer.cacheDriverNames(usableDriverNames);
                                    }
                                }
                            }
                            else if (!sessionFinished && previousGameState != null &&
                                        (currentGameState.SessionData.SessionRunningTime > previousGameState.SessionData.SessionRunningTime ||
                                        (previousGameState != null && previousGameState.SessionData.SessionPhase != currentGameState.SessionData.SessionPhase)))
                            {
                                if (spotter != null)
                                {
                                    spotter.unpause();
                                }
                                if (currentGameState.SessionData.IsNewLap)
                                {
                                    currentGameState.display();
                                }
                                stateCleared = false;
                                foreach (KeyValuePair<String, AbstractEvent> entry in eventsList)
                                {
                                    if (entry.Value.isApplicableForCurrentSessionAndPhase(currentGameState.SessionData.SessionType, currentGameState.SessionData.SessionPhase))
                                    {
                                        triggerEvent(entry.Key, entry.Value, previousGameState, currentGameState);
                                    }
                                }
                                if (spotter != null && spotterEnabled && !spotterIsRunning && !loadDataFromFile)
                                {
                                    Console.WriteLine("********** starting spotter***********");
                                    spotter.clearState();
                                    startSpotterThread();
                                }
                                else if (spotterIsRunning && !spotterEnabled)
                                {
                                    runSpotterThread = false;
                                }
                            }
                            else if (spotter != null)
                            {
                                spotter.pause();
                            }
                        }
                    }
                }
                else
                {
                    Thread.Sleep(threadSleepTime);
                    continue;
                }
            }
            foreach (KeyValuePair<String, AbstractEvent> entry in eventsList)
            {
                entry.Value.clearState();
            }
            if (spotter != null)
            {
                spotter.clearState();
            }
            stateCleared = true;
            currentGameState = null;
            previousGameState = null;
            sessionFinished = false;
            audioPlayer.stopMonitor();
            audioPlayer.disablePearlsOfWisdom = false;
            if (gameDataReader != null && gameDataReader.dumpToFile)
            {
                gameDataReader.DumpRawGameData();
            }
            gameDataReader.stop();
            return true;
        }
Esempio n. 4
0
        public Boolean Run(String filenameToRun, int interval, Boolean dumpToFile)
        {
            loadDataFromFile = false;
            audioPlayer.mute = false;
            if (filenameToRun != null && System.Diagnostics.Debugger.IsAttached)
            {
                loadDataFromFile = true;
                spotterEnabled   = false;
                if (interval > 0)
                {
                    _timeInterval    = TimeSpan.FromMilliseconds(interval);
                    audioPlayer.mute = false;
                }
                else
                {
                    _timeInterval    = TimeSpan.Zero;
                    audioPlayer.mute = true;
                }
                dumpToFile = false;
            }

            gameStateMapper = GameStateReaderFactory.getInstance().getGameStateMapper(gameDefinition);
            gameStateMapper.setSpeechRecogniser(speechRecogniser);
            gameDataReader = GameStateReaderFactory.getInstance().getGameStateReader(gameDefinition);
            gameDataReader.ResetGameDataFromFile();

            gameDataReader.dumpToFile = System.Diagnostics.Debugger.IsAttached && dumpToFile;
            if (gameDefinition.spotterName != null)
            {
                spotter = (Spotter)Activator.CreateInstance(Type.GetType(gameDefinition.spotterName),
                                                            audioPlayer, spotterEnabled);
            }
            else
            {
                Console.WriteLine("No spotter defined for game " + gameDefinition.friendlyName);
                spotter = null;
            }
            running = true;
            DateTime nextRunTime = DateTime.Now;

            if (!audioPlayer.initialised)
            {
                Console.WriteLine("Failed to initialise audio player");
                return(false);
            }
            audioPlayer.startMonitor();
            Boolean attemptedToRunGame = false;

            Console.WriteLine("Polling for shared data every " + _timeInterval.Milliseconds + "ms");
            Boolean sessionFinished = false;

            while (running)
            {
                DateTime now = DateTime.Now;
                if (now > nextRunTime)
                {
                    // ensure the updates don't get synchronised with the spotter / UDP receiver
                    int updateTweak = random.Next(10) - 5;
                    nextRunTime = DateTime.Now.Add(_timeInterval);
                    nextRunTime.Add(TimeSpan.FromMilliseconds(updateTweak));
                    if (!loadDataFromFile)
                    {
                        if (gameDefinition.processName == null || Utilities.IsGameRunning(gameDefinition.processName))
                        {
                            if (!mapped)
                            {
                                mapped = gameDataReader.Initialise();
                            }
                        }
                        else if (UserSettings.GetUserSettings().getBoolean(gameDefinition.gameStartEnabledProperty) && !attemptedToRunGame)
                        {
                            Utilities.runGame(UserSettings.GetUserSettings().getString(gameDefinition.gameStartCommandProperty),
                                              UserSettings.GetUserSettings().getString(gameDefinition.gameStartCommandOptionsProperty));
                            attemptedToRunGame = true;
                        }
                    }

                    if (loadDataFromFile || mapped)
                    {
                        stateCleared = false;
                        Object rawGameData;
                        if (loadDataFromFile)
                        {
                            rawGameData = gameDataReader.ReadGameDataFromFile(filenameToRun);
                            if (rawGameData == null)
                            {
                                Console.WriteLine("Reached the end of the data file, sleeping to clear queued messages");
                                Thread.Sleep(5000);
                                audioPlayer.purgeQueues();
                                running = false;
                                continue;
                            }
                        }
                        else
                        {
                            rawGameData = gameDataReader.ReadGameData(false);
                        }
                        gameStateMapper.versionCheck(rawGameData);

                        GameStateData nextGameState = null;
                        try
                        {
                            nextGameState = gameStateMapper.mapToGameStateData(rawGameData, currentGameState);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Error mapping game data: " + e.StackTrace);
                        }
                        // if we're paused or viewing another car, the mapper will just return the previous game state so we don't lose all the
                        // persistent state information. If this is the case, don't process any stuff
                        if (nextGameState != null && nextGameState != currentGameState)
                        {
                            previousGameState = currentGameState;
                            currentGameState  = nextGameState;
                            if (!sessionFinished && currentGameState.SessionData.SessionPhase == SessionPhase.Finished &&
                                previousGameState != null)
                            {
                                Console.WriteLine("Session finished");
                                audioPlayer.purgeQueues();
                                if (displaySessionLapTimes)
                                {
                                    Console.WriteLine("Session lap times:");
                                    Console.WriteLine(String.Join(";", currentGameState.SessionData.formattedPlayerLapTimes));
                                }
                                sessionEndMessages.trigger(previousGameState.SessionData.SessionRunningTime, previousGameState.SessionData.SessionType, currentGameState.SessionData.SessionPhase,
                                                           previousGameState.SessionData.SessionStartPosition, previousGameState.SessionData.Position, previousGameState.SessionData.NumCarsAtStartOfSession, previousGameState.SessionData.CompletedLaps,
                                                           previousGameState.SessionData.IsDisqualified);

                                sessionFinished = true;
                                audioPlayer.disablePearlsOfWisdom = false;
                                if (loadDataFromFile)
                                {
                                    Thread.Sleep(2000);
                                }
                            }
                            float prevTime = previousGameState == null ? 0 : previousGameState.SessionData.SessionRunningTime;
                            if (currentGameState.SessionData.IsNewSession)
                            {
                                Console.WriteLine("New session");
                                audioPlayer.disablePearlsOfWisdom = false;
                                displayNewSessionInfo(currentGameState);
                                sessionFinished = false;
                                if (!stateCleared)
                                {
                                    Console.WriteLine("Clearing game state...");
                                    audioPlayer.purgeQueues();

                                    foreach (KeyValuePair <String, AbstractEvent> entry in eventsList)
                                    {
                                        entry.Value.clearState();
                                    }
                                    faultingEvents.Clear();
                                    faultingEventsCount.Clear();
                                    stateCleared = true;
                                }
                                if (enableDriverNames)
                                {
                                    List <String> rawDriverNames = currentGameState.getRawDriverNames();
                                    if (currentGameState.SessionData.DriverRawName != null && currentGameState.SessionData.DriverRawName.Length > 0 &&
                                        !rawDriverNames.Contains(currentGameState.SessionData.DriverRawName))
                                    {
                                        rawDriverNames.Add(currentGameState.SessionData.DriverRawName);
                                    }
                                    if (rawDriverNames.Count > 0)
                                    {
                                        List <String> usableDriverNames = DriverNameHelper.getUsableDriverNames(rawDriverNames);
                                        if (speechRecogniser != null && speechRecogniser.initialised)
                                        {
                                            speechRecogniser.addOpponentSpeechRecognition(usableDriverNames, enableDriverNames);
                                        }
                                    }
                                }
                            }
                            // TODO: for AC free practice sessions, the SessionRunningTime is set to 1 hour in the mapper and stays there so this block never triggers
                            else if (!sessionFinished && previousGameState != null &&
                                     (currentGameState.SessionData.SessionRunningTime > previousGameState.SessionData.SessionRunningTime ||
                                      (previousGameState.SessionData.SessionPhase != currentGameState.SessionData.SessionPhase)) ||
                                     ((gameDefinition.gameEnum == GameEnum.PCARS_32BIT || gameDefinition.gameEnum == GameEnum.PCARS_64BIT || gameDefinition.gameEnum == GameEnum.PCARS_NETWORK) &&
                                      currentGameState.SessionData.SessionHasFixedTime && currentGameState.SessionData.SessionTotalRunTime == -1))
                            {
                                if (spotter != null)
                                {
                                    if (currentGameState.FlagData.isFullCourseYellow)
                                    {
                                        spotter.pause();
                                    }
                                    else
                                    {
                                        spotter.unpause();
                                    }
                                }
                                if (currentGameState.SessionData.IsNewLap)
                                {
                                    currentGameState.display();
                                }
                                stateCleared = false;
                                foreach (KeyValuePair <String, AbstractEvent> entry in eventsList)
                                {
                                    if (entry.Value.isApplicableForCurrentSessionAndPhase(currentGameState.SessionData.SessionType, currentGameState.SessionData.SessionPhase))
                                    {
                                        triggerEvent(entry.Key, entry.Value, previousGameState, currentGameState);
                                    }
                                }
                                if (spotter != null && spotterEnabled && !spotterIsRunning && !loadDataFromFile)
                                {
                                    Console.WriteLine("********** starting spotter***********");
                                    spotter.clearState();
                                    startSpotterThread();
                                }
                                else if (spotterIsRunning && !spotterEnabled)
                                {
                                    runSpotterThread = false;
                                }
                            }
                            else if (spotter != null)
                            {
                                spotter.pause();
                            }
                        }
                    }
                }
                else
                {
                    // ensure the updates don't get synchronised with the spotter / UDP receiver
                    int threadSleepTime = 5 + random.Next(10);
                    Thread.Sleep(threadSleepTime);
                    continue;
                }
            }
            foreach (KeyValuePair <String, AbstractEvent> entry in eventsList)
            {
                entry.Value.clearState();
            }
            if (spotter != null)
            {
                spotter.clearState();
            }
            stateCleared      = true;
            currentGameState  = null;
            previousGameState = null;
            sessionFinished   = false;
            Console.WriteLine("Stopping queue monitor");
            audioPlayer.stopMonitor();
            audioPlayer.disablePearlsOfWisdom = false;
            if (gameDataReader != null && gameDataReader.dumpToFile)
            {
                gameDataReader.DumpRawGameData();
            }
            gameDataReader.stop();
            return(true);
        }