Exemplo n.º 1
0
        public override Task Play(GameContext gameContext)
        {
            gameContext.Dungeon.State.MonsterStrength += StrengthBonus;
            gameContext.Dungeon.State.RewardTreasures += TreasureBonus;

            return Task.CompletedTask;
        }
Exemplo n.º 2
0
		//private GamePackageManager gamePackageManager;

		/// <summary>
		/// Default constructor
		/// </summary>
		public Main()
		{
			// Initialize the default application settings
			Window.Title = "";

			// Set the name of the current thread which our application is running at
			Thread.CurrentThread.Name = "Game.Core";

			// Initialize the logger
			Logger.Outputs.Add(new FileOutputSource("log.txt"));

			// Initialize the game context used throughout the application containing shared resources
			context = new GameContext(this);

			// Graphics (first part)
			context.Graphics.DeviceManager = new GraphicsDeviceManager(this);
			context.Graphics.DeviceManager.PreferredBackBufferWidth = context.View.Area.Width;
			context.Graphics.DeviceManager.PreferredBackBufferHeight = context.View.Area.Height;
			//context.Graphics.DeviceManager.IsFullScreen = true;
			context.Graphics.DeviceManager.ApplyChanges();

			// View
			context.View.SafeArea = context.Graphics.DeviceManager.GraphicsDevice.Viewport.TitleSafeArea;

			// Content
			Content.RootDirectory = "Content";
			context.Resources.Content = Content;

			// Initialize the fps counter
			fpsCounter = new FpsCounter(context);
		}
Exemplo n.º 3
0
 public override void DrawAbove(GameContext context)
 {
     // Fade the screen.
     if (!context.Textures.Keys.Contains("black"))
         throw new ProtogameException("You must load a texture with the name 'black' in order for FadingWorld to fade to black.  Check to make sure you are doing this in the LoadContent of your game.");
     context.SpriteBatch.Draw(context.Textures["black"], new Rectangle(0, 0, Tileset.TILESET_PIXEL_WIDTH, Tileset.TILESET_PIXEL_HEIGHT), new Color(1.0f, 1.0f, 1.0f, this.Fade));
 }
Exemplo n.º 4
0
        public void Initialize(GameContext context)
        {
            Texture = context.Content.Load<Texture2D>("Scenes/Levels/LevelFailed");
            HalfSize = new Vector2(Texture.Width / 2f, Texture.Height / 2f);

            Position = new Vector2((int)(Device.HalfWidth - HalfSize.X), (int)(Device.HalfHeight - HalfSize.Y));
        }
Exemplo n.º 5
0
 public CircleEffect(GameContext context)
     : base(context)
 {
     _context = context;
     effect = CGHelper.CreateEffectFx5("Resources\\Shader\\circleShader.fx",
         context.RenderContext.DeviceManager.Device);
     beffect = CGHelper.CreateEffectFx5("Resources\\Shader\\convergenceBeam.fx",
         context.RenderContext.DeviceManager.Device);
     noiseView = context.LoadTexture("Resources\\Effect\\noise.png");
     beamView = context.LoadTexture("Resources\\Effect\\lazer.png");
     ShaderResourceView view = context.LoadTexture("Resources\\Effect\\circle.png");
     frontCircle = new DividedPlaneBoard(context.RenderContext, view,100,
         new Vector2(100, 100),
         new PlaneBoard.PlaneBoardDescription(BlendStateManager.BlendStates.Add, effect, false, RenderFront));
     frontCircle.Initialize();
     for (int i = 0; i < 3; i++)
     {
         subCircle[i] = new PlaneBoard(context.RenderContext, view, new Vector2(30, 30),
             new PlaneBoard.PlaneBoardDescription(BlendStateManager.BlendStates.Add, effect, false, RenderFront));
         subCircle[i].Initialize();
     }
     for (int i = 0; i < 5; i++)
     {
         beamEffects[i]=new DividedPlaneBoard(context.RenderContext, view, 100,
         new Vector2(100, 100),
         new PlaneBoard.PlaneBoardDescription(BlendStateManager.BlendStates.Add, beffect, false, Renderbeam));
         beamEffects[i].Initialize();
     }
 }
Exemplo n.º 6
0
        public override bool Update(GameContext context)
        {
            // Do our fade effect if needed.
            if (this.m_ChangingLevel || this.m_FadingIn)
            {
                // Check to see what stage of fading we're at.
                if (this.m_FadingIn && this.m_FadeLevel < 1f)
                    this.m_FadeLevel += 0.05f;
                else if (!this.m_FadingIn && this.m_FadeLevel > 0f)
                {
                    this.m_FadeLevel -= 0.05f;
                    return false;
                }
                else if (this.m_FadingIn && this.m_FadeLevel >= 1f)
                {
                    this.LoadLevelImmediate(this.m_LevelChangeTarget);
                    this.m_FadingIn = false;
                }
                else if (!this.m_FadingIn && this.m_FadeLevel <= 0f)
                {
                    this.m_ChangingLevel = false;
                    return false;
                }
            }

            // Get the base class to also update.
            return true;
        }
Exemplo n.º 7
0
 public CommandListener(GameContext context)
 {
     _context = context;
     //このクラスの中のCommandAttributeがついているメソッドを列挙
     foreach (MethodInfo methodInfo in GetType().GetMethods())
     {
         var attr = methodInfo.GetCustomAttribute<CommandAttribute>();
         if (attr != null)
         {
             ParameterInfo[] paramsInfo = methodInfo.GetParameters();
             if (paramsInfo.Length != 1)
             {
                 Tracer.w("コマンド{0}は引数の数が正しくないため読み込みはスキップされました。", attr.CommandName);
                 continue;
             }
             if (!paramsInfo[0].ParameterType.IsEquivalentTo(typeof (string[])))
             {
                 Tracer.w("コマンド{0}は引数の型が正しくないため読み込みはスキップされました。", attr.CommandName);
                 continue;
             }
             commands.Add(attr.CommandName, new Tuple<string, CommandAttribute>(methodInfo.Name, attr));
         }
     }
     Task.Run((Action) Listen);
 }
Exemplo n.º 8
0
    void Start()
    {
        context = GetComponent<GameContext>();
        context.BlockTypes.OnAdded += BlockTypes_OnAdded;

        context.Map.BlockChanged += Map_BlockChanged;
    }
 public override Task Play(GameContext gameContext)
 {
     gameContext.Dungeon.State.HeroesStrength += GetProperty<StrengthBonus>().Bonus;
     gameContext.Dungeon.State.RunAwayBonus += GetProperty<RunAwayBonus>().Bonus;
     BoundCards.ForEach(card => card.Play(gameContext));
     return Task.CompletedTask;
 }
Exemplo n.º 10
0
        public void loadGames()
        {
            using (var db = new GameContext())
            {

                IEnumerable games = db.SavedGames.AsEnumerable();
                foreach (var item in games)
                {
                    SavedGame game = item as SavedGame;
                    game.Player1 = (Player) db.Players.Where(s => s.Id == game.Player1ID).First<Player>();
                    game.Player2 = (Player)db.Players.Where(s => s.Id == game.Player2ID).First<Player>();

                    game.Player1.UserBoard = (BoardModel)db.Boards.Where(b => b.Id == game.Player1.UserBoardID).First<BoardModel>();
                    game.Player1.TargetBoard = (BoardModel)db.Boards.Where(b => b.Id == game.Player1.TargetBoardID).First<BoardModel>();
                    game.Player2.UserBoard = (BoardModel)db.Boards.Where(b => b.Id == game.Player2.UserBoardID).First<BoardModel>();
                    game.Player2.TargetBoard = (BoardModel)db.Boards.Where(b => b.Id == game.Player2.TargetBoardID).First<BoardModel>();

                    game.Player1.UserBoard.Model = db.CellValues.Where(c => c.BoardModelID == game.Player1.UserBoardID).ToList<CellValue>();
                    game.Player1.TargetBoard.Model = db.CellValues.Where(c => c.BoardModelID == game.Player1.TargetBoardID).ToList<CellValue>();
                    game.Player2.UserBoard.Model = db.CellValues.Where(c => c.BoardModelID == game.Player2.UserBoardID).ToList<CellValue>();
                    game.Player2.TargetBoard.Model = db.CellValues.Where(c => c.BoardModelID == game.Player2.TargetBoardID).ToList<CellValue>();

                    Names.Add(game);
                }
            }
        }
Exemplo n.º 11
0
 public void Initialize(GameContext context)
 {
     Texture = context.Content.Load<Texture2D>("Player/Moon2");
     HalfSize = new Vector2(Texture.Width / 2f, Texture.Height / 2f);
     CollisionRadius = Texture.Width / 2f;
     ResetBounces();
 }
        public override async void Execute(GameContext gameContext)
        {
            // send a request to player if he is looking for trouble (wants to or can fight his monster)
            var ownMonster = gameContext.RequestSink.Request<MonsterCard>(Player, Player, Player.YourHand.OfType<MonsterCard>());
            var monster = await ownMonster.GetResult();
            if (monster != null)
            {
                await gameContext.Dungeon.PlayACard(monster);

                // allow to run away from monster
                var endBattleAction = new EndBattleAction(Player);
                Player.AddAction(endBattleAction);

                // allow to ask for help only if doors led to monster
                var askForHelpAction = new AskForHelpAction(Player);
                Player.AddAction(askForHelpAction);

                // allow to run away from monster
                var runAwayAction = new RunAwayAction(Player);
                Player.AddAction(runAwayAction);

                // allow to look for trouble
                var takeBadStuffAction = new TakeBadStuffAction(Player);
                Player.AddAction(takeBadStuffAction);
            }
        }
Exemplo n.º 13
0
 public PlatformServices(Game game)
     : base(game)
 {
     DrawContext = new GameContext();
     UpdateContext = new GameContext();
     HttpClient = new HttpClient();
     MainThreadContext = SynchronizationContext.Current;
 }
Exemplo n.º 14
0
 public BulletEffect(GameContext context)
     : base(context)
 {
     game = context;
     effect=CGHelper.CreateEffectFx5("Resources\\Shader\\bulletShader.fx",context.RenderContext.DeviceManager.Device);
     bulletTexture = context.LoadTexture("Resources\\Effect\\thunder.png");
     board=new DividedPlaneBoard(context.RenderContext,bulletTexture,100,new Vector2(10,10),new PlaneBoard.PlaneBoardDescription(BlendStateManager.BlendStates.Add, effect,false,SubscribeLazerEffectVariable));
     board.Initialize();
 }
Exemplo n.º 15
0
	public void InitGame (List<Player> _ListPlayer)		
	{
		GameContext.instance = this;
		foreach(Player lPlayer in _ListPlayer)
		{
			mDicPlayer.Add(lPlayer.mId, lPlayer);
		}
		StartCoroutine(SynchServerValues());
	}
        public override void Execute(GameContext gameContext)
        {
            // remove possibility to enter the dungeon after entered this one
            gameContext.Dungeon.CurrentPlayer.RemoveAction(this);

            // draw a doors card as face-up and play it
            var doors = gameContext.DoorsCardDeck.Take();
            gameContext.Dungeon.Enter(doors, Player);
        }
Exemplo n.º 17
0
        public override void Execute(GameContext gameContext)
        {
            if (!gameContext.Dungeon.TryRunAway())
            {
                gameContext.Dungeon.TakeBadStuff(gameContext);
            }

            gameContext.Dungeon.Exit();
        }
Exemplo n.º 18
0
        PlatformTimer(GameContext context, Action<object> callback, object state, TimeSpan dueTime, TimeSpan period)
            : base(dueTime, period)
        {
            if (callback == null)
                throw new ArgumentNullException("callback");

            _context = context;
            Ellapsed += (s, e) => callback(state);
        }
Exemplo n.º 19
0
 public Scene(GameContext context, SceneEffect effect)
 {
     _device = context.GraphicsDevice;
     _sceneRenderer = new DefaultSceneRenderer(context, effect);
     _allNodes = new List<SceneNode>();
     _allCameras = new List<Camera>();
     LightDirection = new Vector3(1, -1, -1);
     _spriteBatch = new SpriteBatch(_device);
 }
Exemplo n.º 20
0
        public PlatformTimer(GameContext context, Action<object> callback)
            : base(TimeSpan.Zero, TimeSpan.Zero)
        {
            if (callback == null)
                throw new ArgumentNullException("callback");

            _context = context;
            Ellapsed += (s, e) => callback(this);
        }
Exemplo n.º 21
0
 public static PlatformTimer StartNew(GameContext context, Action<object> callback, object state, TimeSpan dueTime, TimeSpan period)
 {
     var timer = new PlatformTimer(context, callback, state, dueTime, period);
     if (dueTime >= TimeSpan.Zero)
     {
         context.Run(timer);
         timer._attached = true;
     }
     return timer;
 }
Exemplo n.º 22
0
        public void Initialize(GameContext context)
        {
            Texture = context.Content.Load<Texture2D>("Items/BlackHole");
            HalfSize = new Vector2(Texture.Height / 2f, Texture.Height / 2f);

            sourceHole = new Rectangle(0, 0, Texture.Height, Texture.Height);
            sourceCorona1 = new Rectangle(Texture.Height, 0, Texture.Height, Texture.Height);
            sourceCorona2 = new Rectangle(Texture.Height * 2, 0, Texture.Height, Texture.Height);
            center = new Vector2(HalfSize.Y, HalfSize.Y);
        }
Exemplo n.º 23
0
        public void Initialize(GameContext context, int type)
        {
            Texture = context.Content.Load<Texture2D>("Items/IceStar");
            HalfSize = new Vector2(Texture.Height / 2f, Texture.Height / 2f);
            fixedHalfSize = new Vector2((int)HalfSize.X, (int)HalfSize.Y);

            source = new Rectangle(Texture.Height * (type % 4), 0, Texture.Height, Texture.Height);
            sourceCracked = new Rectangle(source.X + 256, 0, source.Width, source.Height);

            IsCracked = false;
        }
Exemplo n.º 24
0
        public void Initialize(GameContext context)
        {
            Texture = context.Content.Load<Texture2D>("Scenes/Levels/ChallengeCompleted");
            HalfSize = new Vector2(Texture.Width / 2f, Texture.Height / 2f);

            animationHandler = new AnimationHandler<int>();
            animationHandler.Animations.Add(0, new Animation(0, 1, TimeSpan.FromSeconds(2.5)));

            Position = new Vector2((int)(Device.HalfWidth - HalfSize.X), -Texture.Height);
            target = Position;
        }
Exemplo n.º 25
0
        public override void Commit(GameContext entireContext)
        {
            var system = entireContext.Systems.Single(x => x.SystemNumber == DestinationPlanetId);

            if (!system.CanBuild)
            {
                return;
            }

            system.City.Add(new Farm());
        }
Exemplo n.º 26
0
 public RenderQueue(GameContext context, 
                    Action<Material> handleEffect,
                    Func<IList<DrawableElement>> getDrawableElements,
                    SceneEffect sceneEffect) : base(context)
 {
     _handleEffect = handleEffect;
     _getDrawableElements = getDrawableElements;
     SceneEffect = sceneEffect;
     IsEnabled = true;
     _device = context.GetService<GraphicsDevice>();
 }
Exemplo n.º 27
0
        public KeyboardHandler(GameContext context)
        {
            IsEnabled = Environment.OSVersion.Platform != PlatformID.Xbox;
            KeyboardState = new Dictionary<Keys, InputState>();

            if (IsEnabled)
            {
                keyboardBuffer = new KeyboardBuffer(context.Game.Window.Handle);
                keyboardBuffer.KeyPress += keyboardBuffer_KeyPress;
                keyboardBuffer.KeyDown += keyboardBuffer_KeyDown;
            }
        }
Exemplo n.º 28
0
 void Awake()
 {
     if (_inst == null)
     {
         _inst = this;
         DontDestroyOnLoad(this);
         init();
     }
     else if(this!=inst)
     {
         Destroy (this.gameObject);
     }
 }
Exemplo n.º 29
0
        public ForwardSceneRenderer(GameContext context, SceneEffect effect, RenderSettings settings) : base(context)
        {
            _device = context.GetService<GraphicsDevice>();
            _sceneEffect = effect;
            RenderSettings = settings;
            _allDrawables = new List<DrawableElement>();
            _initializingDrawables = new List<DrawableElement>();
            _allCameras = new List<Camera>();
            _allLights = new List<Light>();

            _directionalLightShadowMap = new RenderTarget2D(_device, RenderSettings.ShadowMapSize, RenderSettings.ShadowMapSize, false, SurfaceFormat.Single, DepthFormat.Depth24);

            var width = context.ScreenBounds.Width;
            var height = context.ScreenBounds.Height;
            _activeInputSource = new RenderTarget2D(_device, width, height, false, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PlatformContents);
            _activeRenderTarget = new RenderTarget2D(_device, width, height, false, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PlatformContents);

            _shadowCasterQueueSolid = new RenderQueue(context, HandleShadowCasterObjects, GetShadowCasterSceneNodes, _sceneEffect)
            {
                BlendState = BlendState.Opaque,
                DepthStencilState = DepthStencilState.Default,
                RasterizerState = RasterizerState.CullCounterClockwise,
                IsEnabled = true,
                SortNodesBackToFront = false,
            };
            _shadowCasterQueueTransparent = new RenderQueue(context, HandleShadowCasterObjects, GetShadowCasterSceneNodesTransparent, _sceneEffect)
            {
                BlendState = BlendState.AlphaBlend,
                DepthStencilState = DepthStencilState.DepthRead,
                RasterizerState = RasterizerState.CullCounterClockwise,
                IsEnabled = true,
                SortNodesBackToFront = true,
            };

            _renderQueues = new List<RenderQueue>
            {
                new RenderQueue(context, HandleSolidObjects, GetSolidObjects, _sceneEffect)
                {
                    DepthStencilState = DepthStencilState.Default,
                    BlendState = BlendState.Opaque,
                    RasterizerState = RasterizerState.CullCounterClockwise,
                },
                new RenderQueue(context, HandleEffectTransparentObjects, GetTransparentObjects, _sceneEffect)
                {
                    DepthStencilState = DepthStencilState.DepthRead,
                    BlendState = BlendState.AlphaBlend,
                    RasterizerState = RasterizerState.CullCounterClockwise,
                    SortNodesBackToFront = true
                }
            };
        }
Exemplo n.º 30
0
        /// <summary>
        /// Creates an instance of the <see cref="GameMode"/> class and loads the data model.
        /// </summary>
        internal GameMode(GameModeInfo gameModeInfo, GameContext gameContext, FileProvider fileLoader) : base(gameContext)
        {
            GameModeInfo = gameModeInfo;
            FileLoader = fileLoader;

            // only continue if the game mode config file loaded correctly.
            if (GameModeInfo.IsValid)
            {
                MapFragmentManager = new MapFragmentManager(this);
                PokemonFactory = new PokemonFactory(this);
            }

            IsValid = true;
        }
Exemplo n.º 31
0
 internal override BehaviorModule CreateModule(GameObject gameObject, GameContext context)
 {
     return(new MaxHealthUpgrade(gameObject, this));
 }
Exemplo n.º 32
0
        public async Task Random()
        {
            GameContext context = GameContexts.getContext(Context.Guild.Id);

            await ReplyAsync(string.Format("{0} pulled **{1}** with attributes **{2}** and **{3}**", ((IGuildUser)Context.User).Nickname, context.Deck.DrawCharacter(), context.Deck.DrawAttribute(), context.Deck.DrawAttribute()));
        }
Exemplo n.º 33
0
        public async Task Challenge()
        {
            GameContext context = GameContexts.getContext(Context.Guild.Id);

            await ReplyAsync(string.Format("{0} pulled challenge **{1}**", ((IGuildUser)Context.User).Nickname, context.Deck.DrawChallenge()));
        }
 public EnsureNetworkUpdatePrioritySystem(Contexts contexts)
 {
     game = contexts.game;
 }
Exemplo n.º 35
0
 public AddViewSystem(Contexts contexts) : base(contexts.game)
 {
     _gameContext = contexts.game;
 }
Exemplo n.º 36
0
 public CreateMoverSystem(Contexts contexts) : base(contexts.input)
 {
     _context = contexts.game;
 }
Exemplo n.º 37
0
 private void Awake()
 {
     _context = Contexts.sharedInstance.game;
     _context.CreateEntity().AddTickListener(this);
 }
Exemplo n.º 38
0
 public MainFixedControllers(GameContext context)
 {
     
 }
Exemplo n.º 39
0
 public bool CanUse(GameContext context)
 {
     return(this.Animal.Food.OfType <FatToken>().Any() && this.Animal.Food.IsNotEnough);
 }
Exemplo n.º 40
0
        private static async Task <string> update(string payload, Client client, GameContext context)
        {
            UpdateCampaignPayload?message;

            try
            {
                message = JsonConvert.DeserializeObject <UpdateCampaignPayload>(payload, new StringEnumConverter());
            }
            catch
            {
                return("CampaignManager update 5: Invalid JSON.");
            }
            if (message == null)
            {
                return("CampaignManager update 6: Null message.");
            }
            Campaign campaignToUpdate;

            try
            {
                campaignToUpdate = await context.campaigns
                                   .Include(c => c.dungeonMaster)
                                   .SingleAsync(c => c.ID == message.ID);
            }
            catch
            {
                return("CampaignManager update 7: Campaign not found.");
            }
            if (client.user.ID == campaignToUpdate.dungeonMaster.ID)
            {
                campaignToUpdate.name             = message.name;
                campaignToUpdate.log              = message.log;
                campaignToUpdate.turnIndex        = message.turnIndex;
                campaignToUpdate.joinable         = message.joinable;
                campaignToUpdate.maxPlayers       = message.maxPlayers;
                campaignToUpdate.password         = message.password ?? campaignToUpdate.password;
                campaignToUpdate.modificationDate = DateTime.Now;
                context.campaigns.Update(campaignToUpdate);
                await context.SaveChangesAsync();
            }
            else
            {
                return("CampaignManager update 8: You are not the Dungeon Master for this campaign.");
            }
            // We also send a new gameState to the other players (we know it's everyone but the dungeon master)
            List <string> clientIdsToUpdate = new List <string>();

            clientIdsToUpdate.Add(campaignToUpdate.dungeonMaster.ID);
            var charactersInCampaign = await context.characters
                                       .Include(c => c.owner)
                                       .Where(c => c.campaign != null && c.campaign.ID == campaignToUpdate.ID)
                                       .Select(c => c.owner.ID)
                                       .ToListAsync();

            clientIdsToUpdate.Concat(charactersInCampaign);
            foreach (var clientID in clientIdsToUpdate)
            {
                await ClientManager.GetInstance().sendGameState(clientID);
            }
            return(await GameState.gameStateFor(client));
        }
Exemplo n.º 41
0
        private static async Task <string> joinCampaign(string payload, Client client, GameContext context)
        {
            JoinCampaignPayload?message;

            try
            {
                message = JsonConvert.DeserializeObject <JoinCampaignPayload>(payload, new StringEnumConverter());
            }
            catch
            {
                return("CampaignManager joinCampaign 14: Invalid JSON.");
            }
            if (message == null)
            {
                return("CampaignManager joinCampaign 15: Null message.");
            }

            Character?joiningCharacter;

            try
            {
                joiningCharacter = await context.characters.SingleAsync(c => c.ID == message.joiningCharacterID);
            }
            catch
            {
                return("CampaignManager joinCampaign 16: Character not found.");
            }

            if (joiningCharacter.campaign != null)
            {
                return("CampaignManager joinCampaign 17: Character is already a part of a campaign.");
            }

            Campaign?campaignToJoin;

            try
            {
                campaignToJoin = await context.campaigns.SingleAsync(c => c.ID == message.campaignToJoinID);
            }
            catch
            {
                return("CampaignManager joinCampaign 18: Campaign not found.");
            }
            if (!campaignToJoin.joinable)
            {
                return("CampaignManager joinCampaign 19: This campaign is not joinable.");
            }

            if (campaignToJoin.password != null)
            {
                if (campaignToJoin.password != message.password)
                {
                    return("CampaignManager joinCampaign 20: Wrong password.");
                }
            }
            var numOfCharactersInCampaign = await context.characters
                                            .Include(c => c.campaign)
                                            .Where(c =>
                                                   c.campaign != null &&
                                                   c.campaign.ID == campaignToJoin.ID
                                                   )
                                            .CountAsync();

            // If we were to join, would there be too many?
            if (numOfCharactersInCampaign + 1 > campaignToJoin.maxPlayers)
            {
                return("CampaignManager joinCampaign 21: Already full");
            }

            joiningCharacter.campaign  = campaignToJoin;
            joiningCharacter.turnIndex = numOfCharactersInCampaign;
            context.characters.Update(joiningCharacter);
            context.campaigns.Update(campaignToJoin);
            await context.SaveChangesAsync();

            return(await GameState.gameStateFor(client));
        }
Exemplo n.º 42
0
        public static Contract GetValidContractForContractDataAndSystem(this SimGameState simGameState, SimGameState.AddContractData addContractData, StarSystem starSystem)
        {
            Logger.Debug($"[SimGameStateExtensions_GetValidContractForContractDataAndSystem] (addContractData) ContractName: {addContractData.ContractName}, Target: {addContractData.Target}, Employer: {addContractData.Employer}, TargetSystem: {addContractData.TargetSystem}, TargetAlly: {addContractData.TargetAlly}");
            Logger.Debug($"[SimGameStateExtensions_GetValidContractForContractDataAndSystem] starSystem: {starSystem.Name}");
            Logger.Debug($"[SimGameStateExtensions_GetValidContractForContractDataAndSystem] starSystem.Def.SupportedBiomes: {String.Join(", ", starSystem.Def.SupportedBiomes.Select(sb => sb.ToString()))}");

            if (starSystem == null)
            {
                throw new Exception("starSystem is null");
            }

            GameInstance gameInstance = simGameState.BattleTechGame;
            DataManager  dataManager  = simGameState.BattleTechGame.DataManager;
            GameContext  gameContext  = new GameContext(simGameState.Context);

            gameContext.SetObject(GameContextObjectTagEnum.TargetStarSystem, starSystem);

            ContractOverride  contractOverride  = dataManager.ContractOverrides.Get(addContractData.ContractName).Copy();
            ContractTypeValue contractTypeValue = contractOverride.ContractTypeValue;

            FactionValue employer      = string.IsNullOrEmpty(addContractData.Employer) ? FactionEnumeration.GetInvalidUnsetFactionValue() : FactionEnumeration.GetFactionByName(addContractData.Employer);
            FactionValue employersAlly = string.IsNullOrEmpty(addContractData.EmployerAlly) ? FactionEnumeration.GetInvalidUnsetFactionValue() : FactionEnumeration.GetFactionByName(addContractData.EmployerAlly);
            FactionValue target        = string.IsNullOrEmpty(addContractData.Target) ? FactionEnumeration.GetInvalidUnsetFactionValue() : FactionEnumeration.GetFactionByName(addContractData.Target);
            FactionValue targetsAlly   = string.IsNullOrEmpty(addContractData.TargetAlly) ? FactionEnumeration.GetInvalidUnsetFactionValue() : FactionEnumeration.GetFactionByName(addContractData.TargetAlly);
            FactionValue neutralToAll  = string.IsNullOrEmpty(addContractData.NeutralToAll) ? FactionEnumeration.GetInvalidUnsetFactionValue() : FactionEnumeration.GetFactionByName(addContractData.NeutralToAll);
            FactionValue hostileToAll  = string.IsNullOrEmpty(addContractData.HostileToAll) ? FactionEnumeration.GetInvalidUnsetFactionValue() : FactionEnumeration.GetFactionByName(addContractData.HostileToAll);

            if (employer.IsInvalidUnset || target.IsInvalidUnset)
            {
                throw new Exception("ContractData didn't have a valid employerValue and/or targetValue");
            }


            // Get all valid encounters (all contract types) for the requested system
            List <MapAndEncounters> allValidMapAndEncountersForCurrentSystem = MetadataDatabase.Instance.GetReleasedMapsAndEncountersBySinglePlayerProceduralContractTypeAndTags(starSystem.Def.MapRequiredTags, starSystem.Def.MapExcludedTags, starSystem.Def.SupportedBiomes, true);

            // Remove all items that dont have an encounter layer for the requested contract type
            allValidMapAndEncountersForCurrentSystem.RemoveAll(MapAndEncounters => MapAndEncounters.Encounters.All(el => el.ContractTypeValue != contractTypeValue));



            // Debug
            foreach (MapAndEncounters mae in allValidMapAndEncountersForCurrentSystem)
            {
                Logger.Info($"allValidMapAndEncountersForCurrentSystem (Map): {mae.Map.FriendlyName}");
                Logger.Info($"allValidMapAndEncountersForCurrentSystem (Encounters): {String.Join(", ", Array.ConvertAll(mae.Encounters, item => item.FriendlyName))}");
                Logger.Info($"-");
            }

            // @ToDo: Remove Map "mapGeneral_taigaRiver_iTnd" for ContractTypeValue "Rescue" (Broken in Vanilla, no buildings at target zones)
            //if (contractTypeValue.FriendlyName == "Rescue")
            //{
            //    allValidMapAndEncountersForCurrentSystem.RemoveAll(MapAndEncounters => MapAndEncounters.Map.MapID == "mapGeneral_taigaRiver_iTnd");
            //}



            // Get a random item
            Random           random           = new Random();
            MapAndEncounters mapAndEncounters = allValidMapAndEncountersForCurrentSystem.OrderBy(MapAndEncounters => random.NextDouble()).First();



            // Debug
            Logger.Info($"chosenMapAndEncounters (Map): {mapAndEncounters.Map.FriendlyName}");
            Logger.Info($"chosenMapAndEncounters: {String.Join(", ", Array.ConvertAll(mapAndEncounters.Encounters, item => item.FriendlyName))}");



            // Get the matching encounter layers
            List <EncounterLayer_MDD> encounterLayers = new List <EncounterLayer_MDD>();

            foreach (EncounterLayer_MDD encounterLayer in mapAndEncounters.Encounters)
            {
                if (encounterLayer.ContractTypeRow.ContractTypeID == (long)contractTypeValue.ID)
                {
                    encounterLayers.Add(encounterLayer);
                }
            }
            if (encounterLayers.Count <= 0)
            {
                throw new Exception("Map does not contain any encounters of type: " + contractTypeValue.Name);
            }



            // Debug
            foreach (EncounterLayer_MDD elMdd in encounterLayers)
            {
                Logger.Info($"chosenEncounter (Name): {elMdd.FriendlyName}");
                Logger.Info($"chosenEncounter (ContractTypeValue): {elMdd.ContractTypeValue}");
            }



            // Get GUID of a random valid encounter layer
            string encounterLayerGUID = encounterLayers[simGameState.NetworkRandom.Int(0, encounterLayers.Count)].EncounterLayerGUID;


            // Check if we need to travel
            if (addContractData.IsGlobal)
            {
                Logger.Debug($"[SimGameStateExtensions_GetValidContractForContractDataAndSystem] Custom handling of travel contracts isn't implemented. Falling back to default handling");

                // Fallback to relevant part of default vanilla method
                simGameState.AddContract(addContractData);

                //Contract travelContract = simGameState.CreateTravelContract(mapAndEncounters.Map.MapName, mapAndEncounters.Map.MapPath, encounterLayerGUID, contractTypeValue, contractOverride, gameContext, employer, employersAlly, target, targetsAlly, neutralToAll, hostileToAll, addContractData.IsGlobal);
                //simGameState.PrepContract(travelContract, employer, employersAlly, target, targetsAlly, neutralToAll, hostileToAll, mapAndEncounters.Map.BiomeSkinEntry.BiomeSkin, travelContract.Override.travelSeed, starSystem);
                //simGameState.GlobalContracts.Add(travelContract);

                //return travelContract;
            }

            Contract contract = new Contract(mapAndEncounters.Map.MapName, mapAndEncounters.Map.MapPath, encounterLayerGUID, contractTypeValue, gameInstance, contractOverride, gameContext, true, contractOverride.difficulty, 0, null);

            Logger.Debug($"[SimGameStateExtensions_GetValidContractForContractDataAndSystem] Contract: {contract.Override.ID}({contractTypeValue}), Difficulty: {contract.Difficulty}, CanNegotiate: {contract.CanNegotiate}, Biome: {mapAndEncounters.Map.BiomeSkinEntry.Name}, Map: {mapAndEncounters.Map.MapName}");

            simGameState.PrepContract(contract, employer, employersAlly, target, targetsAlly, neutralToAll, hostileToAll, mapAndEncounters.Map.BiomeSkinEntry.BiomeSkin, 0, starSystem);
            // Set negotiations
            if (!contract.CanNegotiate)
            {
                contract.SetNegotiatedValues(contract.Override.negotiatedSalary, contract.Override.negotiatedSalvage);
            }



            return(contract);
        }
Exemplo n.º 43
0
 public StarCollectHandlerSystem(Contexts contexts) : base(contexts.game)
 {
     _gameContext  = contexts.game;
     _inputContext = contexts.input;
 }
Exemplo n.º 44
0
 public void Init(IUnityGridInfoProvider unityGridInfoProvider, IUiFacade uiFacade, IOsnowaContextManager contextManager,
                  ITileByIdProvider tileByIdProvider, IGameConfig gameConfig, IEntityDetector entityDetector, GameContext context)
 {
     _tileByIdProvider      = tileByIdProvider;
     _contextManager        = contextManager;
     _uiFacade              = uiFacade;
     _unityGridInfoProvider = unityGridInfoProvider;
     _gameConfig            = gameConfig;
     _entityDetector        = entityDetector;
     _context = context;
 }
 public InitializeBoardSystem(Contexts contexts) : base(contexts.game)
 {
     _gameContext = contexts.game;
 }
Exemplo n.º 46
0
 public CreateClickCounterSystem(Contexts contexts)
 {
     _gameContext = contexts.game;
 }
Exemplo n.º 47
0
 internal override BehaviorModule CreateModule(GameObject gameObject, GameContext context)
 {
     return(new DestroyDie(gameObject, this));
 }
Exemplo n.º 48
0
 public AgentBehavior(GameContext context, Entity entity, ControllerData controllerData)
 {
     Context        = context;
     Entity         = entity;
     ControllerData = controllerData;
 }
 public TeamRepository(GameContext context)
 {
     _context = context;
 }
 public ParentLinkDeletingSystem(Contexts contexts)
 {
     buffer          = new List <GameEntity>();
     gameContext     = contexts.game;
     withParentGroup = gameContext.GetGroup(GameMatcher.Parent);
 }
Exemplo n.º 51
0
 public TraitAction Use(GameContext context)
 {
     return(new FatTissueAction(this));
 }
Exemplo n.º 52
0
 public DestroyEntitySystem(GameContext context) : base(context)
 {
 }
Exemplo n.º 53
0
 public CollisionSystem(Contexts contexts) : base(contexts.game)
 {
     _context = contexts.game;
     _group   = contexts.game.GetGroup(GameMatcher.Collider);
 }
Exemplo n.º 54
0
 public ReverseTileSystem(Contexts contexts)
 {
     _gameContext = contexts.game;
     _mover       = _gameContext.GetGroup(GameMatcher.MoveBackWithoutMatch);
 }
Exemplo n.º 55
0
 public HealthPackPhysicsComponent(GameContext gameContext, Random random) : base(gameContext)
 {
     _gameContext = gameContext ?? throw new ArgumentNullException(nameof(gameContext));
     _random      = random ?? throw new ArgumentNullException(nameof(random));
 }
        public IActionResult Index()
        {
            ViewData["Account"] = HttpContext.Session.GetString("Account");

            List <RankPlayer> top;

            using (GameContext game = new GameContext())
            {
                var player = (from p in game.Players
                              orderby p.TotalExperience descending
                              select p).Take(50);

                top = new List <RankPlayer>();

                int rank = 1;
                foreach (var p in player)
                {
                    string rLevel = "Benginer";
                    if (p.Level == 0)
                    {
                        rLevel = "Benginer";
                    }
                    else if (p.Level <= 20)
                    {
                        rLevel = "Rookie";
                    }
                    else if (p.Level <= 40)
                    {
                        rLevel = "Semi-Pro";
                    }
                    else if (p.Level <= 80)
                    {
                        rLevel = "Pro";
                    }
                    else if (p.Level <= 120)
                    {
                        rLevel = "S1";
                    }
                    else if (p.Level <= 160)
                    {
                        rLevel = "S2";
                    }
                    else if (p.Level <= 200)
                    {
                        rLevel = "S3";
                    }
                    else if (p.Level <= 240)
                    {
                        rLevel = "S4";
                    }
                    var pp = new RankPlayer()
                    {
                        Id    = p.Id,
                        Rank  = rank,
                        Name  = "",
                        Level = rLevel,
                        Exp   = p.TotalExperience
                    };
                    top.Add(pp);
                }
            }
            using (AuthContext auth = new AuthContext())
            {
                var player = from a in auth.Accounts
                             join p in top on a.Id equals p.Id
                             select new RankPlayer()
                {
                    Id    = p.Id,
                    Rank  = p.Rank,
                    Name  = a.Nickname,
                    Level = p.Level,
                    Exp   = p.Exp
                };
                ViewData["Rank"] = player.ToList();
            }

            return(View());
        }
Exemplo n.º 57
0
 internal override BehaviorModule CreateModule(GameObject gameObject, GameContext context)
 {
     return(new PowerPlantUpgrade(gameObject, this));
 }
Exemplo n.º 58
0
 public GameController(GameContext context, BoardController boardController)
 {
     _context         = context;
     _boardController = boardController;
 }
Exemplo n.º 59
0
 public ShouldDieSystem(Contexts contexts) : base(contexts.game)
 {
     context = contexts.game;
     group   = context.GetGroup(GameMatcher.Dead);
 }
Exemplo n.º 60
0
 public NPC(GameContext Context, int bAddr) : base(Context, bAddr)
 {
 }