Example #1
0
 public void AllSeekPlayerGameInstance(GameInstance _gi, float seekTime)
 {
     if (OnSeekPlayerAIGameInstance != null)
     {
         OnSeekPlayerAIGameInstance(_gi, seekTime);
     }
 }
Example #2
0
 /// <summary>
 /// parents the audio source to the audiocontainer, moves the transform to the proper location, sets the clip and then plays the sound
 /// </summary>
 /// <param name="location">the transform of the object causing the sound</param>
 /// <param name="source">the audio source playing the sound</param>
 /// <param name="clip">the clip we will be playing</param>
 /// <param name="g">the game instance the object belongs to</param>
 public void OnSoundPlay(Transform location, AudioSource source, AudioClip clip, GameInstance g)
 {
     source.transform.SetParent(audioContainer);
     source.transform.position = new Vector3(mainCamera.ScreenToWorldPoint(g.gameCam.WorldToScreenPoint(location.position)).x, 0, 0);
     source.clip = clip;
     source.Play();
 }
Example #3
0
 public static void RaiseSoundPlay(Transform location, AudioSource source, AudioClip clip, GameInstance g)
 {
     if (SoundPlay != null)
     {
         SoundPlay(location, source, clip, g);
     }
 }
 public GameInstance CreateNewGameInstance(int gameID, int currentUserID)
 {
     Guid g = Guid.NewGuid();
     var gameInstance = new GameInstance {GameID = gameID, UserID = currentUserID, GameInstanceID = g.ToString()};
     _context.GameInstances.Add(gameInstance);
     return gameInstance;
 }
Example #5
0
 public StatusEffectControl(GameInstance owner, Action<StatusEffectEntity2> onAttach, Action<StatusEffectEntity2> onDetach)
 {
     this.objectHolder = owner;
     this.stat = owner.Stat;
     this.onAttach = onAttach;
     this.onDetach = onDetach;
 }
Example #6
0
    public void Init(Perception newPerception,  GameInstance newInstance)
    {
        myGameInstance = newInstance;
        myPerception = newPerception;

        init = true;
        AssessPerceivables();
    }
Example #7
0
    public Projectile(GameInstance parent, float initX, float initY, ObjectField objectField, ObjectProjectile objectProjectile)
        : base(parent.Rect.point.layer, initX, objectField, parent.ToLeft)
    {
        Move(new Vector2(0, initY));

        this.objectProjectile = objectProjectile;
        this.parent = parent;
    }
 private void Awake()
 {
     instance = this;
     AndroidWrapper.Initialize();
     menuInstance.OpenListMenu();
     if (!AndroidWrapper.IsAuthorizationSuccess())
         WriteError(AndroidWrapper.I.GetJaveExeption());
 }
 public Living New(GameInstance g)
 {
     Living _new;
     if (cameraFollowTargetList.Count < 1)
         _new = Create();
     else
         _new = Ship();
     return _new;
 }
Example #10
0
 public Living New(GameInstance g)
 {
     Living _new;
     if (guardEnemyList.Count < 1)
         _new = Create();
     else
         _new = Ship();
     return _new;
 }
Example #11
0
 public Living New(GameInstance g)
 {
     Living _new;
     if (bombBossList.Count < 1)
         _new = Create();
     else
         _new = Ship();
     return _new;
 }
Example #12
0
        internal static void Main()
        {
            #if !DEBUG
            // Hide mouse cursor in RELEASE mode
            Cursor.Hide();
            #endif

            using (var instance = new GameInstance())
            {
                instance.Scene = new TestScene(instance);
                instance.Run();
            }
        }
Example #13
0
 void Awake()
 {
     if(_instance == null)
     {
         _instance = this;
         DontDestroyOnLoad(this);
     }
     else
     {
         if(this != _instance)
             Destroy(this.gameObject);
     }
 }
Example #14
0
 public ActionHandler.Result ApplyAction(ActionSingle action, GameInstance firer)
 {
     if (handlers.ContainsKey(action.Type))
     {
         string[] values = ExtractValues(action.param, "param");
         ActionHandler.Result result = handlers[action.Type](action.value, firer, values);
         if (result != null && result.statusType != null)
         {
             status.Change(result.statusType, result.value);
         }
         return result;
     }
     return null;
 }
        // executed on the game instance
        internal override void DoAction( GameInstance gameInstance)
        {
            var plr =  (from p in gameInstance.LivingGameObjects  where p is Player && (p as Player).UniqueId == PlayerID select p as Player).First();

            plr.Velocity = new Vector2D(plr.Velocity.X + Velocity.Normal.Scale(Player.RunVelocity).X,
               plr.Velocity.Y + Velocity.Normal.Scale(Player.RunVelocity).Y);

            if (IsJumping)
            {
                if (!plr.IsAirborne)
                {
                    plr.Vz = 7;
                    plr.Z += .25;
                    plr.IsAirborne = true;
                }
            }
        }
        private Mech CreatePathFinderMech()
        {
            GameInstance    game        = UnityGameInstance.BattleTechGame;
            CombatGameState combatState = game.Combat;
            string          spawnerId   = Guid.NewGuid().ToString();
            string          uniqueId    = $"{spawnerId}.9999999999";

            HeraldryDef heraldryDef = null;

            combatState.DataManager.Heraldries.TryGet(HeraldryDef.HeraldyrDef_SinglePlayerSkirmishPlayer1, out heraldryDef);

            MechDef mechDef = null;

            combatState.DataManager.MechDefs.TryGet("mechdef_spider_SDR-5V", out mechDef);

            PilotDef pilotDef = null;

            combatState.DataManager.PilotDefs.TryGet("pilot_default", out pilotDef);
            Mech mech = new Mech(mechDef, pilotDef, new TagSet(), uniqueId, combatState, spawnerId, heraldryDef);

            return(mech);
        }
Example #17
0
        public IEnumerable <GameInstance> GetCollisions(GameInstance i, double x, double y,
                                                        IEnumerable <GameInstance> instances, bool onlySolid)
        {
            if (i.Sprite == null)
            {
                yield break;
            }

            var transform1 = GetSpriteTransform(i, x, y);

            foreach (var other in instances)
            {
                if (other.Id == i.Id)
                {
                    continue;
                }
                if (other.Sprite == null)
                {
                    continue;                       // Can change, so check again
                }
                if (onlySolid && !other.Solid)
                {
                    continue;
                }
                if (!(i.AssignedObject.IsEventRegistered(other.AssignedObject) ||
                      other.AssignedObject.IsEventRegistered(i.AssignedObject)))
                {
                    continue;
                }
                var transform2 = GetSpriteTransform(other);

                if (CheckSpriteCollision(i.Sprite, i.ComputeSubimage(), transform1, other.Sprite,
                                         other.ComputeSubimage(), transform2))
                {
                    yield return(other);
                }
            }
        }
Example #18
0
        public static void DoHotReload(GameInstance game)
        {
            Main.HBSLog?.Log("HotReload!");

            Main.ReloadResources();

            // reload behavior variables by forcing a new scope manager
            // TODO: THIS CAUSES A GAME FREEZE IF HOT RELOAD DURING AI PAUSE
            // this is because of scope manager taking a little bit to get info
            // from dataManager, temp solution is to skip if paused
            if (!AIPause.IsPaused)
            {
                Traverse.Create(game).Property("BehaviorVariableScopeManager")
                .SetValue(new BehaviorVariableScopeManager(game));
            }

            var aiActors = game.Combat.AllActors.Where(unit => unit.team is AITeam);

            foreach (var unit in aiActors)
            {
                Main.ResetUnitAI(unit);
                Main.TryOverrideUnitAI(unit);
            }

            var aiTeams = game.Combat.Teams.Where(team => team is AITeam).Cast <AITeam>();

            foreach (var team in aiTeams)
            {
                Main.ResetTeamAI(team);
                Main.TryOverrideTeamAI(team);
            }

            if (AIPause.IsPaused)
            {
                AIPause.Reset();
                TurnOrderOverride.TryRecalculateCurrentUnit(AIPause.CurrentAITeam);
            }
        }
Example #19
0
        /// <summary>
        /// Calculates an action based on a simple set of rules.
        /// </summary>
        public static UctAction RuleBasedAction(GameInstance game)
        {
            if (Constants.FastActionGeneration)
            {
                return(DefaultPolicyAction(game));
            }

            var result = new List <UctAction>();

            var currentMob = game.CurrentMob;

            if (!currentMob.HasValue)
            {
                return(UctAction.EndTurnAction());
            }

            var mob = game.CachedMob(currentMob.Value);

            GenerateDirectAbilityUse(game, mob, result);
            if (result.Count > 0)
            {
                return(MaxAbilityRatio(game, result));
            }

            GenerateAttackMoveActions(game, mob, result);
            if (result.Count > 0)
            {
                return(MaxAbilityRatio(game, result));
            }

            GenerateDefensiveMoveActions(game, mob, result);
            if (result.Count > 0)
            {
                return(result[0]);
            }

            return(UctAction.EndTurnAction());
        }
Example #20
0
        private async Task HandleMessage(SocketMessage Message)
        {
            if (!FunConfiguration.GamesChannels.Contains(Message.Channel.Id) && Message.Channel is not IDMChannel)
            {
                return;
            }
            if (Message.Content.StartsWith(BotConfiguration.Prefix))
            {
                return;
            }

            Player Player = GamesDB.Players.Find(Message.Author.Id);

            if (Player is null)
            {
                return;
            }
            if (Player.Playing < 1)
            {
                return;
            }

            GameInstance Instance = GamesDB.Games.Find(Player.Playing);

            if (Instance is null)
            {
                return;
            }

            IGameTemplate Game = Instance.ToGameProper();

            if (Game is null)
            {
                return;
            }

            await Game.HandleMessage(Message, GamesDB, DiscordSocketClient, FunConfiguration);
        }
Example #21
0
    // Called via gs_Game_In* LateUpdate, kills the player if they're still marked for death by the end of the frame
    public static void DoLateUpdatePlayerDeathCheck()
    {
        GameInstance gi = GameInstance.Object;

        GAssert.Assert(null != gi, "Unable to get GameInstance!");

        PlayerState ps = gi.GetPlayerState();

        GAssert.Assert(null != ps, "Unable to get player state!");

        // Only do this if the player is marked for death!
        if (!ps.GetPlayerMarkedForDeath())
        {
            return;
        }

        // Player can't pause
        m_bCanPause = false;

        // Do player death...
        uint iPlayerLives = ps.OnPlayerHasDied();

        // Let the room cleanup...
        m_gcActiveRoomController.OnPlayerHasDied(iPlayerLives);

        // And any subscribers...
        Messenger.Invoke(Types.s_sPLAYER_HasDied);

        // Set a respawn timer if we have lives left...
        if (iPlayerLives > 0)
        {
            TimerManager.AddTimer(Types.s_fPLAYER_RespawnHalfDur, BeginRespawnPlayer);
        }

        // Move player offscreen until we can respawn...
        // This needs to be done last. Things might still need the player position above!
        gi.GetPlayerObject().transform.position = new Vector3(1000f, 1000f, 0f);
    }
        public override void Mouse(MouseState state, MouseState oldState)
        {
            Vector2 position = GameInstance.ConvertScreenToWorld(state.X, state.Y);

            if (state.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released)
            {
                aabbM.LowerBound = position - d;
                aabbM.UpperBound = position + d;

                if (_left != null)
                {
                    aabbL = _left.GetCollisionBox();

                    if (AABB.TestOverlap(ref aabbM, ref aabbL))
                    {
                        _selectedVertex = _left;
                    }
                }

                if (_right != null)
                {
                    aabbR = _right.GetCollisionBox();

                    if (AABB.TestOverlap(ref aabbM, ref aabbR))
                    {
                        _selectedVertex = _right;
                    }
                }
            }

            if (state.LeftButton == ButtonState.Released && oldState.LeftButton == ButtonState.Pressed)
            {
                _selectedVertex = null;
            }

            MouseMove(state, oldState, position);
            base.Mouse(state, oldState);
        }
Example #23
0
        public void Update(GameTime gameTime)
        {
            GameInstance.Tick(gameTime);
            TickGameStartCountdown(gameTime);

            Timers.Update(gameTime);
            ProcessMessages();
            //Send all the wideband messages (if someone is listening)
            if (Connections.ActiveConnections.Count > 0)
            {
                if (MessageProcessor.MessageQueue.Count > 0)
                {
                    var msg = NetworkServer.CreateMessage();
                    MessageProcessor.WriteMessages(msg);
                    NetworkServer.SendMessage(msg, Connections.ActiveConnections,
                                              Lidgren.Network.NetDeliveryMethod.ReliableOrdered,
                                              Channels.GameplayData);
                }

                //As well as narrowband ones
                foreach (var plr in Players)
                {
                    if (MessageProcessor.HasPrivateMessages(plr) && plr.Connection != null && plr.Connection.Status == Lidgren.Network.NetConnectionStatus.Connected)
                    {
                        var msg = NetworkServer.CreateMessage();
                        MessageProcessor.WritePrivateMessages(plr, msg);
                        plr.Connection.SendMessage(msg,
                                                   Lidgren.Network.NetDeliveryMethod.ReliableOrdered,
                                                   Channels.GameplayData);
                    }
                }
            }
            //Just clear the queue since no one is listening
            MessageProcessor.ClearQueue();
            MessageProcessor.ClearPrivateQueues();

            FlushMessages();
        }
Example #24
0
    private IEnumerator ResumeGame()
    {
        Image fadeTexture = GameInstance.GetInstance().UI_Components.fadeTexture;
        Color newColor    = new Color(fadeTexture.color.r, fadeTexture.color.g, fadeTexture.color.b, 0f);
        float counter     = 0f;

        Time.timeScale = 1;

        while (counter < 1f)
        {
            if (counter > 0.1f)
            {
                //Band-aid solution. If we change the state immediately the character jumps
                InputManager.state = InputState.Ingame;
            }
            counter          += Time.fixedDeltaTime;
            fadeTexture.color = Color.Lerp(fadeTexture.color, newColor, counter);
            menuGroup.alpha  -= Time.deltaTime * 2;
            yield return(null);
        }

        menuGroup.Deactivate();
    }
        public bool DoStep(ref Player p, GameInstance gi)
        {
            double endTurnValue = eval(serializer.ConvertPosition(p));

            var boards = GetBoards(p);

            //foreach (var b in boards) { GamingForm.ShowAsync(b, "LOL"); }

            GetMaxBoard(boards, serializer, p.IsA, eval, out var maxBoard, out var maxValue);

            if (maxValue > endTurnValue)
            {
                p        = p.IsA ? maxBoard.A : maxBoard.B;
                gi.board = p.Board;
                return(true);
            }
            else
            {
                gi.board = p.Board;
                new RandomEvent.EndTurnREvent(p);
                return(false);
            }
        }
Example #26
0
    public void OnLoginAckPlayerServerId(byte[] pBuf)
    {
        GameProto.LoginAckPlayerServerId oRet = GameProto.LoginAckPlayerServerId.Parser.ParseFrom(pBuf);
        if (oRet == null)
        {
            H5Helper.H5LogStr("OnLoginAckPlayerServerId error parse");
            return;
        }

        string  szUrl = GameInstance.Instance().proUrlHost + GameInstance.Instance().proGetRoleUri;
        WWWForm form  = new WWWForm();

        form.AddField("platform", GameInstance.Instance().proPlatform);
        form.AddField("name", GameInstance.Instance().proName);
        form.AddField("head_img", GameInstance.Instance().proHeadImage);
        form.AddField("sex", GameInstance.Instance().proSex.ToString());
        form.AddField("access_token", GameInstance.Instance().proAccessToken);
        form.AddField("expires_date", GameInstance.Instance().proExpiresDate.ToString());
        form.AddField("openid", GameInstance.Instance().proOpenId);
        form.AddField("server_id", oRet.DwServerId.ToString());

        StartCoroutine(H5Helper.SendPost(szUrl, form, OnRoleData));
    }
Example #27
0
        public JsonResult NewGame(int gameDefId, NewGameModel newGameModel)
        {
            if (Platform.IsUserLogged())
            {
                newGameModel.Nick = User.Identity.Name;
            }

            try
            {
                newGameModel.Validate();
                Game = Platform.NewGameInstance(Platform.GetGameDefinitionById(gameDefId), newGameModel.Name, newGameModel.Password);
                int playerId = Game.AddPlayer(new Player(newGameModel.Nick, Permission.TYPE.Moderator));
                SaveGame(Game.Id);

                Platform.GameAuthentication.AddPermission(Game.Id, playerId, newGameModel.Nick, Crypto.HashPassword(newGameModel.Password), Permission.TYPE.Moderator);

                return(Json(new Result(new { gameId = Game.Id }).AsSuccess()));
            }
            catch (Error.ValidationException validation)
            {
                return(Json(validation.Result));
            }
        }
Example #28
0
        public GamingForm(GameInstance g)
        {
            CheckForIllegalCrossThreadCalls = false;
            KeyPreview      = true;
            StartPosition   = FormStartPosition.CenterScreen;
            FormBorderStyle = FormBorderStyle.FixedToolWindow;

            Size = new Size(1300, 700);

            center = new ControlCenter(g, this);

            center.boardC.Location = BoardControl.StdLocation(center.boardC);

            center.HeroA.Location = HeroPortret.DefaultLocation(center.HeroA);
            center.HeroB.Location = HeroPortret.DefaultLocation(center.HeroB);

            center.AHand.Location = HandControl.StdLocation(center.AHand, false);
            center.BHand.Location = HandControl.StdLocation(center.BHand, true);

            center.endButt.Location = EndTurnButton.StdLocation(center.endButt);

            Load += StdForm_Load;
        }
Example #29
0
    private void UpdateWeapon()
    {
        var savedWeapons = PlayerSave.GetWeapons();
        var minPosition  = int.MaxValue;

        foreach (int position in savedWeapons.Keys)
        {
            if (minPosition > position)
            {
                minPosition = position;
            }
        }
        var newWeaponData = GameInstance.GetAvailableWeapon(savedWeapons[minPosition]);

        if (weaponData != newWeaponData)
        {
            weaponData = newWeaponData;
            if (characterModel != null && weaponData != null)
            {
                characterModel.SetWeaponModel(weaponData.rightHandObject, weaponData.leftHandObject, weaponData.shieldObject);
            }
        }
    }
Example #30
0
        /// <summary>
        /// Returns an action that moves towards an enemy as fast as possible.
        /// </summary>
        public static UctAction FastMoveTowardsEnemy(GameInstance state, CachedMob mob, CachedMob target)
        {
            var pathfinder = state.Pathfinder;

            var moveTarget = pathfinder.FurthestPointToTarget(mob, target);

            if (moveTarget != null && pathfinder.Distance(mob.MobInstance.Coord, moveTarget.Value) <=
                mob.MobInstance.Ap)
            {
                return(UctAction.MoveAction(mob.MobId, moveTarget.Value));
            }
            else if (moveTarget == null)
            {
                // Intentionally doing nothing
                return(UctAction.EndTurnAction());
            }
            else
            {
                Utils.Log(LogSeverity.Debug, nameof(AiRuleBasedController),
                          $"Move failed since target is too close, source {mob.MobInstance.Coord}, target {target.MobInstance.Coord}");
                return(UctAction.EndTurnAction());
            }
        }
Example #31
0
    protected virtual void OnWeaponsChanged(string value)
    {
        selectWeapons = value;
        // Changes weapon list, equip first weapon equipped position
        if (isServer)
        {
            var splitedData = selectWeapons.Split('|');
            var minEquipPos = int.MaxValue;
            for (var i = 0; i < splitedData.Length; ++i)
            {
                var singleData = splitedData[i];
                var weaponData = GameInstance.GetWeapon(singleData);

                if (weaponData == null)
                {
                    continue;
                }

                var equipPos = weaponData.equipPosition;
                if (minEquipPos > equipPos)
                {
                    if (defaultWeaponIndex == -1)
                    {
                        defaultWeaponIndex = i;
                    }
                    minEquipPos = equipPos;
                }

                var equippedWeapon = new EquippedWeapon();
                equippedWeapon.defaultId = weaponData.GetId();
                equippedWeapon.weaponId  = weaponData.GetId();
                equippedWeapon.SetMaxAmmo();
                equippedWeapons[equipPos] = equippedWeapon;
                equippedWeapons.Dirty(equipPos);
            }
        }
    }
        public async Task <ExecutionInfo> StartInstanceAsync(string host, int port, GameInstance instance)
        {
            string version;

            if (port < this._portRangeStart || port > this._portRangeEnd)
            {
                // TODO - also check other instances (not trivial due to race condition)
                this._logger.LogWarning("Port ({port}) out of range ({low} - {high})", port, this._portRangeStart, this._portRangeEnd);
                throw new Exception("TODO - Invalid port");
            }

            if (instance.TargetVersion.Patch == null)
            {
                version = string.Format("{0}.{1}", instance.TargetVersion.Major, instance.TargetVersion.Minor);
            }
            else
            {
                version = string.Format("{0}.{1}.{2}", instance.TargetVersion.Major, instance.TargetVersion.Minor, instance.TargetVersion.Patch);
            }

            await this.LoadImageAsync(version);

            // TODO - handle invliad info
            string newID = await this.StartImageAsync(instance.Key, port, instance.ImplementationInfo.GetValueOrDefault("localPath"), version);

            ExecutionInfo i = new ExecutionInfo
            {
                Key      = newID,
                Hostname = host,
                Port     = port,

                RunningVersion = version,
                InstanceKey    = instance.Key,
            };

            return(i);
        }
Example #33
0
 private static void OnPathfindingComplete(AStar.AStarResult result)
 {
     try {
         int                      baseDifficulty = 5;
         GameInstance             game           = LazySingletonBehavior <UnityGameInstance> .Instance.Game;
         Dictionary <string, int> allCareerFactionReputations = new Dictionary <string, int>();
         foreach (FactionValue faction in FactionEnumeration.FactionList)
         {
             if (faction.DoesGainReputation)
             {
                 allCareerFactionReputations.Add(faction.Name, game.Simulation.GetRawReputation(faction));
             }
         }
         int            count           = result.path.Count;
         StarSystemNode starSystemNode  = (StarSystemNode)result.path[0];
         int            rangeDifficulty = 0;
         int            repModifier     = 0;
         string         repFaction      = starSystemNode.System.OwnerValue.Name;
         if (!DCECore.settings.isCapital(starSystemNode.System))
         {
             rangeDifficulty = Mathf.RoundToInt((count - 1));
         }
         else
         {
             repFaction = DCECore.settings.getFactionForCapital(starSystemNode.System.Name);
         }
         if (allCareerFactionReputations.ContainsKey(repFaction))
         {
             int repOfOwner = allCareerFactionReputations[repFaction];
             repModifier = Mathf.CeilToInt(repOfOwner / 20f);
         }
         int endDifficulty = Mathf.Clamp(baseDifficulty + rangeDifficulty - repModifier, 1, DCECore.settings.maxDifficulty);
         AccessTools.Field(typeof(StarSystemDef), "DefaultDifficulty").SetValue(starSystemNode.System.Def, endDifficulty);
     }catch (Exception e) {
         DCECore.modLog.Error?.Write(e);
     }
 }
Example #34
0
        private void UpdateData(GameInstance gameInstance)
        {
            if (gameInstance != null)
            {
                CardDeck deck = new CardDeck();

                this.GameUID = gameInstance.GameUID;

                if (gameInstance.PlayersPublic != null)
                {
                    this.Adventurers = gameInstance.PlayersPublic;
                }

                if (gameInstance.GetCurrent() != null)
                {
                    this.Nodes = (new Card[] { new Card(-1, CardType.ENTRY) }).Concat(deck.GetThisDeck(gameInstance.GetCurrent().Node)).ToArray();
                }

                this.MineIndex  = (gameInstance.CurrentMineID + 1).ToString() + " / " + gameInstance.MineNumber.ToString();
                this.PathLength = nodes.Length;

                if (gameInstance.GetCurrent() != null)
                {
                    this.EmeraldsForTake = gameInstance.GetCurrent().EmeraldsForTake;
                }

                var player = gameInstance.GetPlayerData(this.playerUID);

                if (player != null)
                {
                    this.Pocket         = player.pocket;
                    this.Chest          = player.chest;
                    this.playerID       = player.id;
                    this.makingDecision = (player.status == PlayerStatus.EXPLORING);
                }
            }
        }
Example #35
0
        public void Init(IGameEngine engine, GameInstance gameInstance, bool requireAllActions)
        {
            m_engine = engine;
            m_gameInstance = gameInstance;

            m_keyMappings = new Dictionary<NamedKey, MethodInfo>();
            m_actionKeyMapping = new Dictionary<string, NamedKey>();

            // So we don't hit disk n times, where n is the number of Keyboard handlers, cache the file to read over and over.
            if (m_keyMappingsStream == null)
            {
                m_keyMappingsStream = new StreamReader("KeyMappings.xml");
                m_arrowMappingsStream = new StreamReader(GetArrowMappingConfigPath());                
            }
            else
            {
                m_keyMappingsStream.BaseStream.Seek(0, SeekOrigin.Begin);
                m_arrowMappingsStream.BaseStream.Seek(0, SeekOrigin.Begin);
            }

            // We depend on this order so specific actions "like rest" can be overwritten by arrow mapping files.
            ParseKeymappingFile(requireAllActions, m_keyMappingsStream);
            ParseKeymappingFile(requireAllActions, m_arrowMappingsStream);
        }
Example #36
0
        void CreateTopBar()
        {
            var path = AssetsCoordinates.Generic.Icons.ResourcePath;

            // BACK
            Button btn_back = new Button();

            GameInstance.UI.Root.AddChild(btn_back);
            btn_back.SetStyleAuto(null);
            btn_back.SetPosition((int)(dim.XScreenRatio * 40), (int)(dim.YScreenRatio * 40));
            btn_back.SetSize((int)(dim.XScreenRatio * 120), (int)(dim.YScreenRatio * 120));
            btn_back.Texture   = GameInstance.ResourceCache.GetTexture2D(AssetsCoordinates.Generic.Icons.ResourcePath);
            btn_back.ImageRect = AssetsCoordinates.Generic.Icons.BntBack;
            btn_back.Pressed  += async args => {
                // Close game
                GameInstance.Graphics.Close();
                await GameInstance.Exit();
            };
#if __ANDROID__
            btn_back.Visible = false;
#else
            btn_back.Visible = true;
#endif
        }
Example #37
0
        static public void Tra_SeasonedFollowers(SPlayer player)
        {
            var  sPlayerGroups      = GameInstance.Get().GetPlayerGroups().FindAll(o => o.ownerID == player.ID);
            FInt extraXP            = (FInt)20;
            FInt charactersInGroups = FInt.ZERO;

            foreach (var v in sPlayerGroups)
            {
                charactersInGroups += v.characters.Count;
            }

            FInt bonus = extraXP / charactersInGroups;

            foreach (var v in sPlayerGroups)
            {
                if (v.characters != null)
                {
                    foreach (var c in v.characters)
                    {
                        c.Get().Xp = c.Get().Xp + bonus;
                    }
                }
            }
        }
 private static void OnPathfindingComplete(AStar.AStarResult result)
 {
     try {
         int          baseDifficulty = 5;
         GameInstance game           = LazySingletonBehavior <UnityGameInstance> .Instance.Game;
         Dictionary <Faction, int> allCareerFactionReputations = game.Simulation.GetAllCareerFactionReputations();
         Settings       settings        = Helper.LoadSettings();
         int            count           = result.path.Count;
         StarSystemNode starSystemNode  = (StarSystemNode)result.path[0];
         int            rangeDifficulty = 0;
         int            repModifier     = 0;
         Faction        repFaction      = starSystemNode.System.Owner;
         if (!Helper.IsCapital(starSystemNode.System))
         {
             rangeDifficulty = Mathf.RoundToInt((count - 1));
         }
         else
         {
             repFaction = Helper.GetFactionForCapital(starSystemNode.System);
         }
         if (allCareerFactionReputations.ContainsKey(repFaction))
         {
             int repOfOwner = allCareerFactionReputations[repFaction];
             repModifier = Mathf.CeilToInt(repOfOwner / 20f);
         }
         else
         {
             //Logger.LogLine("RepMissing: " + starSystemNode.System.Owner.ToString());
             //Logger.LogLine("Def: " + starSystemNode.System.Def.Owner.ToString());
         }
         int endDifficulty = Mathf.Clamp(baseDifficulty + rangeDifficulty - repModifier, 1, 10);
         AccessTools.Field(typeof(StarSystemDef), "DefaultDifficulty").SetValue(starSystemNode.System.Def, endDifficulty);
     }catch (Exception e) {
         Logger.LogError(e);
     }
 }
Example #39
0
        /// <summary>
        /// Stochastically picks an ability based on its damage/cost. Can be optionally
        /// run with a deterministic result simply returning the maximum value.
        /// </summary>
        public static UctAction MaxAbilityRatio(GameInstance game, List <UctAction> actions,
                                                bool deterministic = false)
        {
            if (deterministic)
            {
                return(DeterministicMaxAbilityRatio(game, actions));
            }
            else
            {
                var pairs = actions.Select(action => {
                    return(Tuple.Create(action, game.MobManager.Abilities[action.AbilityId]));
                })
                            .ToList();

                pairs.Sort((a, b) => b.Item2.DmgCostRatio.CompareTo(a.Item2.DmgCostRatio));

                var totalRatio = pairs.Sum(p => p.Item2.DmgCostRatio);

                var probabilities = pairs.Select(p => (double)p.Item2.DmgCostRatio / totalRatio);

                var pick = Probability.UniformPick(pairs, probabilities.ToList());
                return(pick.Item1);
            }
        }
Example #40
0
 public static GameInstance GetInstance(GameObject prefab = null)
 {
     if (singleton == null)
     {
         if (FindObjectsOfType <GameInstance>().Length < 1)
         {
             if (prefab)
             {
                 singleton = ((GameObject)Object.Instantiate(prefab, Vector2.zero, Quaternion.identity))
                             .GetComponent <GameInstance>();
             }
             else
             {
                 singleton = ((GameObject)Object.Instantiate(Resources.Load("Prefabs/GameInstance"), Vector2.zero,
                                                             Quaternion.identity)).GetComponent <GameInstance>();
             }
         }
         else
         {
             singleton = FindObjectOfType <GameInstance>();
         }
     }
     return(singleton);
 }
Example #41
0
        public Entity BuildMobPreview(GameInstance game, Func <int> mobFunc)
        {
            Func <string> textFunc = () => {
                var builder = new StringBuilder();

                var mobId = mobFunc();

                builder.AppendLine(mobId.ToString());

                var mobInfo = game.MobManager.MobInfos[mobId];

                foreach (var abilityId in mobInfo.Abilities)
                {
                    var ability = game.MobManager.Abilities[abilityId];
                    builder.AppendLine("-----");
                    builder.AppendLine($"DMG {ability.Dmg}, Range {ability.Range}");

                    if (!ability.Buff.IsZero)
                    {
                        var buff = ability.Buff;
                        builder.AppendLine("Buffs:");
                        builder.AppendLine($"Hp {buff.HpChange}, Ap {buff.ApChange}");
                    }
                }

                return(builder.ToString());
            };

            var wrapper = new Entity {
                Renderer = new ColorRenderer(Color.White)
            };

            wrapper.AddChild(new Label(textFunc, _assetManager.Font));

            return(wrapper);
        }
Example #42
0
    private IEnumerator LiftPlatform(bool liftPlatform)
    {
        float   counter         = 0;
        Vector3 initialPosition = platform.position;

        Transform initialTransform = GameInstance.GetInstance().Player_Components.dog;
        Transform newParent        = CheckForDog();

        lifted = !lifted;
        while (counter < 1)
        {
            counter += Time.deltaTime * 0.5f;
            if (liftPlatform)
            {
                platform.position = ExtensionMethods.SmoothStep(initialPosition, groundedPosition + new Vector3(0, height, 0), counter);
            }
            else
            {
                platform.position = ExtensionMethods.SmoothStep(initialPosition, groundedPosition, counter);
            }
            yield return(null);
        }
        initialTransform.SetParent(newParent);
    }
Example #43
0
        /// <summary>
        /// Runs a playout with the given encounter defined by a DNA pair and both controllers.
        /// </summary>
        public static int Playout(GameInstance game, DNA d1, DNA d2, IMobController c1, IMobController c2)
        {
            GameSetup.OverrideGameDna(game, d1, d2);

            game.AssignAiControllers(c1, c2);

            int iterations = Constants.MaxPlayoutEvaluationIterations;

            var hub = new GameEventHub(game);

            while (!game.IsFinished && iterations-- > 0)
            {
                game.CurrentController.FastPlayTurn(hub);
                ActionEvaluator.FNoCopy(game, UctAction.EndTurnAction());
            }

            if (Constants.GetLogBuffer().ToString().Length != 0)
            {
                Console.WriteLine(Constants.GetLogBuffer());
            }
            Constants.ResetLogBuffer();

            return(Constants.MaxPlayoutEvaluationIterations - iterations);
        }
Example #44
0
    private void StartGame()
    {
        // Spawn the player offscreen. SetPlayerDefaults locks it and prevents movement.
        // Player Object remains in the persistent scene, so we don't need to care
        // about what happens between scene loads...
        {
            m_goPlayerObjectReference = GameInstance.Instantiate(m_goPlayerPrefab, new Vector3(100, 100, 0), Quaternion.identity);
            GAssert.Assert(null != m_goPlayerObjectReference, "Unable to instantiate Player Object");
            m_gcPlayerState = m_goPlayerObjectReference.GetComponent <PlayerState>();
            GAssert.Assert(null != m_gcPlayerState, "Unable to get Player State");
            m_gcPlayerController = m_goPlayerObjectReference.GetComponent <PlayerController>();
            GAssert.Assert(null != m_gcPlayerController, "Unable to get Player Controller");
            m_gcPlayerInventory = m_goPlayerObjectReference.GetComponent <PlayerInventory>();
            GAssert.Assert(null != m_gcPlayerInventory, "Unable to get Player Inventory!");
        }

        // Set Game Defaults
        {
            Messenger.ClearAll();
            TimerManager.SetDefaults(1.0f, 1.0f);
            m_gcPlayerInventory.SetDefaults();
            m_gcPlayerState.SetDefaults();
            m_gcGameCamera.SetDefaults();
            GameGlobals.SetDefaults();
            m_gcGameHud.SetDefaults();
            m_gcPauseScreen.SetDefaults();
            m_gcMainMenu_Cecconoid.SetDefaults();
            m_gcGameOverScreen.SetDefaults();
            m_gcCompletionSequence.SetDefaults();
#if GDEBUG
            m_gcDevMenu.SetDefaults();
#endif

            Messenger.Invoke(Types.s_sHUD_Hide);
        }
    }
Example #45
0
 static void Postfix(Contract __instance, MissionResult result)
 {
     try {
         GameInstance game     = LazySingletonBehavior <UnityGameInstance> .Instance.Game;
         StarSystem   system   = game.Simulation.StarSystems.Find(x => x.ID == __instance.TargetSystem);
         Faction      oldOwner = system.Def.Owner;
         if (result == MissionResult.Victory)
         {
             system = Helper.PlayerAttackSystem(system, game.Simulation, __instance.Override.employerTeam.faction, __instance.Override.targetTeam.faction, true);
         }
         else
         {
             system = Helper.PlayerAttackSystem(system, game.Simulation, __instance.Override.employerTeam.faction, __instance.Override.targetTeam.faction, false);
         }
         if (system.Def.Owner != oldOwner)
         {
             SimGameInterruptManager interruptQueue = (SimGameInterruptManager)AccessTools.Field(typeof(SimGameState), "interruptQueue").GetValue(game.Simulation);
             interruptQueue.QueueGenericPopup_NonImmediate("Conquered", Helper.GetFactionName(system.Def.Owner, game.Simulation.DataManager) + " took " + system.Name + " from " + Helper.GetFactionName(oldOwner, game.Simulation.DataManager), true, null);
         }
     }
     catch (Exception e) {
         Logger.LogError(e);
     }
 }
Example #46
0
        static public void Tra_MentalWall(SPlayer player)
        {
            var  sPlayerGroups      = GameInstance.Get().GetPlayerGroups().FindAll(o => o.ownerID == player.ID);
            FInt mentalSgielding    = (FInt)20;
            FInt charactersInGroups = FInt.ZERO;

            foreach (var v in sPlayerGroups)
            {
                charactersInGroups += v.characters.Count;
            }

            FInt bonus = (mentalSgielding / charactersInGroups).ReturnRounded();

            foreach (var v in sPlayerGroups)
            {
                if (v.characters != null)
                {
                    foreach (var c in v.characters)
                    {
                        c.Get().attributes.AddToBase(TAG.SHIELDING_MENTAL, bonus);
                    }
                }
            }
        }
Example #47
0
 // Use this for initialization
 void Start()
 {
     gm = GameInstance.Instance;
 }
 public void JoinGameInstance(GameInstance gameInstance, int currentUserID)
 {
     if (GetUsersByGameInstance(gameInstance.GameInstanceID).ToList().Exists(user => user.UserID == currentUserID)) return;
     var joinInstance = new GameInstance { GameID = gameInstance.GameID, UserID = currentUserID, GameInstanceID = gameInstance.GameInstanceID };
     _context.GameInstances.Add(joinInstance);
     Save();
 }
Example #49
0
 public TestScene(GameInstance instance)
     : base(instance)
 {
     cameraController = new Input.CameraController(Input, Camera);
     CreateEntity(Cache.Get<Graphics.Mesh>("simplecube.DAE"), Cache.Get<Graphics.Materials.Material>("default"));
 }
 internal DialogConfirmAction(IGameEngine engine, GameInstance gameInstance, List<ISkill> newlySelectedSkill)
 {
     m_engine = engine;
     m_gameInstance = gameInstance;
     m_newlySelectedSkills = new List<ISkill>(newlySelectedSkill);   // Copy list since skill tree will clear
 }
		public ArrayIterator (string id, GameInstance game, System.Action<int> onNext) {
			this.id = id;
			this.game = game;
			this.onNext = onNext;
			game.Dispatcher.AddListener ("__next", OnNext);
		}
Example #52
0
 public void PlayRandomGroan(GameInstance playerInstance)
 {
     groanSound.PlaySound(playerInstance);
 }
Example #53
0
 public void PlayRandomWhoosh(GameInstance playerInstance)
 {
     whooshSound.PlaySound(playerInstance);
 }
Example #54
0
 public void PlayRandomPunch(GameInstance playerInstance)
 {
     punchSound.PlaySound(playerInstance);
 }
Example #55
0
 public ActionHandler.Result ApplyAction(ActionSingle action, GameInstance firer)
 {
     if (actionHandler != null)
     {
         return actionHandler.ApplyAction(action, null);
     }
     return null;
 }
Example #56
0
 public void PauseAIGameInstance(GameInstance _gi)
 {
     if (OnPauseAIGameInstance != null)
         OnPauseAIGameInstance(_gi);
 }
Example #57
0
 void Awake()
 {
     DontDestroyOnLoad(this.gameObject);
     instance = this;
 }
Example #58
0
 public override void EditProps(GameInstance newInstance)
 {
     myProperties.myGameInstance = newInstance;
     myProperties.myScreen = GameData.instance.allScreens[myProperties.myGameInstance.instanceIndex];
 }
Example #59
0
    public ProjectileCustom(GameInstance parent, float initX, float initY, ObjectField objectField, ObjectProjectile objectProjectile, Action action)
        : base(parent, initX, initY, objectField, objectProjectile)
    {
        List<VectorEntity> pattern = VectorGenerator.Custom(objectProjectile.Speed, objectProjectile.SpeedY, objectProjectile.Gravity, parent.ToLeft);
        //pattern.Add(new LinearVelocity(parent.Velocity));
        SetMove(pattern);

        InitAction(action);
    }
Example #60
0
 public virtual void LoadContent(GameInstance game,string filename){
     effect = game.Content.Load<Effect>(filename);
 }