Exemplo n.º 1
0
        public void GetMatchdayProfit123()
        {
            // Arrange
            configManagerMock.Setup(p => p.GetBetStyle()).Returns("123");
            List <MetricConfig> configs      = new List <MetricConfig>();
            List <double>       matchdayOdds = new List <double>();
            GlobalStats         globalStats  = new GlobalStats(configs, configManagerMock.Object, fixtureRetrieverMock.Object, logger);
            double oddGame1 = 2;
            double oddGame2 = 3;
            double oddGame3 = 4;

            matchdayOdds.Add(oddGame1);
            matchdayOdds.Add(oddGame2);
            matchdayOdds.Add(oddGame3);

            // Act
            double result = globalStats.GetMatchdayProfit(matchdayOdds);

            // Assert
            Assert.AreEqual(result, (oddGame1 - 1) +
                            (oddGame2 - 1) +
                            (oddGame3 - 1) +
                            (oddGame1 * oddGame2 - 1) +
                            (oddGame2 * oddGame3 - 1) +
                            (oddGame3 * oddGame1 - 1) +
                            (oddGame1 * oddGame2 * oddGame3 - 1));
        }
Exemplo n.º 2
0
        /// <summary>Get whether any machine groups may be blocked by a full chest.</summary>
        /// <param name="stats">The global stats to check.</param>
        private bool AnyMachineGroupsBlockedByFullChests(GlobalStats stats)
        {
            foreach (GroupStats group in stats.Locations.SelectMany(p => p.MachineGroups))
            {
                ulong filledSlots = 0;
                ulong totalSlots  = 0;
                foreach (var container in group.Containers)
                {
                    filledSlots += (ulong)container.FilledSlots;
                    totalSlots  += (ulong)container.TotalSlots;
                }

                if (filledSlots < totalSlots)
                {
                    continue;
                }

                bool hasOutputReady = group.Machines.Any(p => p.States.ContainsKey(MachineState.Done));
                if (hasOutputReady)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 3
0
 //Set text to whatever score it's supposed to be
 public void SetText()
 {
     if (bestLevel)
     {
         if (replaceWithRegularScore)
         {
             numberText.text = GameObject.Find("LevelSpawner").GetComponent <LevelSpawner>().GetLevel().ToString();
         }
         else
         {
             numberText.text = GlobalStats.GetFarthestLevel().ToString();
         }
     }
     else if (bestScore)
     {
         if (replaceWithRegularScore)
         {
             numberText.text = GlobalStats.score.ToString();
         }
         else
         {
             numberText.text = GlobalStats.GetHiScore().ToString();
         }
     }
     else if (coinBonus)
     {
         int coinBonus = GlobalStats.score / 50;
         numberText.text = coinBonus.ToString();
     }
 }
Exemplo n.º 4
0
    //End the game here along with highscores, rewards, etc.
    public void EndGame()
    {
        //Hide warning signs so they don't block the screen
        SpikeTrap.hideAllWarningSigns = true;

        //Grant bonus coins
        int coinBonus = GlobalStats.score / 50;

        endGameScreen.SetActive(true);

        //Coins are to be "tallied" so increase them afterwards.
        GlobalStats.coins += coinBonus;


        //Check for best scores here. Show feedback if the player improved!
        if (GlobalStats.CheckForHiScore())
        {
            GameObject textObj = endGameScreen.transform.Find("NewBestScoreText").gameObject;
            textObj.GetComponent <Text>().text = "New Best! ";
            SoundManager.PlaySound(SoundManager.Sounds.HISCORE);
        }
        if (GlobalStats.CheckForFarthestLevel())
        {
            GameObject textObj = endGameScreen.transform.Find("NewBestLevelText").gameObject;
            textObj.GetComponent <Text>().text = "New Best! ";
            SoundManager.PlaySound(SoundManager.Sounds.HISCORE);
        }
    }
Exemplo n.º 5
0
        async Task <GlobalStats> RunStatsAsync(string method)
        {
            GlobalStats batch = null;

            using (var client = new HttpClient())
            {
                client.BaseAddress = baseUrl;

                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;

                // New code:
                HttpResponseMessage response = await client.GetAsync(method);

                if (response.IsSuccessStatusCode)
                {
                    Debug.WriteLine("Batch Request Recieved");
                    return(batch = await response.Content.ReadAsAsync <GlobalStats>()); // Install-Package Microsoft.AspNet.WebApi.Client

                    //Console.WriteLine("{0}\t${1}\t{2}", batch.Key, batch.Data, batch.LastComplete);
                }
                else
                {
                    Debug.WriteLine("Batch Request Failed");
                    return(batch);
                }
            }
        }
Exemplo n.º 6
0
        public void GetMatchdayDataDepth()
        {
            // Arrange
            configManagerMock.Setup(p => p.GetBetStyle()).Returns("1");
            configManagerMock.Setup(p => p.GetUseExpanded()).Returns(false);
            configManagerMock.Setup(p => p.GetMaxOdds()).Returns(10);
            configManagerMock.Setup(p => p.GetMinOdds()).Returns(1);
            configManagerMock.Setup(p => p.GetDrawMargin()).Returns(10);
            configManagerMock.Setup(p => p.GetDrawMixedMargin()).Returns(20);
            configManagerMock.Setup(p => p.GetMinMetricCorrect()).Returns(1);

            int matchDay = 4;
            int year     = 0;

            MetricConfig metricConfigLastGames = new MetricConfig
            {
                name  = "LastGamesMetric",
                depth = 3
            };

            List <MetricConfig> configs = new List <MetricConfig>
            {
                metricConfigLastGames
            };

            // Act
            GlobalStats globalStats = new GlobalStats(configs, configManagerMock.Object, fixtureRetrieverMock.Object, logger);

            globalStats.GetMatchdayData(out int correctFixturesWithData, out int totalFixturesWithData, out double currentProfit, matchDay, year);

            // Assert
            Assert.AreEqual(correctFixturesWithData, 1);//just one is correct
            Assert.AreEqual(totalFixturesWithData, 2);
            Assert.AreEqual(currentProfit, commonOdds["2"] - 1 - 1);
        }
Exemplo n.º 7
0
        public async Task <GlobalStats?> Get(CancellationToken cancellationToken = default)
        {
            var cacheEntry = await Cache.GetStringAsync(CacheKeys.GlobalStats, cancellationToken);

            if (cacheEntry != null)
            {
                Logger.LogTrace("Global Stats were found in cache");

                return(JsonConvert.DeserializeObject <GlobalStats>(cacheEntry));
            }

            Logger.LogTrace("Global Stats were not found in cache");

            GlobalStats stats;

            try
            {
                var pokemonRequests = await DbContext.Stats.AsNoTracking().SumAsync(st => st.Requests.Pokemon, cancellationToken);

                var fusionRequests = await DbContext.Stats.AsNoTracking().SumAsync(st => st.Requests.Fusion, cancellationToken);

                var usersCount = await DbContext.Users.AsNoTracking().CountAsync(cancellationToken);

                var chatsCount = await DbContext.Chats.AsNoTracking().CountAsync(ch => ch.Type == Chat.ChatType.Group || ch.Type == Chat.ChatType.Supergroup, cancellationToken);

                stats = new GlobalStats(pokemonRequests, fusionRequests, usersCount, chatsCount);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Unhandled error calculating global stats.");
                return(default);
Exemplo n.º 8
0
        internal async static Task <GlobalStats> GetGlobalStats()
        {
            try {
                var resp = await Ioc.Default.GetService <ICoinGecko>().GetGlobalStats();

                var response = JsonSerializer.Deserialize <object>(resp.ToString());

                var data = ((JsonElement)response).GetProperty("data");

                var stats        = new GlobalStats();
                var currency     = App.currency.ToLowerInvariant();
                var btcDominance = double.Parse(
                    data.GetProperty("market_cap_percentage").GetProperty("btc").ToString()
                    );
                var totalVolume = double.Parse(
                    data.GetProperty("total_volume").GetProperty(currency).ToString()
                    );
                var totalMarketCap = double.Parse(
                    data.GetProperty("total_market_cap").GetProperty(currency).ToString()
                    );

                stats.BtcDominance   = Math.Round(btcDominance, 2);
                stats.TotalVolume    = totalVolume;
                stats.TotalMarketCap = totalMarketCap;
                stats.CurrencySymbol = App.currencySymbol;
                return(stats);
            }
            catch (Exception ex) {
                return(new GlobalStats());
            }
        }
Exemplo n.º 9
0
    public void BuyOrUpgradeUnit()
    {
        // Прокачиваем
        if (unit_lvl > 0)
        {
            int gems = GlobalData.GetInt("Gems");
            GlobalData.SetInt("Gems", gems - unit_lvl);
        }

        // Покупаем
        else
        {
            int gold = GlobalData.GetInt("Gold");
            GlobalData.SetInt("Gold", gold - GetUnitGoldCost());

            // Добавляем в статистику +1 разблокированный юнит
            GlobalStats.SetStats("StatsUnitsUnlocked", 1);
        }

        unit_lvl++;                               // +1 уровень
        GlobalData.SetInt(ChoosedUnit, unit_lvl); // Устанавливаем новый уровень юнита

        UpdateInfo();
        unit_button.UpdateText();
        money_info.UpdateInfo();
    }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting Database Loading");
            GlobalStats  globalStats = Util.LoadJSON <GlobalStats>("global.json");                                          // some global stats
            List <Match> matches     = Util.LoadJSON <List <Match> >("matches.json");                                       // list of all matches
            Dictionary <string, string> playerAvatars = Util.LoadJSON <Dictionary <string, string> >("playerAvatars.json"); // list of player avatar images (steam urls)
            List <Player> players = Util.LoadJSON <List <Player> >("players.json");                                         // list of all players
            //Dictionary<long, string> uidTable = Util.LoadJSON<Dictionary<long, string>>("uidTable.json"); // list of custom UIDs and associated steamids

            var dbCon = DBConnection.Instance();

            dbCon.DatabaseName = "aytgrcom_Counterstrike";
            Queries queries = new Queries();

            queries.PlayerAvatars = playerAvatars;

            //queries.TestConnection();
            queries.AddStatTypes();
            queries.AddAllPlayers(players);
            queries.AddGlobalStats(globalStats);
            queries.AddAllMatches(matches);

            dbCon.Close();


            Console.WriteLine("Finnished Loading Database");
            Console.ReadLine();
            // you can do what you need to here
        }
Exemplo n.º 11
0
        static public GlobalStats GetRanking(NetworkStream stream, string category)
        {
            string msg    = "{\"msg\":\"GimmeStats\",\"category\":\"" + category + "\"}";
            var    byData = Encoding.UTF8.GetBytes(msg);
            var    bytes  = HeaderParser.Encode(Header.STR, Convert.ToUInt32(byData.Length));

            stream.Write(bytes, 0, bytes.Length);
            try
            {
                stream.Write(byData, 0, byData.Length);
            }
            catch (System.IO.IOException e) { }

            var buffer      = new byte[3];
            int messageSize = stream.Read(buffer, 0, 3);
            var head        = HeaderParser.Decode(buffer);
            var buffer2     = new byte[head.Item2];

            stream.Read(buffer2, 0, buffer2.Length);
            string receive = Encoding.UTF8.GetString(buffer2);
            //string[] jsonified = new string[9];
            GlobalStats globalStats = JsonSerializer.Deserialize <GlobalStats>(receive);

            if (head.Item1 == Header.STA)
            {
                return(globalStats);
            }
            else
            {
                return(new GlobalStats());
            }
        }
Exemplo n.º 12
0
        public void ProcessUpcomingFixtures()
        {
            // Arrange
            configManagerMock.Setup(p => p.GetBetStyle()).Returns("1");
            configManagerMock.Setup(p => p.GetUseExpanded()).Returns(false);
            configManagerMock.Setup(p => p.GetMaxOdds()).Returns(10);
            configManagerMock.Setup(p => p.GetMinOdds()).Returns(1);
            configManagerMock.Setup(p => p.GetDrawMargin()).Returns(10);
            configManagerMock.Setup(p => p.GetDrawMixedMargin()).Returns(20);
            configManagerMock.Setup(p => p.GetMinMetricCorrect()).Returns(1);
            configManagerMock.Setup(p => p.GetMatchDay()).Returns(3);
            configManagerMock.Setup(p => p.GetReverseDays()).Returns(4);

            MetricConfig metricConfigLastGames = new MetricConfig
            {
                name  = "LastGamesMetric",
                depth = 1
            };

            List <MetricConfig> configs = new List <MetricConfig>
            {
                metricConfigLastGames
            };

            // Act
            GlobalStats globalStats = new GlobalStats(configs, configManagerMock.Object, fixtureRetrieverMock.Object, logger);

            globalStats.ProcessUpcomingFixtures(out double expectedProfit);

            // Assert
            Assert.AreEqual(expectedProfit, (commonOdds["1"] - 1)
                            + (commonOdds["2"] - 1));
        }
Exemplo n.º 13
0
 private void ListToolStripMenuItem_Click(object sender, EventArgs e)
 {
     using (GlobalStats globalStatsForm = new GlobalStats(_loginUser))
     {
         globalStatsForm.ShowDialog(this);
     }
 }
Exemplo n.º 14
0
        private void RenderUsageStats(GlobalStats inStats)
        {
            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("RUNNING/", GUILayout.Width(FIELD_NAME_WIDTH));
                EditorGUILayout.LabelField(inStats.Running.ToString());
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("MAX/", GUILayout.Width(FIELD_NAME_WIDTH));
                EditorGUILayout.LabelField(inStats.Max.ToString());
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("CAPACITY/", GUILayout.Width(FIELD_NAME_WIDTH));
                EditorGUILayout.LabelField(inStats.Capacity.ToString());
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("AVG_TIME/", GUILayout.Width(FIELD_NAME_WIDTH));
                EditorGUILayout.LabelField(inStats.AvgMillisecs.ToString("00.000") + "ms");
            }
            EditorGUILayout.EndHorizontal();
        }
Exemplo n.º 15
0
    // Use this for initialization
    void Start()
    {
        globalStats = FindObjectOfType <GlobalStats>();
        if (globalStats == null)
        {
            globalStats = new GameObject().AddComponent <GlobalStats>();
        }
        else
        {
            globalStats.loadStats(this);
        }

        CharSheet = GameObject.Find("CharacterSheet");
        Atk       = GameObject.Find("AddAtack").GetComponent <Button>();
        Def       = GameObject.Find("AddDef").GetComponent <Button>();
        Fcs       = GameObject.Find("AddFocus").GetComponent <Button>();
        Evs       = GameObject.Find("AddEvasion").GetComponent <Button>();
        HPPotion  = GameObject.Find("useHPPotion").GetComponent <Button>();

        Atk.onClick.AddListener(AddAtk);
        Def.onClick.AddListener(AddDef);
        Fcs.onClick.AddListener(AddHP);
        Evs.onClick.AddListener(AddEvs);
        HPPotion.onClick.AddListener(usePotion);

        charSheetController = FindObjectOfType <CharSheetController>();
    }
Exemplo n.º 16
0
        private void RenderUsageBar(GlobalStats inStats)
        {
            float barWidth = this.position.width - 40;

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(20);

            float remainingPercent = 1.0f;

            float runningPercent = (float)inStats.Running / inStats.Capacity;

            if (runningPercent > 0)
            {
                GUILayout.Box(inStats.Running.ToString(), m_Style_Running,
                              GUILayout.Width(barWidth * runningPercent), GUILayout.Height(BAR_HEIGHT));
                remainingPercent -= runningPercent;
            }

            float watermarkPercent = (float)inStats.Max / inStats.Capacity;

            if (watermarkPercent > runningPercent)
            {
                GUILayout.Box((inStats.Max).ToString(), m_Style_Watermark,
                              GUILayout.Width(barWidth * (watermarkPercent - runningPercent)), GUILayout.Height(BAR_HEIGHT));
                remainingPercent -= watermarkPercent - runningPercent;
            }

            if (remainingPercent > 0)
            {
                GUILayout.Box((inStats.Capacity).ToString(), m_Style_Capacity,
                              GUILayout.Width(barWidth * (remainingPercent)), GUILayout.Height(BAR_HEIGHT));
            }
            EditorGUILayout.EndHorizontal();
        }
Exemplo n.º 17
0
    // Считаем выигрышное золото
    private void CalcGold(float round_time)
    {
        float reward_time_bonus;

        // Считаем бонусную награду от времени победы
        if (round_time < 70)
        {
            reward_time_bonus = 0.5f; // 50% reward
        }
        else if (round_time > 70 && round_time < 80)
        {
            reward_time_bonus = 0.35f; // 35% reward
        }
        else if (round_time > 80 && round_time < 90)
        {
            reward_time_bonus = 0.20f; // 20% reward
        }
        else if (round_time > 90 && round_time < 100)
        {
            reward_time_bonus = 0.1f; // 10% reward
        }
        else
        {
            reward_time_bonus = 0;
        }

        // Финальная награда
        float reward = Random.Range(200, 500) * (1 + reward_time_bonus);

        // Записываем новое значение золота
        GlobalStats.AddGold((int)reward);
    }
Exemplo n.º 18
0
    // Если покупка завершена успешно
    public void OnPurchaseComplete(Product product)
    {
        switch (product.definition.id)
        {
        // Первый товар за 0.99$
        case "first_product":
            gold = 20000;
            gems = 10;
            break;

        // Второй товар за 1.99$
        case "second_product":
            gold = 40000;
            gems = 20;
            break;

        // Третий товар за 2.99$
        case "third_product":
            gold = 60000;
            gems = 30;
            break;
        }

        // Добавляем купленное золото
        GlobalStats.AddInstantGold(gold);

        // Добавляем купленные гемы
        GlobalStats.AddInstantGems(gems);

        // Обновляем текст на странице
        GetComponent <MenuGoldAndGemsInfo>().UpdateInfo();

        // Вызываем белый эффект
        fade_out.SetTrigger("activate");
    }
Exemplo n.º 19
0
 void Start()
 {
     maxHealth = GlobalStats.enemyHealth();
     health    = maxHealth;
     exp       = maxHealth / 7;
     damage    = GlobalStats.enemyDamage();
 }
Exemplo n.º 20
0
        // ###############################################################################################
        //  (GET) global stats
        internal async static Task <GlobalStats> GetGlobalStats()
        {
            String URL = "https://api.coingecko.com/api/v3/global";

            Uri                 uri          = new Uri(URL);
            HttpClient          httpClient   = new HttpClient();
            HttpResponseMessage httpResponse = new HttpResponseMessage();

            String response = "";

            try {
                httpResponse = await httpClient.GetAsync(uri);

                httpResponse.EnsureSuccessStatusCode();

                response = await httpResponse.Content.ReadAsStringAsync();

                var data = JToken.Parse(response);
                data = data["data"];

                GlobalStats g = new GlobalStats();
                g.ActiveCurrencies = data["active_cryptocurrencies"].ToString();
                g.BtcDominance     = Math.Round((double)data["market_cap_percentage"]["btc"], 2).ToString() + "%";
                g.TotalVolume      = ToKMB((double)(data["total_volume"][coin.ToLower()] ?? data["total_volume"]["usd"])) + coinSymbol;
                g.TotalMarketCap   = ToKMB((double)(data["total_market_cap"][coin.ToLower()] ?? data["total_market_cap"]["usd"])) + coinSymbol;
                return(g);
            } catch (Exception ex) {
                //await new MessageDialog(ex.Message).ShowAsync();
                return(new GlobalStats());
            }
        }
Exemplo n.º 21
0
    //Player clicks continue button to try it out!
    void ClickOnTryIt()
    {
        Debug.Log("Try it was clicked.");

        if (isLevelTheme)
        {
            Skins.randomTheme = false;
        }
        else
        {
            Skins.randomSkin = false;

            //Change the player skin if not randomizing
            GameObject.Find("Player").GetComponent <Snake>().ChangeSnakeSkin();
        }


        //Save game so skin is here for good.
        GlobalStats.Save();

        //Get rid of this screen.
        if (!isLevelTheme)
        {
            GlobalStats.hud.ChangeMenuMode(1);
            gameObject.SetActive(false);
        }


        SceneManager.LoadScene(0);
    }
Exemplo n.º 22
0
    // Проверяем можем ли открыть новый уровень и проверяем гемы
    private void CheckLevel(float round_time)
    {
        int
            current_lvl = GlobalData.GetInt("CurrentLevel"),
            max_lvl     = GlobalData.GetInt("MaxLevel"),
            gem_chance  = CheckGemsChance(round_time); // Записываем шанс выпадения гема

        // Открываем новый уровень
        if (current_lvl == max_lvl)
        {
            max_lvl++;
            GlobalData.SetInt("MaxLevel", max_lvl);
            GlobalData.SetInt("CurrentLevel", max_lvl);
        }

        // Даём гем только если пройденный уровень равен последним трём открытым
        if (current_lvl >= max_lvl - 3)
        {
            // Если гем выпал
            if (Random.Range(0, 99) < gem_chance)
            {
                GlobalStats.AddGems(1);
                gems_obj.SetActive(true); // Активируем текстуру с текстом полученных гемов

                txt_gems.text = GlobalTranslateSystem.TranslateStatsText("Gems received") + ":  1";
            }
        }
    }
Exemplo n.º 23
0
 void Awake()
 {
     instanceCount++;
     if (instanceCount > 1)
         return;
     instance = this;
 }
Exemplo n.º 24
0
    //Toggle control type
    public void ChangeControls()
    {
        GlobalStats.swipeControls = !GlobalStats.swipeControls;

        ChangeControlButtonText();

        GlobalStats.Save();
    }
Exemplo n.º 25
0
    public void DeleteScores()
    {
        GlobalStats.ResetScores();
        GlobalStats.Save();

        deletedData = true;
        ShowResult(2);
    }
Exemplo n.º 26
0
 /// <summary>
 ///     Create a client that connects to the SendGrid Web API
 /// </summary>
 /// <param name="apiKey">Your SendGrid API Key</param>
 /// <param name="baseUri">Base SendGrid API Uri</param>
 public Client(string apiKey, string baseUri = "https://api.sendgrid.com/")
 {
     _baseUri           = new Uri(baseUri);
     _apiKey            = apiKey;
     Version            = "Josh";//Assembly.GetExecutingAssembly().GetName().Version.ToString();
     ApiKeys            = new APIKeys(this);
     UnsubscribeGroups  = new UnsubscribeGroups(this);
     Suppressions       = new Suppressions(this);
     GlobalSuppressions = new GlobalSuppressions(this);
     GlobalStats        = new GlobalStats(this);
 }
Exemplo n.º 27
0
    public static void SaveGame(GlobalStats player)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string          path      = Application.persistentDataPath + "/mainSave.Save";
        FileStream      stream    = new FileStream(path, FileMode.Create);

        SaveData data = new SaveData(player);

        formatter.Serialize(stream, data);
        stream.Close();
    }
Exemplo n.º 28
0
    //Level up
    //Increase our level by one, calculate exp for next level
    //Add skill points
    void levelUp()
    {
        level++;
        updateExpToNext();
        levelUpStats();
        GlobalStats.leveled(level);

        weaponOneSkillPoints++;
        weaponTwoSkillPoints++;

        UI.updateLevelText();
    }
Exemplo n.º 29
0
 private void Initialize()
 {
     Version            = Assembly.GetExecutingAssembly().GetName().Version.ToString();
     ApiKeys            = new APIKeys(this);
     UnsubscribeGroups  = new UnsubscribeGroups(this);
     Suppressions       = new Suppressions(this);
     GlobalSuppressions = new GlobalSuppressions(this);
     GlobalStats        = new GlobalStats(this);
     Templates          = new Templates(this);
     Versions           = new Versions(this);
     Batches            = new Batches(this);
 }
Exemplo n.º 30
0
 private void Awake()
 {
     if (instance == null)
     {
         DontDestroyOnLoad(gameObject);
         instance = this;
     }
     else if (instance != this)
     {
         Destroy(gameObject);
     }
 }
Exemplo n.º 31
0
    private void SpawnPopup(HealthHaver dead)
    {
        Enemy enemy = dead.GetComponent <Enemy>();

        if (enemy == null || !enemy.enabled)
        {
            return;
        }
        ScorePopup myPopupPrefab = Instantiate(popupPrefab, dead.transform.position, quaternion.identity);

        myPopupPrefab.DisplayScore(enemy.Value * GlobalStats.DifficultyMultiplier(GlobalStats.instance.SelectedDifficulty));
        myPopupPrefab.DisplayCombo(comboerToRead.NumberAbsorbed);
    }
Exemplo n.º 32
0
        private GlobalStats ReadFromFile(string filePath)
        {
            XmlSerializer formatter = GetSerializer();
            GlobalStats loadedStats;
            try
            {
                using (FileStream readFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    loadedStats = (GlobalStats)formatter.Deserialize(readFileStream);
                }
            }
            catch (Exception)
            {
                loadedStats = new GlobalStats();
            }

            if (loadedStats.Scores == null)
                loadedStats.Scores = new Highscore();

            return loadedStats;
        }
Exemplo n.º 33
0
 // Use this for initialization
 void Start()
 {
     global = control.GetComponent<GlobalStats>();
 }
Exemplo n.º 34
0
 public StatsHandler()
 {
     _globalStats = ReadFromFile(_globalStatsPath);
     _dailyStats = new DailyStats();
     _sessionTimer = new Stopwatch();
 }