// Update is called once per frame
	void Update () {
		if (gameStats == null) {
			gameStats = FindObjectOfType<GameStats> ();
			heartScript.SetHearts (gameStats.GetHealth ());
			initPos = gameStats.GetInitialPosition ();
		}
	}
Example #2
0
    void Start()
    {
        m_LevelTraps = m_Level.GetComponentsInChildren<ITrap>();
        m_GameStats = GameObject.FindGameObjectWithTag(ConstValues.GAMESTATS_TAG).GetComponent<GameStats>();

        if (m_PlayerPrefab != null)
        {
            m_ActivePlayer = Instantiate(m_PlayerPrefab);
            RespawnPlayer();

            if (m_CameraController != null)
            {
                m_CameraController.SetTarget(m_ActivePlayer);
                PlayerController playerControl = m_ActivePlayer.GetComponent<PlayerController>();
                if (playerControl != null)
                {
                    playerControl.GameController = this;
                }
            }
        }

        if (m_AIController == null)
        {
            m_AIController = GetComponent<AIController>();
        }

        if (m_AIController != null)
        {
            m_AIController.GameController = this;

            m_AIController.SpawnCreature(AIType.FLOATY_FRED, ConstValues.FLOATY_FRED_MAX_COUNT);
            m_AIController.SpawnCreature(AIType.SUICIDE_SAM, ConstValues.SUICIDE_SAM_MAX_COUNT);
        }
    }
Example #3
0
 private void Awake()
 {
     Scene.ActiveMB = this;
     Scene.GameStats = this._gameStats;
     Scene.SceneTracker = this._sceneTracker;
     Scene.MutantControler = this._mutantControler;
     Scene.MutantSpawnManager = this._mutantSpawnManager;
     Scene.Yacht = this._yacht;
     Scene.PlaneCrash = this._plane;
     Scene.PlaneCrashAnimGO = this._planeCrashAnimGO;
     Scene.TriggerCutScene = this._triggerCutScene;
     Scene.RainFollowGO = this._rainFollowGO;
     Scene.RainTypes = this._rainTypes;
     Scene.WeatherSystem = this._weatherSystem;
     Scene.HudGui = this._hudGui;
     Scene.Cams = this._cams;
     Scene.Clock = this._clock;
     Scene.Atmosphere = this._atmos;
     Scene.WorkScheduler = this._workScheduler;
     Scene.LoadSave = this._loadSave;
     Scene.PlaneGreebles = this._planeGreebles;
     Scene.OceanFlat = this._oceanFlat;
     Scene.OceanCeto = this._oceanCeto;
     Scene.ShoreMask = this._shoreMask;
     Scene.SinkHoleCenter = this._sinkHoleCenter;
     Scene.CaveGrounds = this._caveGrounds;
 }
Example #4
0
    public BaseProject(int[] costs, int[] capacities, int[] buildingRounds, int[] requiredPoints, int[] requiredWhitehouse,
        string projectName, GameStats stats, string pType, BaseProject[] dependence = null, int[] extraPointsList = null, int[] discounts = null, int[] builder = null, int newProjectLevel = 0)
    {
        _costs                = costs;
         _capacities           = capacities;
         _buildingRounds       = buildingRounds;
         _requiredPoints       = requiredPoints;
         _requiredWhitehouse   = requiredWhitehouse;

        if(discounts != null)
        {
            _discounts = discounts;
        }

        if (builder != null)
        {
            _builder = builder;
        }

        if (extraPointsList != null)
        {
            _extraPointsList = extraPointsList;
        }

        projectType = pType;
        gameStats = stats;
        _projectName = projectName;
        _dependence = dependence;

        projectLevel = newProjectLevel;
    }
Example #5
0
	// Update is called once per frame
	void Update () {
		if (gameStats == null) {
			gameStats = FindObjectOfType<GameStats> ();
			transform.position = gameStats.GetInitialPosition ();
		}

	}
Example #6
0
 void Start()
 {
     if (m_GameStats == null)
     {
         m_GameStats = GameObject.Find(ConstValues.GAMESTATS_TAG).GetComponent<GameStats>();
     }
 }
Example #7
0
    public static void resetReferencesForNewLevel()
    {
        // Managers
        manager = GameObject.FindGameObjectWithTag("Manager");
        stateManager = manager.GetComponent<StateManager>();
        stateTiming = manager.GetComponent<StateTiming>();

        // Game stats and information
        gameStats = manager.GetComponent<GameStats>();
        itemDatabase = manager.GetComponent<Item_Database>();
        inventory = manager.GetComponent<Inventory>();
        market = manager.GetComponent<Market>();
        marketArrays = manager.GetComponent<MarketArrays>();
        soundEffects = GameObject.FindObjectOfType<SoundEffectsDatabase>().GetComponent<SoundEffectsDatabase>();

        // Cameras
        realtimeCamera = GameObject.FindGameObjectWithTag("Camera_Realtime").GetComponent<Camera>();
        strategicCamera = GameObject.FindGameObjectWithTag("Camera_Strategic").GetComponent<Camera>();

        // Game entities
        player = GameObject.FindGameObjectWithTag("Player");
        castle = GameObject.FindGameObjectWithTag("Castle");
        soundEffect = (GameObject)Resources.Load("OneTimeSoundEffect", typeof(GameObject));

        // Data
        lastLevelIndex = Application.loadedLevel;
        currentLevel = 1;
    }
Example #8
0
	// Use this for initialization
	void Start () {
		gameStats = FindObjectOfType<GameStats> ();

		if (gameStats.GetRoomList() != null && gameStats.GetRoomList().Count != 0) {
			gameStats.currentRoom.roomNo = gameStats.GetCurrentRoomNo();
			gameStats.SetRoom (gameStats.currentRoom, gameStats.currentRoom.roomNo);
		}

	}
Example #9
0
	private void Awake() {
		if (instance == null) {
			instance = this;
			DontDestroyOnLoad(gameObject);
		}
		else {
			Destroy(gameObject);
		}
	}
Example #10
0
 void Start()
 {
     m_StatText = GetComponent<Text>();
     m_GameStats = GameObject.FindGameObjectWithTag("GameStats").GetComponent<GameStats>();
     if (m_GameStats == null)
     {
         Debug.Log("GameStats is NULL!");
     }
     m_GameStats.ReadStatistics();
 }
Example #11
0
        public bool PlaceMarkAndCheckWinner(Board board, int[] tempPos, bool tempFirst)
        {
            int DIM = board.GetDIM();
            tempBoard = new Board(DIM);
            tempBoard.SetBoard(board.Copy());
            tempBoard.SetCell(tempPos, tempFirst);

            GameStats gameStats = new GameStats();
            return gameStats.IsWinner(tempBoard, tempFirst);
        }
Example #12
0
    // Initialisiert alle Variablen
    void Init()
    {
        gameController = GameObject.FindGameObjectWithTag(Tags.gameController);
        gameStats = gameController.GetComponent<GameStats>();
        playerMovement = GetComponent<Player_Movement>();

        EventPositionsList = new Dictionary<int, Vector3>();
        EventDistancesList = new Dictionary<int, float>();
        EventCount = 0;
        SetupLineRenderer();
    }
Example #13
0
 void Start()
 {
     stateManager = GetComponent<StateManager> ();
     adMnan = GetComponent<AdMan> ();
     gameStats = GetComponent<GameStats> ();
     menuManager = GetComponent<MenuManager> ();
     lanePlacer = GameObject.Find ("PROCEDURAL").GetComponent<LanePlacer> ();
     gameCamera = Camera.main.GetComponent<GameCamera> ();
     //		if(isFirstGame){
     //			menuManager.SwitchMenu(MenuManager.MenuTypes.PreGame);
     //		}
 }
Example #14
0
    void Awake()
    {
        DontDestroyOnLoad(this);

        if(gameStats == null)
        {
            DontDestroyOnLoad(gameObject);
            gameStats = this;
        }else if(gameStats != null)
        {
            Destroy(gameObject);
        }
    }
Example #15
0
    public string[] GetPermutation(int days, List<BaseProject> projects, GameStats game)
    {
        List<string> output = new List<string>();
        List<int> allPoints = new List<int>();

        LinkedList<Day> linkedDays = new LinkedList<Day>();

        GetPermutationPerRef(days, projects, output, allPoints, game, linkedDays);

        _allPoints = allPoints;

        return output.ToArray();
    }
Example #16
0
    void Start()
    {
        m_GameManager = GameObject.Find("GameManager").GetComponent<GameController>();
        m_GameStats = GameObject.FindGameObjectWithTag("GameStats").GetComponent<GameStats>();

        if (m_GameManager == null ||
            m_GameStats == null ||
            m_DeathCounterText == null ||
            m_LevelText == null ||
            m_TimerText == null)
        {
            Debug.LogWarning("Something is NULL");
        }
    }
Example #17
0
    // Use this for initialization
    void Start()
    {
        //Find out info about the world
        gameStats = GameObject.FindGameObjectWithTag("Properties").GetComponent<GameStats>();
        difficulty = gameStats.difficulty;
        player = GameObject.FindGameObjectWithTag("Player");

        //If we have a display to show where the fire will be.
        if (useIndicator)
        {
            burnIndicator = transform.FindChild("BurnIndicator").gameObject;
        }
        runner = player.GetComponent<Cryomancer>();
        stats = player.GetComponent<PlayerStats>();
        fire.SetActive(true);
    }
Example #18
0
    // Initialisiert alle Variablen
    void Init()
    {
        gameController = GameObject.FindGameObjectWithTag(Tags.gameController);
        gameStats = gameController.GetComponent<GameStats>();

        eventID = -1;

        source = GetComponent<AudioSource>();
        soundDistance = initialSoundDistance;
        source.maxDistance = soundDistance;
        nav = GetComponent<NavMeshAgent>();
        player = GameObject.FindGameObjectWithTag(Tags.player);
        playerMovement = player.GetComponent<Player_Movement>();
        ProtagonistSVISystem = player.GetComponent<SVI_I>();

        directDistanceFromPlayer = 0f;
        currentStatus = EventStatus.inactive;
    }
    // Use this for initialization
    void Start()
    {
        gameStats = GameObject.FindGameObjectWithTag("Properties").GetComponent<GameStats>();
        difficulty = gameStats.difficulty;
        player = GameObject.FindGameObjectWithTag("Player");
        if (player.GetComponent<PlayerStats>() != null)
        {
            stats = player.GetComponent<PlayerStats>();
        }
        else
        {
            player.AddComponent<PlayerStats>();
        }

        if (player.GetComponent<TeleTarget>() == null)
        {
            player.AddComponent<TeleTarget>();
        }
        startPos = player.transform.position;
        startRot = player.transform.rotation;
    }
Example #20
0
 private void OpenGameDetails(GameStats selected)
 {
     if (selected == null)
     {
         return;
     }
     if (selected.HasReplayFile && !Keyboard.IsKeyDown(Key.LeftCtrl))            //hold ctrl to open old game viewer
     {
         ReplayReader.LaunchReplayViewer(selected.ReplayFile);
     }
     else if (Config.Instance.StatsInWindow)
     {
         Core.Windows.StatsWindow.GameDetailsFlyout.SetGame(selected);
         Core.Windows.StatsWindow.FlyoutGameDetails.Header = selected.ToString();
         Core.Windows.StatsWindow.FlyoutGameDetails.IsOpen = true;
     }
     else
     {
         Core.MainWindow.GameDetailsFlyout.SetGame(selected);
         Core.MainWindow.FlyoutGameDetails.Header = selected.ToString();
         Core.MainWindow.FlyoutGameDetails.IsOpen = true;
     }
 }
Example #21
0
    private void BuildTheLevel()
    {
        PlayerControl.Instance.MoveForceKoef = 1f;
        SetHpFromLevel();
        SetEnemyHpFromLevel();
        ClearObjHashSets();
        ControlConstantGameObjs();

        maxCountOfMoneyPoint = currLevel.maxMoneyInGame;

        if (!isFreeRun)
        {
            GameStats.SetСurrency();
            uI_Control.ShowDescribePanel(currLevel.description);
        }

        uI_Control.RenewMoneyUI();

        uI_Control.RenewtHealthUI();

        InputParams.hitButton = true;
        soundControl.Win();
    }
Example #22
0
 public GameResultNotificationWindow(string deckName, [NotNull] GameStats game)
 {
     InitializeComponent();
     DeckName = deckName;
     _game    = game;
     ComboBoxOpponentClass.ItemsSource = Enum.GetValues(typeof(HeroClass)).Cast <HeroClass>().Select(x => new HeroClassWrapper(x));
     ComboBoxResult.ItemsSource        = new[] { GameResult.Win, GameResult.Loss };
     ComboBoxGameMode.ItemsSource      = new[]
     {
         GameMode.Arena,
         GameMode.Brawl,
         GameMode.Casual,
         GameMode.Friendly,
         GameMode.Practice,
         GameMode.Ranked,
         GameMode.Spectator
     };
     UpdatePosition();
     _startUpTime = DateTime.UtcNow;
     CloseAsync();
     Logger.WriteLine("Now showing", "GameResultNotification");
     Activate();
 }
Example #23
0
    private void LoadGameStats()
    {
        if (GameStats.LoadLevelSettings == true)
        {
            // load Level Settings

            int currentLevel = GameStats.Level;

            GameStats.UpdateLevelSettings(currentLevel);

            levelManager.WorldWidth  = GameStats.LvlWorldWidht;
            levelManager.WorldHeight = GameStats.LvlWorldHeight;
            levelManager.IsleDensity = GameStats.LvlIsleDensity;
        }

        if (GameStats.LoadCharStats == true)
        {
            // load Player Stats

            Player player = playerObject.GetComponent <Player>();
            GameStats.ReadCharStats(player);
        }
    }
Example #24
0
    public void SaveLevelData(GameStats newStat)
    {
        //SET SAVE
        LevelsStats totalStats = GetStatsFromJSON();

        //If there is no entries in the json create a new LevelStats

        if (totalStats == null)
        {
            totalStats = new LevelsStats();
            totalStats.Levels_Stats.Add(newStat);
        }
        //If there is entries in the json check whether the new entry is already added
        else
        {
            //GameStats copyStats = totalStats.GetStatsByLevelname(newStat.levelName);
            GameStats existingStats = totalStats.GetStats(newStat.levelName, newStat.difficulty);

            //if stats already stored just update the field :
            if (existingStats != null)
            {
                if (newStat.playerTime < existingStats.playerTime)
                {
                    existingStats.playerTime = newStat.playerTime;
                }
            }
            else
            {
                totalStats.Levels_Stats.Add(newStat);
            }
        }


        string statsText = JsonUtility.ToJson(totalStats);

        System.IO.File.WriteAllText(Application.persistentDataPath + "/LevelsStats.json", statsText);
    }
Example #25
0
        public void Reset(bool resetStats = true)
        {
            Log.Info("-------- Reset ---------");

            Player.Reset();
            Opponent.Reset();
            if (!_matchInfoCacheInvalid && MatchInfo?.LocalPlayer != null && MatchInfo.OpposingPlayer != null)
            {
                UpdatePlayers();
            }
            ProposedAttacker = 0;
            ProposedDefender = 0;
            Entities.Clear();
            SavedReplay = false;
            SecretsManager.Reset();
            SetupDone        = false;
            _spectator       = null;
            _currentGameMode = GameMode.None;
            _currentGameType = GameType.GT_UNKNOWN;
            _currentFormat   = FormatType.FT_UNKNOWN;
            if (!IsInMenu && resetStats)
            {
                CurrentGameStats = new GameStats(GameResult.None, "", "")
                {
                    PlayerName = "", OpponentName = "", Region = CurrentRegion
                }
            }
            ;
            PowerLog.Clear();
            LastKnownBattlegroundsBoardState.Clear();

            if (Core.Game != null && Core.Overlay != null)
            {
                Core.UpdatePlayerCards(true);
                Core.UpdateOpponentCards(true);
            }
        }
Example #26
0
        public void Reset(bool resetStats = true)
        {
            Log.Info("-------- Reset ---------");

            Player.Reset();
            Opponent.Reset();
            if (!_matchInfoCacheInvalid && MatchInfo?.LocalPlayer != null && MatchInfo.OpposingPlayer != null)
            {
                Player.Name   = MatchInfo.LocalPlayer.Name;
                Opponent.Name = MatchInfo.OpposingPlayer.Name;
                Player.Id     = MatchInfo.LocalPlayer.Id;
                Opponent.Id   = MatchInfo.OpposingPlayer.Id;
            }
            Entities.Clear();
            SavedReplay         = false;
            OpponentSecretCount = 0;
            OpponentSecrets.ClearSecrets();
            _spectator       = null;
            _currentGameMode = GameMode.None;
            _currentGameType = GameType.GT_UNKNOWN;
            _currentFormat   = FormatType.FT_UNKNOWN;
            if (!IsInMenu && resetStats)
            {
                CurrentGameStats = new GameStats(GameResult.None, "", "")
                {
                    PlayerName = "", OpponentName = "", Region = CurrentRegion
                }
            }
            ;
            PowerLog.Clear();

            if (Core.Game != null && Core.Overlay != null)
            {
                Core.UpdatePlayerCards(true);
                Core.UpdateOpponentCards(true);
            }
        }
        public void Reset(bool resetStats = true)
        {
            Logger.WriteLine("-------- Reset ---------", "Game");

            ReplayMaker.Reset();
            Player.Reset();
            Opponent.Reset();

            Entities.Clear();
            SavedReplay         = false;
            OpponentSecretCount = 0;
            OpponentSecrets.ClearSecrets();
            NoMatchingDeck = false;

            if (!IsInMenu && resetStats)
            {
                if (CurrentGameMode == GameMode.Ranked)
                {
                    Logger.WriteLine("Resetting gamemode to casual", "Game");
                    CurrentGameMode = GameMode.Casual;
                }
                CurrentGameStats = new GameStats(GameResult.None, "", "")
                {
                    PlayerName = "", OpponentName = "", Region = CurrentRegion
                };
                _gameModeDetectionComplete = false;
            }
            HSLogLines.Clear();
            PowerLog.Clear();

            if (Core.Game != null && Core.Overlay != null)
            {
                Helper.UpdatePlayerCards();
                Helper.UpdateOpponentCards();
                Core.MainWindow.NeedToIncorrectDeckMessage = false;
            }
        }
 private void BtnSave_OnClick(object sender, RoutedEventArgs e)
 {
     try
     {
         int duration;
         int.TryParse(TextBoxDuration.Text, out duration);
         int rank;
         int.TryParse(TextBoxRank.Text, out rank);
         int turns;
         int.TryParse(TextBoxTurns.Text, out turns);
         var gs = new GameStats
         {
             Result            = (GameResult)ComboBoxResult.SelectedItem,
             GameMode          = (GameMode)ComboBoxMode.SelectedItem,
             OpponentHero      = ComboBoxOpponent.SelectedValue.ToString(),
             StartTime         = DateTime.Now,
             GameId            = Guid.NewGuid(),
             Coin              = (YesNo)ComboBoxCoin.SelectedValue == YesNo.Yes,
             EndTime           = DateTime.Now.AddMinutes(duration),
             Rank              = rank,
             Note              = TextBoxNote.Text,
             OpponentName      = TextBoxOppName.Text,
             PlayerHero        = _deck.Class,
             Turns             = turns,
             WasConceded       = (YesNo)ComboBoxConceded.SelectedValue == YesNo.Yes,
             VerifiedHeroes    = true,
             Region            = (Region)ComboBoxRegion.SelectedItem,
             PlayerDeckVersion = _deck.SelectedVersion
         };
         _tcs.SetResult(gs);
     }
     catch (Exception ex)
     {
         Logger.WriteLine(ex.ToString(), "AddGameDialog");
         _tcs.SetResult(null);
     }
 }
Example #29
0
        public static double Benchmark(double[] X)
        {
            // create random coef run 10 times and get the win rate
            SetCoef(X);

            //todo: rename to Main
            GameConfig gameConfig = new GameConfig
            {
                StartPlayer      = 1,
                Player1HeroClass = CardClass.MAGE,
                Player2HeroClass = CardClass.MAGE,
                FillDecks        = true,
                Logging          = false,
            };

            //Console.WriteLine("Setup POGameHandler");
            AbstractAgent player1     = new FaceHunter();
            AbstractAgent player2     = new UCTHunter();
            var           gameHandler = new POGameHandler(gameConfig, player1, player2, debug: false);

            //Console.WriteLine("PlayGame");
            gameHandler.PlayGames(20);
            GameStats gameStats = gameHandler.getGameStats();

            gameStats.printResults();
            //Console.WriteLine("Setup gameConfig");

            double winRate = (double)gameStats.PlayerB_Wins / (double)gameStats.GamesPlayed;
            var    str     = new StringBuilder();

            Log.Instance("coef.txt").Append(FullPrintCoef(winRate));

            double expectedMin = 1;

            return(Math.Pow(winRate - expectedMin, 2));
        }
Example #30
0
    // Start is called before the first frame update
    void Start()
    {
        //transfer the game stats from the previous scene to our manager
        GameStats stats = FindObjectOfType <GameStats>();

        if (stats != null) //make sure we have a valid stats object
        {
            m_score   = stats.Score;
            m_gameWon = stats.GameWon;
            Destroy(stats.gameObject); //destroy the stats game object so we can make a new one if we play again


            if (m_gameWon) //if the player won
            {
                GameStatusText.text = "Congratulations You Win!!!";
            }
            else //player lost
            {
                GameStatusText.text = "GAME OVER!!!";
            }

            GameScoreText.text = "Your final score was: " + m_score.ToString();
        }
    }
Example #31
0
        protected override void OnAppearing()
        {
            string gameStatsPath = GetGameStatsPath();

            if (File.Exists((gameStatsPath)))
            {
                using (var reader = new StreamReader(gameStatsPath))
                {
                    string serializedGameStats = reader.ReadToEnd();
                    gameSettings = JsonConvert.DeserializeObject <GameStats>(serializedGameStats);
                    UpdateGameStats();
                }
            }

            else
            {
                gameSettings = new GameStats();
                UpdateGameStats();
            }


            computerChoice = MakeComputerChoice();
            base.OnAppearing();
        }
Example #32
0
        private async void EditGame(GameStats game)
        {
            if (game == null)
            {
                return;
            }

            var dialog = new AddGameDialog(game);
            await
            Helper.MainWindow.ShowMetroDialogAsync(dialog,
                                                   new MetroDialogSettings { AffirmativeButtonText = "save", NegativeButtonText = "cancel" });

            var result = await dialog.WaitForButtonPressAsync();

            await Helper.MainWindow.HideMetroDialogAsync(dialog);

            if (result == null)            //cancelled
            {
                return;
            }
            Refresh();
            if (Config.Instance.HearthStatsAutoUploadNewGames && HearthStatsAPI.IsLoggedIn)
            {
                var deck = DeckList.Instance.Decks.FirstOrDefault(d => d.DeckId == game.DeckId);
                if (game.GameMode == GameMode.Arena)
                {
                    HearthStatsManager.UpdateArenaMatchAsync(game, deck, true, true);
                }
                else
                {
                    HearthStatsManager.UpdateMatchAsync(game, _deck.GetVersion(game.PlayerDeckVersion), true, true);
                }
            }
            DeckStatsList.Save();
            Helper.MainWindow.DeckPickerList.UpdateDecks();
        }
Example #33
0
    /// <summary>
    /// Initializes a new instance of the <see cref="BuildingDrain"/> class.
    /// </summary>
    /// <param name='inStats'>
    /// In stats.
    /// </param>
    /// <param name='upORdown'>
    /// If true the building is going up in stats, if false the building is getting decreaed in stats. 
    /// </para>
    public BuildingDrain(GameStats  inStats, bool upORdown)
    {
        goingUp = upORdown;

        monthDestroyed = GameTime.CurrentMonth.ToString();

        myStats = new GameStats(inStats);

        numbertoSubtract = new GameStats(myStats);

        if (upORdown == true)
        {
            maxStats = new GameStats(myStats);
            myStats = new GameStats();
        }
        if (numbertoSubtract.Health !=0)
        numbertoSubtract.Health = (Math.Abs( numbertoSubtract.Health)) / numbertoDivide;
        if(numbertoSubtract.ProductionRate !=0)
        numbertoSubtract.ProductionRate = (Math.Abs( numbertoSubtract.ProductionRate)) / numbertoDivide;
        if(numbertoSubtract.Energy !=0)
        numbertoSubtract.Energy = (Math.Abs( numbertoSubtract.Energy)) / numbertoDivide;
        if(numbertoSubtract.Technology !=0)
        numbertoSubtract.Technology = (Math.Abs( numbertoSubtract.Technology)) / numbertoDivide;
    }
    public void Init(SlotInfo slotInfo, Vector2 position, int playerNumber)
    {
        GameStats stats = Persistent.PlayerStats[slotInfo.Index];

        rectTransform.localPosition = position;

        // Set up texts
        playerText.text   = $"Player {playerNumber}";
        killsText.text    = stats.TotalKills.ToString();
        deathsText.text   = stats.Deaths.ToString();
        damageText.text   = $"{stats.DamageDealt} : {stats.DamageTaken}";
        accuracyText.text = $"{stats.ShotsHit} / {stats.ShotsFired}";
        dashesText.text   = stats.DashesLaunched.ToString();

        // Set up image components
        backgroundImage.color = slotInfo.Color;
        indicatorImage.rectTransform.rotation = UIHelper.PlayerIndicatorRotation(slotInfo.Index);

        // Placing
        int placing = Persistent.PlayerPlacings().IndexOf(slotInfo.Index);

        medalText.text   = placingStrings[placing];
        medalImage.color = medalColors[placing];
    }
Example #35
0
    public Player(FightScene fightScene)
    {
        this.fightScene = fightScene;
        this.gameStats  = GameObject.FindGameObjectWithTag("GameStatsPersistor")
                          .GetComponent <GameStatsPersistor> ().GameStats;
        // init for Fight Scene
        this.Hitpoint.Val = this.fightScene.GameStats.Hitpoint;
        this.MaxHitpoint  = this.fightScene.GameStats.MaxHitpoint;
        this.Shield.Val   = 0;

        this.Hitpoint.OnChange += (oldVal, newVal) =>
        {
            if (newVal <= 0)
            {
                onDeath();
            }
        };

        this.playerObject   = GameObject.FindGameObjectsWithTag("Placeholder").Single(o => o.name == "Player");
        this.playerRenderer = playerObject.AddComponent <PlayerRenderer>();
        this.playerRenderer.Register(this);

        this.States = new StatesBar(playerObject);
    }
Example #36
0
        public async Task <GameWithStatsDTO> Handle(UpdateGameStatsCommand request, CancellationToken cancellationToken)
        {
            Game gm = await _context.Games.Where(ch => ch.GameId == request.Id).FirstOrDefaultAsync(cancellationToken: cancellationToken);

            GameStats gmStats          = gm.Stats;
            GameStats updatedGameStats = new GameStats
            {
                BombsTotalTeamOne           = request.BombsTotalTeamOne,
                BombsTotalTeamTwo           = request.BombsTotalTeamTwo,
                GrandTichuCallsTotalTeamOne = request.GrandTichuCallsTotalTeamOne,
                GrandTichuCallsTotalTeamTwo = request.GrandTichuCallsTotalTeamTwo,
                GrandTichuCallsWonTeamOne   = request.GrandTichuCallsWonTeamOne,
                GrandTichuCallsWonTeamTwo   = request.GrandTichuCallsWonTeamTwo,
                HighCardsTotalTeamOne       = request.HighCardsTotalTeamOne,
                HighCardsTotalTeamTwo       = request.HighCardsTotalTeamTwo,
                Rounds                 = request.Rounds.Select(rd => _mapper.Map <Round>(rd)).ToList(),
                RoundsTotal            = request.RoundsTotal,
                RoundsWonTeamOne       = request.RoundsWonTeamOne,
                RoundsWonTeamTwo       = request.RoundsWonTeamTwo,
                ScoreTeamOne           = request.ScoreTeamOne,
                ScoreTeamTwo           = request.ScoreTeamTwo,
                TichuCallsTotalTeamOne = request.TichuCallsTotalTeamOne,
                TichuCallsTotalTeamTwo = request.TichuCallsTotalTeamTwo,
                TichuCallsWonTeamOne   = request.TichuCallsWonTeamOne,
                TichuCallsWonTeamTwo   = request.TichuCallsWonTeamTwo,
                DateLastModified       = DateTime.Now,
                LastModifiedBy         = request.UserId,
                CreatedBy              = gmStats?.CreatedBy ?? request.UserId,
                DateCreated            = gmStats?.DateCreated ?? DateTime.Now,
                GameId                 = gm.GameId
            };

            await _context.SaveChangesAsync(cancellationToken);

            return(_mapper.Map <GameWithStatsDTO>(gm));
        }
        public static async Task <bool> ShowEditGameDialog(this MetroWindow window, GameStats game)
        {
            if (game == null)
            {
                return(false);
            }
            var dialog = new AddGameDialog(game);
            await window.ShowMetroDialogAsync(dialog, new MetroDialogSettings { AffirmativeButtonText = "save", NegativeButtonText = "cancel" });

            var result = await dialog.WaitForButtonPressAsync();

            await window.HideMetroDialogAsync(dialog);

            if (result == null)
            {
                return(false);
            }
            if (Config.Instance.HearthStatsAutoUploadNewGames && HearthStatsAPI.IsLoggedIn)
            {
                var deck = DeckList.Instance.Decks.FirstOrDefault(d => d.DeckId == game.DeckId);
                if (deck != null)
                {
                    if (game.GameMode == GameMode.Arena)
                    {
                        HearthStatsManager.UpdateArenaMatchAsync(game, deck, true, true);
                    }
                    else
                    {
                        HearthStatsManager.UpdateMatchAsync(game, deck.GetVersion(game.PlayerDeckVersion), true, true);
                    }
                }
            }
            DeckStatsList.Save();
            Core.MainWindow.DeckPickerList.UpdateDecks();
            return(true);
        }
Example #38
0
        public async Task <IActionResult> Edit(
            int id,
            [Bind("ID,MonsterKills,CollectedGold,DeathsNumber," +
                  "LostFights,WinFights,DrawFights,LootedNormal," +
                  "LootedUnique,LootedHeroic,LootedLegendary")]
            GameStats gameStats)
        {
            if (id != gameStats.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(gameStats);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!GameStatsExists(gameStats.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }

                return(RedirectToAction(nameof(Index)));
            }

            return(View(gameStats));
        }
Example #39
0
 public AddGameDialog(GameStats game) : this()
 {
     _editing = true;
     _game    = game;
     if (game == null)
     {
         return;
     }
     ComboBoxResult.SelectedItem = game.Result;
     if (!string.IsNullOrWhiteSpace(game.OpponentHero) && Enum.TryParse(game.OpponentHero, out HeroClass heroClass))
     {
         ComboBoxOpponent.SelectedItem = heroClass;
     }
     ComboBoxMode.SelectedItem   = game.GameMode;
     ComboBoxFormat.SelectedItem = game.Format;
     ComboBoxRegion.SelectedItem = game.Region;
     if (game.GameMode == Ranked)
     {
         TextBoxRank.Text       = game.Rank.ToString();
         TextBoxLegendRank.Text = game.LegendRank.ToString();
         TextBoxLeagueId.Text   = game.LeagueId.ToString();
         TextBoxStarLevel.Text  = game.StarLevel.ToString();
     }
     PanelRank.Visibility          = PanelLegendRank.Visibility = game.GameMode == Ranked ? Visible : Collapsed;
     PanelFormat.Visibility        = game.GameMode == Ranked || game.GameMode == Casual ? Visible : Collapsed;
     ComboBoxCoin.SelectedItem     = game.Coin ? Yes : No;
     ComboBoxConceded.SelectedItem = game.WasConceded ? Yes : No;
     TextBoxTurns.Text             = game.Turns.ToString();
     TextBoxDuration.Text          = game.Duration;
     TextBoxDuration.IsEnabled     = false;
     TextBoxNote.Text       = game.Note;
     TextBoxOppName.Text    = game.OpponentName;
     TextBoxPlayerName.Text = game.PlayerName;
     BtnSave.Content        = LocUtil.Get(LocSaveGame);
     Title = LocUtil.Get(LocEditTitle);
 }
Example #40
0
        public static void main_start(string s)
        {
            node_string = s;



            Console.WriteLine("Setup gameConfig");

            //todo: rename to Main
            GameConfig gameConfig = new GameConfig
            {
                StartPlayer      = 1,
                Player1HeroClass = CardClass.WARRIOR,                 // <- put your hero class here
                Player2HeroClass = CardClass.WARRIOR,
                Player1Deck      = Decks.AggroPirateWarrior,          // <- put your new deck here
                Player2Deck      = Decks.AggroPirateWarrior,
                FillDecks        = true,
                Logging          = false
            };


            Console.WriteLine("Setup POGameHandler");
            AbstractAgent player1     = new MyMCTS_Agent();
            AbstractAgent player2     = new gre();
            var           gameHandler = new POGameHandler(gameConfig, player1, player2, debug: true);

            Console.WriteLine("PlayGame");
            //gameHandler.PlayGame();
            gameHandler.PlayGames(totalgames);            //30模50場66%,20模50場74%,15模50場82%,15模擬1000場70%
            GameStats gameStats = gameHandler.getGameStats();

            gameStats.printResults();

            Console.WriteLine("Test successful");
            //Console.ReadLine();
        }
Example #41
0
        public static string SaveToDisk(GameStats gameStats, List <string> powerLog)
        {
            try
            {
                var fileName = $"{gameStats.PlayerName}({gameStats.PlayerHero}) vs "
                               + $"{gameStats.OpponentName}({gameStats.OpponentHero}) {DateTime.Now:HHmm-ddMMyy}";

                if (!Directory.Exists(Config.Instance.ReplayDir))
                {
                    Directory.CreateDirectory(Config.Instance.ReplayDir);
                }
                var path = Helper.GetValidFilePath(Config.Instance.ReplayDir, fileName, ".hdtreplay");
                using (var ms = new MemoryStream())
                {
                    using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
                    {
                        var hsLog = archive.CreateEntry("output_log.txt");
                        using (var logStream = hsLog.Open())
                            using (var swLog = new StreamWriter(logStream))
                                powerLog?.ForEach(swLog.WriteLine);
                    }

                    using (var fileStream = new FileStream(path, FileMode.Create))
                    {
                        ms.Seek(0, SeekOrigin.Begin);
                        ms.CopyTo(fileStream);
                    }
                }
                return(fileName + ".hdtreplay");
            }
            catch (Exception e)
            {
                Log.Error(e);
                return(null);
            }
        }
Example #42
0
    // flocking logic
    private void flockTasks()
    {
        if (GamePrefs.GetBool(EnumGamePrefs.DebugStopEnemiesMoving) || GameStats.GetInt(EnumGameStats.GameState) == 2)
        {
            return;
        }
        if (this.world.IsRemote())
        {
            return;
        }
        if (this.IsDead())
        {
            return;
        }
        if (masterEntity == null && !hasFlock && maxToSpawn > 0)
        {
            SpawnFlock();
        }
        else if (masterEntity == null && hasFlock && oldmasterID > 0)
        {
            FindOldMaster();
        }
        base.GetEntitySenses().ClearIfExpired();
        if (this.AttackTimeout > 0)
        {
            this.AttackTimeout--;
        }
        if (this.AttackTimeout <= 0)
        {
            Vector3 a            = this.Waypoint - this.position;
            float   sqrMagnitude = a.sqrMagnitude;
            if (sqrMagnitude < 1f || sqrMagnitude > 6400f)
            {
                if (!base.isWithinHomeDistanceCurrentPosition() && this.GetMasterEntity() == null && !isHunting)
                {
                    // uses vanilla code to stay near "home position" if its a "master"
                    Vector3 ye = RandomPositionGenerator.CalcTowards(this, 2 * base.getMaximumHomeDistance(), 2 * base.getMaximumHomeDistance(), 2 * base.getMaximumHomeDistance(), base.getHomePosition().position.ToVector3());
                    if (!ye.Equals(Vector3.zero))
                    {
                        if (debug)
                        {
                            Debug.Log("Going Home");
                        }
                        this.Waypoint    = ye;
                        this.HasWaypoint = true;
                    }
                }
                else
                {
                    this.HasWaypoint = false;
                    if (base.GetRevengeTarget() != null && ((base.GetRevengeTarget().GetDistanceSq(this) < 6400f && UnityEngine.Random.value <= 0.5f) || isHunting))
                    {
                        // if it's targeting an enemy. Notice that if it's hunting I just want it to get it done.
                        this.Waypoint = base.GetRevengeTarget().GetPosition() + Vector3.up;
                    }
                    else
                    {
                        if (this.GetMasterEntity() == null)
                        {
                            // if it finds a target block nearby, it will go for it. Not attack it, just go near it
                            // this will make them "destroy" crops for example, if we make them target crop blocks.
                            if (FindLandSpot())
                            {
                                // going for landing spot
                                this.Waypoint = landPosition + new Vector3((float)((this.rand.RandomDouble * 2.0 - 1.0) * 3.0), (float)((this.rand.RandomDouble * 2.0 - 1.0) * 3.0), (float)((this.rand.RandomDouble * 2.0 - 1.0) * 3.0));
                            }
                            else
                            {
                                // chooses a random waypoint - vanilla code
                                this.Waypoint = base.GetPosition() + new Vector3((float)((this.rand.RandomDouble * 2.0 - 1.0) * 16.0), (float)((this.rand.RandomDouble * 2.0 - 1.0) * 16.0), (float)((this.rand.RandomDouble * 2.0 - 1.0) * 16.0));
                                // maximum Y. Just to avoid them going too high (out of sight, out of heart)
                                int maxY = this.world.GetHeight((int)this.Waypoint.x, (int)this.Waypoint.z) + maxHeight;
                                if (this.Waypoint.y > maxY)
                                {
                                    this.Waypoint.y = maxY;
                                    if (debug)
                                    {
                                        Debug.Log("Prevented it from going higher");
                                    }
                                }
                            }
                        }
                        else
                        {
                            if ((this.GetMasterEntity() as EntityZombieFlockSDX).GetRevengeTarget() != null)
                            {
                                // attacks the same target as master
                                this.SetRevengeTarget((this.GetMasterEntity() as EntityZombieFlockSDX).GetRevengeTarget());
                                this.Waypoint = (this.GetMasterEntity() as EntityZombieFlockSDX).GetRevengeTarget().GetPosition() + Vector3.up;
                            }
                            else
                            {
                                // if the master has a landing spot, it goes to random position near the landing spot, otherwise just follows master
                                if ((this.GetMasterEntity() as EntityZombieFlockSDX).GetLandingSpot() == Vector3.zero)
                                {
                                    this.Waypoint = this.GetMasterEntity().GetPosition() + Vector3.up;
                                }
                                else
                                {
                                    this.Waypoint = (this.GetMasterEntity() as EntityZombieFlockSDX).GetLandingSpot() + new Vector3((float)((this.rand.RandomDouble * 2.0 - 1.0) * 3.0), (float)((this.rand.RandomDouble * 2.0 - 1.0) * 3.0), (float)((this.rand.RandomDouble * 2.0 - 1.0) * 3.0));
                                }
                            }
                        }
                    }
                    int num = 255;
                    // if waypoint is not in the air, change it up
                    while (this.world.GetBlock(new Vector3i(this.Waypoint)).type != BlockValue.Air.type && num > 0)
                    {
                        this.Waypoint.y = this.Waypoint.y + 1f;
                        num--;
                    }
                }
                this.Waypoint.y = Mathf.Min(this.Waypoint.y, 250f);
            }
            if (this.CourseCheck-- <= 0)
            {
                this.CourseCheck += this.rand.RandomRange(5) + 2;
                //if (base.isCourseTraversable(this.Waypoint, out sqrMagnitude))
                //{
                //    this.motion += a / sqrMagnitude * 0.1f;
                //}
                //else
                //{
                this.Waypoint = base.GetPosition();
                //}
            }
        }
        if (base.GetRevengeTarget() != null)
        {
            if (!retaliateAttack && !targetPlayers && !isHunting)
            {
                base.SetRevengeTarget(null);
            }
            else if (base.GetRevengeTarget().IsDead())
            {
                base.SetRevengeTarget(null);
                isHunting = false;
            }
        }
        // if it's a parent and has no target, then it will look for one.
        if ((base.GetRevengeTarget() == null) && this.GetMasterEntity() == null)
        {
            if (this.TargetInterval-- <= 0)
            {
                isHunting = false;
                if (targetPlayers)
                {
                    // if it's an agressive animal, will look for a player to attack
                    FindClosestPlayer();
                }
                if ((base.GetRevengeTarget() == null))
                {
                    if (naturalEnemies != null)
                    {
                        if (naturalEnemies.Length > 0)
                        {
                            // if it has natural enemies, will look for one to attack
                            FindNaturalEnemy();
                        }
                    }
                }
                if (base.GetRevengeTarget() != null)
                {
                    this.TargetInterval = 20;
                }
            }
        }
        float intendedRotation;

        if (!this.HasWaypoint)
        {
            if (base.GetRevengeTarget() != null)
            {
                float distanceSq;
                if ((distanceSq = base.GetRevengeTarget().GetDistanceSq(this)) < 6400f)
                {
                    float y = base.GetRevengeTarget().position.x - this.position.x;
                    float x = base.GetRevengeTarget().position.z - this.position.z;
                    if (distanceSq < 5f)
                    {
                        intendedRotation = Mathf.Atan2(y, x) * 180f / 3.14159274f;
                    }
                    else
                    {
                        intendedRotation = (float)Math.Atan2((double)this.motion.x, (double)this.motion.z) * 180f / 3.14159274f;
                        if (this.motion.magnitude < 0.25f)
                        {
                            this.motion = this.motion.normalized * 0.25f;
                        }
                    }
                    if (this.AttackTimeout <= 0)
                    {
                        if (distanceSq < 2.8f)
                        {
                            if (this.position.y >= base.GetRevengeTarget().position.y)
                            {
                                if (!isHunting)
                                {
                                    if (this.position.y <= base.GetRevengeTarget().getHeadPosition().y - 0.25f)
                                    {
                                        if (base.Attack(false))
                                        {
                                            this.AttackTimeout = base.GetAttackTimeoutTicks();
                                            base.Attack(true);
                                        }
                                    }
                                }
                                else
                                {
                                    // just marks the "target" to unload, as if it had captured it.
                                    if (UnityEngine.Random.value <= 0.5f)
                                    {
                                        if (debug)
                                        {
                                            Debug.Log("Eating the target!!!");
                                        }
                                        base.GetRevengeTarget().MarkToUnload();
                                        // stops hunting to look for another suitable target after a bit
                                        isHunting = false;
                                        base.SetRevengeTarget(null);
                                        this.TargetInterval = 50;
                                    }
                                }
                            }
                        }
                    }
                    this.rotation.y = EntityAlive.UpdateRotation(this.rotation.y, intendedRotation, 10f);
                    return;
                }
            }
        }
        intendedRotation = (float)Math.Atan2((double)this.motion.x, (double)this.motion.z) * 180f / 3.14159274f;
        this.rotation.y  = EntityAlive.UpdateRotation(this.rotation.y, intendedRotation, 10f);
    }
 // Use this for initialization
 void Start()
 {
     gameStats = GameObject.FindGameObjectWithTag("Properties").GetComponent<GameStats>();
     difficulty = gameStats.difficulty;
     counter = -3.0f;
     player = GameObject.FindGameObjectWithTag("Player");
 }
Example #44
0
    private void BrandNewDay(int day, LinkedListNode<Day> currentDay, GameStats game, LinkedList<Day> linkedDays)
    {
        if (currentDay != null)
        {
            // clears all constructions which who have been build after the previous buildpath ended
            game.ClearConstructing();
            // sets the projectlevels of that day
            game.whitehouse.projectLevel = currentDay.Value.WhitehouseLvl;
            game.cycletrack.projectLevel = currentDay.Value.CycletrackLvl;
            game.houses.projectLevel = currentDay.Value.HouseLvl;
            game.street.projectLevel = currentDay.Value.StreetLvl;
            game.carpool.projectLevel = currentDay.Value.CarpooltLvl;
            game.station.projectLevel = currentDay.Value.StationLvl;
            game.bus.projectLevel = currentDay.Value.BusLvl;
            game.train.projectLevel = currentDay.Value.TrainLvl;
            game.industry.projectLevel = currentDay.Value.IndustryLvl;

            // sets the income of that day
            game.coins = currentDay.Value.coins;
            game.points = currentDay.Value.points;
            game.citizen = currentDay.Value.citizen;
            game.capacity = currentDay.Value.capacity;
            game.environmentPoints = currentDay.Value.environmentPoints;

            // sets the industry values of that day
            game.maxBuilder = currentDay.Value.maxBuilder;
            game.builder = currentDay.Value.builder;
            game.discount = currentDay.Value.discount;

            // sets the constructiondays of the constructing projects of that day
            for (int i = 0; i < currentDay.Value.constructProjects.Count; i++)
            {
                foreach (BaseProject gbp in game.baseProjects)
                {
                    if (currentDay.Value.constructProjects.ContainsKey(gbp.projectName))
                    {
                        gbp.constructing = true;
                        gbp.constructionDays = currentDay.Value.constructProjects[gbp.projectName];
                    }
                }
            }

            // clear all the new days ahead
            while (currentDay != null)
            {
                var next = currentDay.Next;

                linkedDays.Remove(currentDay);
                currentDay = next;
            }

            // save the events of that day
            AddDaytoList(day, game, linkedDays);
        }
        else
        {
            // save the events of that day
            AddDaytoList(day, game, linkedDays);
        }
    }
Example #45
0
 protected void LegacyTask()
 {
     if (!GamePrefs.GetBool(EnumGamePrefs.DebugStopEnemiesMoving))
     {
         if (GameStats.GetInt(EnumGameStats.GameState) != 2)
         {
             base.GetEntitySenses().ClearIfExpired();
             if (this.MV > 0)
             {
                 this.MV--;
             }
             if (this.MV <= 0)
             {
                 Vector3 vector       = this.HV - this.position;
                 float   sqrMagnitude = vector.sqrMagnitude;
                 if (sqrMagnitude < 1f || sqrMagnitude > 2304f)
                 {
                     if (!base.isWithinHomeDistanceCurrentPosition())
                     {
                         Vector3 hv = RandomPositionGenerator.CalcTowards(this, 2 * base.getMaximumHomeDistance(), 2 * base.getMaximumHomeDistance(), 2 * base.getMaximumHomeDistance(), base.getHomePosition().position.ToVector3());
                         if (!hv.Equals(Vector3.zero))
                         {
                             this.HV = hv;
                             this.AV = true;
                         }
                     }
                     else
                     {
                         this.AV = false;
                         if (base.GetRevengeTarget() != null && base.GetRevengeTarget().GetDistanceSq(this) < 2304f && Random.value <= 0.5f)
                         {
                             this.HV = base.GetRevengeTarget().GetPosition() + Vector3.up;
                         }
                         else
                         {
                             this.HV = base.GetPosition() + new Vector3((float)((this.rand.NextDouble() * 2.0 - 1.0) * 16.0), (float)((this.rand.NextDouble() * 2.0 - 1.0) * 16.0), (float)((this.rand.NextDouble() * 2.0 - 1.0) * 16.0));
                         }
                     }
                     this.HV.y = Mathf.Min(this.HV.y, 250f);
                 }
                 if (this.LV-- <= 0)
                 {
                     this.LV += this.rand.Next(5) + 2;
                     if (this.isCourseTraversable(this.HV, out sqrMagnitude))
                     {
                         this.motion += vector / sqrMagnitude * 0.1f;
                     }
                     else
                     {
                         this.HV = base.GetPosition();
                     }
                 }
             }
             if (base.GetRevengeTarget() != null && base.GetRevengeTarget().IsDead())
             {
                 base.SetRevengeTarget(null);
             }
             if (base.GetRevengeTarget() == null || this.EV-- <= 0)
             {
                 EntityPlayer closestPlayer = this.world.GetClosestPlayer(this, 48f, false);
                 if (base.CanSee(closestPlayer))
                 {
                     base.SetRevengeTarget(closestPlayer);
                 }
                 if (base.GetRevengeTarget() != null)
                 {
                     this.EV = 20;
                 }
             }
             float distanceSq;
             if (!this.AV && base.GetRevengeTarget() != null && (distanceSq = base.GetRevengeTarget().GetDistanceSq(this)) < 2304f)
             {
                 float num  = base.GetRevengeTarget().position.x - this.position.x;
                 float num2 = base.GetRevengeTarget().position.z - this.position.z;
                 this.rotation.y = Mathf.Atan2(num, num2) * 180f / 3.14159274f;
                 if (this.MV <= 0 && distanceSq < 2.8f && this.position.y >= base.GetRevengeTarget().position.y&& this.position.y <= base.GetRevengeTarget().getHeadPosition().y&& base.Attack(false))
                 {
                     this.MV = base.GetAttackTimeoutTicks();
                     base.Attack(true);
                 }
             }
             else
             {
                 this.rotation.y = (float)Math.Atan2((double)this.motion.x, (double)this.motion.z) * 180f / 3.14159274f;
             }
             return;
         }
     }
 }
Example #46
0
    void Start()
    {
        m_GameStats = GameObject.FindGameObjectWithTag("GameStats").GetComponent<GameStats>();
        if (m_GameStats == null)
        {
            Debug.LogWarning("GameStats is null");
        }

        if (m_Animator == null)
        {
            m_Animator = GetComponent<Animator>();
        }

        if (m_Rigidbody == null)
        {
            m_Rigidbody = GetComponent<Rigidbody>();
        }

        m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
    }
Example #47
0
	void Awake () {
		Instance = this;
	}
Example #48
0
    private void AddDaytoList(int day, GameStats game, LinkedList<Day> linkedDays)
    {
        Day d = new Day();

        d.coins = game.coins;
        d.points = game.points;
        d.citizen = game.citizen;
        d.capacity = game.capacity;
        d.environmentPoints = game.environmentPoints;

        d.WhitehouseLvl = game.whitehouse.projectLevel;
        d.CycletrackLvl = game.cycletrack.projectLevel;
        d.HouseLvl = game.houses.projectLevel;
        d.StreetLvl = game.street.projectLevel;
        d.CarpooltLvl = game.carpool.projectLevel;
        d.StationLvl = game.station.projectLevel;
        d.BusLvl = game.bus.projectLevel;
        d.TrainLvl = game.train.projectLevel;
        d.IndustryLvl = game.industry.projectLevel;

        Dictionary<string, int> newBpList = new Dictionary<string, int>();

        foreach (BaseProject bp in game.baseProjects)
        {
            if (bp.constructing)
            {
                newBpList.Add(bp.projectName, bp.constructionDays);
            }
        }
        d.constructProjects = newBpList;

        d.discount = game.discount;
        d.maxBuilder = game.maxBuilder;
        d.builder = game.builder;

        d.day = day;
        linkedDays.AddLast(d);
    }
        public static async Task <PostResult> PostGameResultAsync(GameStats game, Deck deck)
        {
            if (!IsValidGame(game))
            {
                return(PostResult.Failed);
            }
            if (!deck.HasHearthStatsId)
            {
                Log.Warn("can not upload game, deck has no hearthstats id");
                return(PostResult.Failed);
            }
            long versionId;

            if (!long.TryParse(deck.HearthStatsDeckVersionId, out versionId))
            {
                Log.Error("invalid HearthStatsDeckVersionId");
                return(PostResult.Failed);
            }
            Log.Info("uploading match: " + game);
            var url = BaseUrl + "/matches?auth_token=" + _authToken;

            dynamic gameObj = new ExpandoObject();

            gameObj.mode            = game.GameMode.ToString();
            gameObj.@class          = string.IsNullOrEmpty(game.PlayerHero) ? deck.Class : game.PlayerHero;
            gameObj.result          = game.Result.ToString();
            gameObj.coin            = game.Coin.ToString().ToLower();
            gameObj.numturns        = game.Turns;
            gameObj.duration        = (int)(game.EndTime - game.StartTime).TotalSeconds;
            gameObj.deck_id         = deck.HearthStatsIdForUploading;
            gameObj.deck_version_id = versionId;
            if (!string.IsNullOrEmpty(game.OpponentHero))
            {
                gameObj.oppclass = game.OpponentHero;
            }
            if (!string.IsNullOrEmpty(game.OpponentName))
            {
                gameObj.oppname = game.OpponentName;
            }
            if (!string.IsNullOrEmpty(game.Note))
            {
                gameObj.notes = game.Note;
            }
            if (game.GameMode == GameMode.Ranked && game.HasRank)
            {
                gameObj.ranklvl = game.Rank.ToString();
            }
            var opponentCards = game.GetOpponentDeck().Cards;

            if (opponentCards.Where(Database.IsActualCard).Any())
            {
                gameObj.oppcards = opponentCards.Where(Database.IsActualCard).Select(c => new { id = c.Id, count = c.Count }).ToArray();
            }
            gameObj.created_at = game.StartTime.ToUniversalTime().ToString("s");

            var data = JsonConvert.SerializeObject(gameObj);

            try
            {
                var response = await PostAsync(url, data);

                var json = JsonConvert.DeserializeObject(response);
                if (json.status.ToString() == "200")
                {
                    game.HearthStatsId = json.data.id;
                    Log.Info("assigned id to match: " + game.HearthStatsId);
                    return(PostResult.WasSuccess);
                }
                if (json.status.ToString() == "fail" && json.message.ToString().Contains("Deck could not be found"))
                {
                    //deck does not exist on hearthstats
                    deck.ResetHearthstatsIds();
                    DeckList.Save();
                    deck.DeckStats.Games.ForEach(g => g.ResetHearthstatsIds());
                    DeckStatsList.Save();
                }
                return(PostResult.Failed);
            }
            catch (Exception e)
            {
                Log.Error(e);
                return(PostResult.Failed);
            }
        }
Example #50
0
        private bool VerifyHeroes(GameStats game)
        {
            // If its Brawl skip verification
            if (game.GameMode == GameMode.Brawl)
            {
                game.VerifiedHeroes = true;
                return(false);
            }

            var modifiedHero   = false;
            var playerHeroes   = new Dictionary <string, int>();
            var opponentHeroes = new Dictionary <string, int>();

            foreach (var turn in game.TurnStats)
            {
                foreach (var play in turn.Plays)
                {
                    if (string.IsNullOrEmpty(play.CardId))
                    {
                        continue;
                    }
                    if (play.Type.ToString().Contains("Player"))
                    {
                        var hero = Database.GetCardFromId(play.CardId).PlayerClass;
                        if (hero == null)
                        {
                            continue;
                        }
                        if (!playerHeroes.ContainsKey(hero))
                        {
                            playerHeroes.Add(hero, 0);
                        }
                        playerHeroes[hero]++;
                    }
                    else if (play.Type.ToString().Contains("Opponent"))
                    {
                        var hero = Database.GetCardFromId(play.CardId).PlayerClass;
                        if (hero == null)
                        {
                            continue;
                        }
                        if (!opponentHeroes.ContainsKey(hero))
                        {
                            opponentHeroes.Add(hero, 0);
                        }
                        opponentHeroes[hero]++;
                    }
                }
            }
            if (playerHeroes.Count > 0)
            {
                var pHero = playerHeroes.OrderByDescending(x => x.Value).First().Key;
                if (game.PlayerHero != pHero)
                {
                    game.PlayerHero = pHero;
                    modifiedHero    = true;
                }
            }
            if (opponentHeroes.Count > 0)
            {
                var oHero = opponentHeroes.OrderByDescending(x => x.Value).First().Key;
                if (game.OpponentHero != oHero)
                {
                    game.OpponentHero = oHero;
                    modifiedHero      = true;
                }
            }

            game.VerifiedHeroes = true;
            return(modifiedHero);
        }
        public static async Task <PostResult> MoveMatchAsync(GameStats game, Deck newDeck)
        {
            if (game == null)
            {
                Log.Error("game is null");
                return(PostResult.Failed);
            }
            if (!game.HasHearthStatsId)
            {
                Log.Error("game has no HearthStatsId");
                return(PostResult.Failed);
            }
            if (newDeck == null)
            {
                Log.Error("deck is null");
                return(PostResult.Failed);
            }
            if (!newDeck.HasHearthStatsId)
            {
                Log.Error("deck has no HearthStatsId");
                return(PostResult.Failed);
            }
            long deckId;

            if (!long.TryParse(newDeck.HearthStatsId, out deckId))
            {
                Log.Info("deck has invalid HearthStatsId");
                return(PostResult.Failed);
            }

            long gameId;

            if (!long.TryParse(game.HearthStatsId, out gameId))
            {
                Log.Error("error: game has invalid HearthStatsId");
                return(PostResult.Failed);
            }
            Log.Info("moving game: " + game);

            var url  = BaseUrl + "/matches/move?auth_token=" + _authToken;
            var data = JsonConvert.SerializeObject(new { match_id = new[] { gameId }, deck_id = deckId });

            try
            {
                var response = await PostAsync(url, data);

                dynamic json = JsonConvert.DeserializeObject(response);
                if (json.status.ToString() == "200")
                {
                    Log.Info("moved game");
                    return(PostResult.WasSuccess);
                }
                Log.Error(response);
                return(PostResult.Failed);
            }
            catch (Exception e)
            {
                Log.Error(e);
                return(PostResult.Failed);
            }
        }
Example #52
0
        protected void BaseConstructor(Framework framework, bool demoMode, Framework.MapData mapData)
        {
            game_Framework = framework;
            //Assigns the framework parameter to the variable.

            game_MediaPlayer = new MediaPlayer()
            {
                Volume = 0.1
            };
            game_TankMoveSoundUri      = new Uri(@"Resources/Tank Move sound effect.mp3", UriKind.Relative);
            game_TankFireSoundUri      = new Uri(@"Resources/Tank Fire sound effect.mp3", UriKind.Relative);
            game_ExplosionSoundUri     = new Uri(@"Resources/Explosion sound effect.mp3", UriKind.Relative);
            game_ClickForwardSoundUri  = new Uri(@"Resources/Click Forward sound effect.mp3", UriKind.Relative);
            game_ClickBackwardSoundUri = new Uri(@"Resources/Click Backward sound effect.mp3", UriKind.Relative);

            game_SkyTexture   = new BitmapImage(new Uri(@"Resources/Sky texture.png", UriKind.Relative));
            game_SteelTexture = new BitmapImage(new Uri(@"Resources/GUI texture.png", UriKind.Relative));
            //Selects the images for the two textures.

            game_MainCanvas = new Canvas()
            {
                Height     = 450,
                Width      = 1280,
                Background = new ImageBrush(game_SkyTexture)
            };
            game_GUICanvas = new Canvas()
            {
                Height     = 240,
                Width      = 1280,
                Background = new ImageBrush(game_SteelTexture)
                {
                    Viewport = new Rect(0, 0, 1d / 7.2, 1d / 1.35),
                    TileMode = TileMode.Tile
                }
            };
            //Instantiates the two Canvas objects, giving them heights
            //and widths, as well as applying their textures.

            game_Grid = new Grid()
            {
                Height = 690,
                Width  = 1280,
            };
            //Instantiates the Grid control that will encapsulate the two
            //Canvas objects.

            game_MainRow = new RowDefinition()
            {
                Height = new GridLength(450)
            };
            game_Grid.RowDefinitions.Add(game_MainRow);
            Grid.SetRow(game_MainCanvas, 0);
            game_Grid.Children.Add(game_MainCanvas);
            //Adds the game_MainCanvas to the Grid.

            game_GUIRow = new RowDefinition()
            {
                Height = new GridLength(240)
            };
            game_Grid.RowDefinitions.Add(game_GUIRow);
            Grid.SetRow(game_GUICanvas, 1);
            game_Grid.Children.Add(game_GUICanvas);
            //Adds the game_GUICanvas to the Grid.

            game_Map        = new Map(this, mapData);
            game_Projectile = new Shot(this);
            //Instantiates the game objects.

            game_MessageBox     = new MessageBox(this);
            game_AimingIcon     = new AimingIcon(this, 500, 115);
            game_FireButton     = new FireButton(this, 700, 85);
            game_WeaponSelector = new WeaponSelector(this, 700, 10);
            //Instantiates the GUI objects.

            game_LeftBoundary  = 0;
            game_RightBoundary = 1280;
            //Sets the boundaries for the Tank and Projectile objects.

            game_NewTurn             = true;
            game_Gravity             = 10;
            game_Turn                = 1;
            game_ProjectileDetonated = false;
            game_TurnDamage          = 0;
            //Sets the gravity, turn counter and NewTurn bool.

            game_Stats = new GameStats();
            game_Stats.player1Username = "******";
            game_Stats.player2Username = "******";

            game_MapData = mapData;

            game_NextMinX       = 100;
            game_NextMaxX       = 500;
            game_AngleDirection = true;
            GenerateRandomXLoc();
            if (demoMode)
            {
                ToggleDemoMode();
            }
            //Assigns the demo mode variables to their defaults and
            //activates the demo mode.

            game_Framework.GetFramework_Window().KeyDown += EscKeyPress;

            game_MessageBox.StartGameMessage(demoMode);
        }
Example #53
0
    // flocking logic
    private void flockTasks()
    {
        if (GamePrefs.GetBool(EnumGamePrefs.DebugStopEnemiesMoving) ||
            GameStats.GetInt(EnumGameStats.GameState) == 2)
        {
            return;
        }
        if (world.IsRemote())
        {
            return;
        }
        if (IsDead())
        {
            return;
        }
        if (masterEntity == null && !hasFlock && maxToSpawn > 0)
        {
            SpawnFlock();
        }
        else if (masterEntity == null && hasFlock && oldmasterID > 0)
        {
            FindOldMaster();
        }
        GetEntitySenses().ClearIfExpired();
        if (AttackTimeout > 0)
        {
            AttackTimeout--;
        }
        if (AttackTimeout <= 0)
        {
            var a            = Waypoint - position;
            var sqrMagnitude = a.sqrMagnitude;
            if (sqrMagnitude < 1f || sqrMagnitude > 6400f)
            {
                if (!isWithinHomeDistanceCurrentPosition() && GetMasterEntity() == null && !isHunting)
                {
                    // uses vanilla code to stay near "home position" if its a "master"
                    Vector3 ye = RandomPositionGenerator.CalcTowards(this, 2 * base.getMaximumHomeDistance(), 2 * base.getMaximumHomeDistance(), 2 * base.getMaximumHomeDistance(), base.getHomePosition().position.ToVector3());

                    if (!ye.Equals(Vector3.zero))
                    {
                        // going home
                        Waypoint    = ye;
                        HasWaypoint = true;
                    }
                }
                else
                {
                    HasWaypoint = false;


                    if (!HasWaypoint)
                    {
                        if (base.GetRevengeTarget() != null &&
                            (base.GetRevengeTarget().GetDistanceSq(this) < 6400f && Random.value <= 0.5f || isHunting))
                        {
                            // if it's targeting an enemy. Notice that if it's hunting I just want it to get it done.
                            Waypoint = base.GetRevengeTarget().GetPosition() + Vector3.up;
                        }
                        else
                        {
                            if (GetMasterEntity() == null)
                            {
                                // if it finds a target block nearby, it will go for it. Not attack it, just go near it
                                // this will make them "destroy" crops for example, if we make them target crop blocks.
                                if (FindLandSpot())
                                {
                                    // going for landing spot
                                    Waypoint = landPosition +
                                               new Vector3((float)((rand.NextDouble() * 2.0 - 1.0) * 3.0),
                                                           (float)((rand.NextDouble() * 2.0 - 1.0) * 3.0),
                                                           (float)((rand.NextDouble() * 2.0 - 1.0) * 3.0));
                                }
                                else
                                {
                                    // chooses a random waypoint - vanilla code
                                    Waypoint = GetPosition() +
                                               new Vector3((float)((rand.NextDouble() * 2.0 - 1.0) * 16.0),
                                                           (float)((rand.NextDouble() * 2.0 - 1.0) * 16.0),
                                                           (float)((rand.NextDouble() * 2.0 - 1.0) * 16.0));
                                    // maximum Y. Just to avoid them going too high (out of sight, out of heart)
                                    var maxY = world.GetHeight((int)Waypoint.x, (int)Waypoint.z) + maxHeight;
                                    if (Waypoint.y > maxY)
                                    {
                                        Waypoint.y = maxY;
                                    }
                                }
                            }
                            else
                            {
                                // if the master has a landing spot, it goes to random position near the landing spot, otherwise just follows master
                                if ((GetMasterEntity() as EntityZombieFlyingSDX).GetLandingSpot() == Vector3.zero)
                                {
                                    Waypoint = GetMasterEntity().GetPosition() + Vector3.up;
                                }
                                else
                                {
                                    Waypoint = (GetMasterEntity() as EntityZombieFlyingSDX).GetLandingSpot() +
                                               new Vector3((float)((rand.NextDouble() * 2.0 - 1.0) * 3.0),
                                                           (float)((rand.NextDouble() * 2.0 - 1.0) * 3.0),
                                                           (float)((rand.NextDouble() * 2.0 - 1.0) * 3.0));
                                }
                                // }
                            }
                        }
                    }

                    var num = 255;

                    AdjustWayPoint();
                    // if waypoint is not in the air, change it up
                    //                    while (world.GetBlock(new Vector3i(Waypoint)).type != BlockValue.Air.type && num > 0)
                    //                  {
                    //                    Waypoint.y = Waypoint.y + 1f;
                    //                  num--;
                    //            }
                }

                Waypoint.y = Mathf.Min(Waypoint.y, 250f);
            }

            if (CourseCheck-- <= 0)
            {
                CourseCheck += rand.Next(5) + 2;
                if (isCourseTraversable(Waypoint, out sqrMagnitude))
                {
                    motion += a / sqrMagnitude * 0.1f;
                }
                else
                {
                    Waypoint = GetPosition();
                }
            }
        }



        float intendedRotation;

        intendedRotation = (float)Math.Atan2(motion.x, motion.z) * 180f / 3.14159274f;
        rotation.y       = UpdateRotation(rotation.y, intendedRotation, 10f);
    }
Example #54
0
	// Update is called once per frame
	void Update () {
		if(gameStats == null)
			gameStats = FindObjectOfType<GameStats> ();
	}
        //LocUtil.Get()}

        public static async Task <MessageDialogResult> ShowDeleteGameStatsMessage(this MetroWindow window, GameStats stats)
        => await window.ShowMessageAsync(LocUtil.Get(LocDeleteGameStatsTitle),
                                         stats + Environment.NewLine + Environment.NewLine + LocUtil.Get(LocDeleteGameStatsSure),
                                         AffirmativeAndNegative,
                                         new Settings
        {
            AffirmativeButtonText = LocUtil.Get(LocDeleteGameStatsButtonDelete),
            NegativeButtonText    = LocUtil.Get(LocDeleteGameStatsButtonCancel)
        });
Example #56
0
    public string[] StartUnitTest()
    {
        GameStats game = new GameStats();

        List<BaseProject> bplist = game.GetBuyAbleBaseProjects();

        return GetPermutation(maxDays, bplist, game);
    }
Example #57
0
 public async Task PostGame(GameStats game)
 {
     _context.GameStats.Add(game);
     await _context.SaveChangesAsync();
 }
Example #58
0
    void Start()
    {
        gameManager = GetComponent<GameManager> ();
        stateManager = GetComponent<StateManager>();
        shopManager = GetComponent<ShopManager> ();
        gameStats = GetComponent<GameStats> ();
        //canvases:
        VloadCanvas = GameObject.Find ("VloadCanvas").GetComponent<Canvas> ();
        VpreGameCanvas = GameObject.Find ("VpreGameCanvas").GetComponent<Canvas> ();
        VpostGameCanvas = GameObject.Find ("VpostGameCanvas").GetComponent<Canvas> ();
        HloadCanvas = GameObject.Find ("HloadCanvas").GetComponent<Canvas> ();
        HpreGameCanvas = GameObject.Find ("HpreGameCanvas").GetComponent<Canvas> ();
        HpostGameCanvas = GameObject.Find ("HpostGameCanvas").GetComponent<Canvas> ();

        VtouchHand01 = VpreGameCanvas.transform.FindChild("TouchHand01").GetComponent<Image> ();
        HtouchHand01 = HpreGameCanvas.transform.FindChild("TouchHand01").GetComponent<Image> ();
        VtouchHand02 = VpreGameCanvas.transform.FindChild("TouchHand02").GetComponent<Image> ();
        HtouchHand02 = HpreGameCanvas.transform.FindChild("TouchHand02").GetComponent<Image> ();
        VtouchHand01.enabled = false;
        HtouchHand01.enabled = false;
        currentMenu = MenuTypes.PreGame;
        //---
        if(Input.deviceOrientation == DeviceOrientation.Portrait){
            SwitchOrientation(CanvasTypes.Port, true);
        }
        if (Input.deviceOrientation == DeviceOrientation.LandscapeRight) {
            SwitchOrientation(CanvasTypes.Land, true);
        }
    }
Example #59
0
    /// <summary>
    /// Generiert ein Array, aus Elementen die jeweils aus 'chars' unterschiedlichen Zeichen bestehen, mit jeweils 'places' Stellen.
    /// Das Array beinhaltet alle möglichen Verknüpfungsmöglichkeiten, die durch Permutation ermittelt werden.
    /// Das Ergebnis wird in der als Referenz übergebenen ArrayList 'output' gespeichert.
    /// </summary>
    /// <param name="days">Count of how many days the player would have time to build</param>
    /// <param name="projects">List of the available projects</param>
    /// <param name="output">List in which all the buildpathes will be stored</param>
    /// <param name="allPoints">List in which all the points of each buildpath will be stored</param>
    /// <param name="game">Game holds all the values to provide a environment where project can be build</param>
    /// <param name="outputPart" >Internally parameter to pass on the information during the recursiv progress</param>
    private void GetPermutationPerRef(int days, List<BaseProject> projects, List<string> output, List<int> allPoints, GameStats game, LinkedList<Day> linkedDays, string outputPart = "")
    {
        if (days == 0)
        {
            // If all the days are through,
            // the buildpath is added to a List of buildpathes
            // and the score of that buildpath is added to the scorelist
            AddDaytoList(days, game, linkedDays);

            allPoints.Add(game.points);
            output.Add(outputPart);
            dayInfo.Add(linkedDays);
        }
        else
        {
            if (projects.Count > 0) // there are projects which can be build
            {
                // for each new baseproject there is a complete new buildpath
                foreach (BaseProject p in projects)
                {
                    // because the days are getting counted down every new buildpath starts with the maximum count of days
                    // the game environment gets reset as do the linkedlist of days
                    if (days == maxDays)
                    {
                        game.Reset();
                        linkedDays.Clear();
                    }
                    // check if the day already exists
                    LinkedListNode<Day> currentDay = FindDay(days, linkedDays);

                    BrandNewDay(days, currentDay, game, linkedDays);

                    // the barriers prevent not promising buildpathes from being furhter pursued
                    // so that the numbers of possible buildpathes dont get out of hand
                    if (days == (maxDays - barrierer0) && game.points <= pointsBarrierer0)
                    {
                        // end of tail recursion
                    }
                    else if (days == (maxDays - barrierer1) && game.points <= pointsBarrierer1)
                    {
                        // end of tail recursion
                    }
                    else if (days == (maxDays - barrierer2) && game.points <= pointsBarrierer2)
                    {
                        // end of tail recursion
                    }
                    else if (days == (maxDays - barrierer3) && game.points <= pointsBarrierer3)
                    {
                        // end of tail recursion
                    }
                    else
                    {
                        // construct the current project
                        game.BuyProject(p);

                        // move on to the next day
                        game.nextDay();

                        // find all the projects the player could buy the next day
                        projects = game.GetBuyAbleBaseProjects();

                        // tail recursion
                        GetPermutationPerRef(days - 1, projects, output, allPoints, game, linkedDays, outputPart + p.projectName + " ");
                    }
                }
            }
            else // there are no projects which can be build
            {
                if (days == maxDays)
                {
                    game.Reset();
                    linkedDays.Clear();
                }

                if (days == (maxDays - barrierer0) && game.points <= pointsBarrierer0)
                {
                    // ende
                }
                else if (days == (maxDays - barrierer1) && game.points <= pointsBarrierer1)
                {
                    // ende
                }
                else if (days == (maxDays - barrierer2) && game.points <= pointsBarrierer2)
                {
                    // ende
                }
                else if (days == (maxDays - barrierer3) && game.points <= pointsBarrierer3)
                {
                    // ende
                }
                else
                {
                    // check if the day already exists
                    LinkedListNode<Day> currentDay = FindDay(days, linkedDays);
                    BrandNewDay(days, currentDay, game, linkedDays);

                    // dont buy or upgrade any project

                    game.nextDay();

                    projects = game.GetBuyAbleBaseProjects();

                    GetPermutationPerRef(days - 1,
                        projects,
                        output,
                        allPoints,
                        game,
                        linkedDays,
                        outputPart + "empty ");
                }
            }
        }
    }
Example #60
0
 /// <summary>
 /// makes it so that there is no draining and the stats are static. NOT TO BE USED anywere but when buildings are created at start. 
 /// </summary>
 internal void noDain()
 {
     this.myStats = this.maxStats;
 }