public GameUpdate CreateGameUpdate()
        {
            var config = MinecraftCronConfiguration.GetConfiguration();

            var newId = Regex.Replace(this.Id, "[^0-9]", "");

            int.TryParse(newId, out var parsedId);

            var variables = new Dictionary <string, object>
            {
                { "Update", this },
                { "Update.Version", this.Id }
            };

            Console.WriteLine("Name = " + config.VanillaSettings.NameTemplate.ReplaceWithVariables(variables));
            var gameUpdate = new GameUpdate
            {
                Name            = config.VanillaSettings.NameTemplate.ReplaceWithVariables(variables),
                GroupName       = this.Type == "release" ? config.VanillaSettings.Group : config.VanillaSettings.SnapshotGroup,
                WindowsFileName = $"{this.Downloads.Server.Url} minecraft_server.jar",
                LinuxFileName   = $"{this.Downloads.Server.Url} minecraft_server.jar",
                ExtractPath     = "/",
                Reinstallable   = true,
                DefaultInstall  = false,
                GameId          = config.GameId,
                Comments        = config.VanillaSettings.Description.ReplaceWithVariables(variables),
                UserAccess      = true,
                SubAdminAccess  = true,
                ResellerAccess  = true,
                ViewOrder       = config.VanillaSettings.UseVersionAsViewOrder ? parsedId : 0
            };

            gameUpdate.GenerateKey();
            return(gameUpdate);
        }
Exemplo n.º 2
0
 private void InvokeGameUpdate()
 {
     if (GameUpdate != null)
     {
         GameUpdate.Invoke(this, GenerateEventArgs());
     }
 }
Exemplo n.º 3
0
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            var screen = Screen.AllScreens.First(e => e.Primary);

            Window.IsBorderless = true;
            Window.Position     = new Point(screen.Bounds.X, screen.Bounds.Y);
            graphics.PreferredBackBufferWidth  = screen.Bounds.Width;
            graphics.PreferredBackBufferHeight = screen.Bounds.Height;
            graphics.IsFullScreen = true;
            //graphics.ToggleFullScreen();
            //graphics.ApplyChanges();

            Content.RootDirectory = "Content";
            gameDrawStack         = new Stack <GameDraw>();
            gameUpdateStack       = new Stack <GameUpdate>();
            gameDrawStack.Push(StartMenuUpdate);
            gameUpdateStack.Push(StartMenuDraw);
            //gameDrawStack.Enqueue(MainGameUpdate);
            //gameUpdateStack.Enqueue(MainGameDraw);
            gameUpdate   = gameUpdateStack.Peek();
            gameDraw     = gameDrawStack.Peek();
            Actor.Spawn += new EventHandler <SpawnEventArgs>(Actor_Spawn);
            Actor.Use   += new EventHandler <EventArgs>(Actor_Use);
        }
Exemplo n.º 4
0
        public GameUpdate CreateGameUpdate()
        {
            var config = new CronJob().FindByType(typeof(MinecraftVanillaUpdatesCron)).Configuration.Parse <VanillaSettings>();

            var newId = Regex.Replace(this.Id, "[^0-9]", "");

            int.TryParse(newId, out var parsedId);

            var variables = new Dictionary <string, object>
            {
                { "Update", this },
                { "Update.Version", this.Id }
            };

            var gameUpdate = new GameUpdate
            {
                Name            = config.NameTemplate.ReplaceWithVariables(variables),
                GroupName       = config.Group,
                WindowsFileName = $"{this.Downloads.Server.Url} {config.FileName.ReplaceWithVariables(variables)}",
                LinuxFileName   = $"{this.Downloads.Server.Url} {config.FileName.ReplaceWithVariables(variables)}",
                ImageUrl        = config.ImageUrl,
                ExtractPath     = config.ExtractPath,
                Reinstallable   = true,
                DefaultInstall  = false,
                GameId          = config.GameId,
                Comments        = config.Description.ReplaceWithVariables(variables),
                UserAccess      = true,
                SubAdminAccess  = true,
                ResellerAccess  = true,
                ViewOrder       = config.UseVersionAsViewOrder ? parsedId : 0
            };

            gameUpdate.GenerateKey();
            return(gameUpdate);
        }
Exemplo n.º 5
0
        private void mniAddGamez_Click(object sender, RoutedEventArgs e)
        {
            Task.Factory.StartNew(() => Util.NotifyEvent("AddGames"));

            try
            {
                Main main = Util.TryFindParent <Main>(this);

                if (main != null)
                {
                    main.OldSelectedItems = main.SelectedItems;
                    main.SelectedItems    = EntityType.Games;

                    main.OldAction = main.Action;
                    main.Action    = EntityAction.Added;

                    GameUpdate objAdd = new GameUpdate();
                    objAdd.ShowDialog();
                    main.ShowGames(main.Action);
                }
            }
            catch (Exception ex)
            {
                CatchException(ex);
            }
            finally
            {
                Cursor = null;
            }
        }
Exemplo n.º 6
0
        protected override async Task RunInterval()
        {
            await using var conn = await _db.Obtain();

            var sim = await _updateStore.GetLatestUpdate(conn, UpdateType.Sim);

            var(season, dayStart) = (sim.Data.Value <int>("season"), sim.Data.Value <int>("day"));

            var updates = new List <GameUpdate>();

            for (var day = dayStart + 1; day < 100; day++)
            {
                var jsonStr = await _client.GetStringAsync($"https://www.blaseball.com/database/games?season={season}&day={day}");

                var timestamp = _clock.GetCurrentInstant();
                var json      = JArray.Parse(jsonStr);
                _logger.Information("Polled future games at season {Season} day {Day}", season, day);

                updates.AddRange(json.Select(game => GameUpdate.From(_sourceId, timestamp, game)));
            }

            await using (var tx = await conn.BeginTransactionAsync())
            {
                await _gameUpdateStore.SaveGameUpdates(conn, updates);

                await tx.CommitAsync();
            }

            await _gameStore.TryAddNewGameIds(conn, updates.Select(gu => gu.GameId));
        }
Exemplo n.º 7
0
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.SynchronizeWithVerticalRetrace = true;
            var screen = Screen.AllScreens.First(e => e.Primary);
            Window.IsBorderless = true;
            Window.Position = new Point(screen.Bounds.X, screen.Bounds.Y);
            graphics.PreferredBackBufferWidth = screen.Bounds.Width;
            graphics.PreferredBackBufferHeight = screen.Bounds.Height;
            graphics.IsFullScreen = true;
            //graphics.ToggleFullScreen();
            //graphics.ApplyChanges();

            Content.RootDirectory = "Content";
            gameDrawStack = new Stack<GameDraw>();
            gameUpdateStack = new Stack<GameUpdate>();
            gameDrawStack.Push(StartMenuUpdate);
            gameUpdateStack.Push(StartMenuDraw);
            //gameDrawStack.Enqueue(MainGameUpdate);
            //gameUpdateStack.Enqueue(MainGameDraw);
            gameUpdate = gameUpdateStack.Peek();
            gameDraw = gameDrawStack.Peek();
            Actor.Spawn += new EventHandler<SpawnEventArgs>(Actor_Spawn);
            Actor.Use += new EventHandler<EventArgs>(Actor_Use);
            
        }
Exemplo n.º 8
0
        public GameUpdate UpdateGame()
        {
            GameUpdate update = new GameUpdate
            {
                GameId = GameId,
                State  = State,
                Round  = Round,
            };

            update.PlayersState = Players.Select(p =>
            {
                var playerState = new GameUpdate.PlayerState
                {
                    Name     = p.User.UserName,
                    Point    = p.Point,
                    LeftGame = p.LeftGame,
                };
                if (State == GameState.Compare)
                {
                    playerState.Hand = p.PlayerHand;
                }
                return(playerState);
            }).ToList();
            return(update);
        }
Exemplo n.º 9
0
        private async Task <List <GameUpdate> > FetchGamesAt(string sim, int tournament, int season, int day)
        {
            var sw = new Stopwatch();

            sw.Start();

            var cacheBust = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

            var url     = $"https://api.blaseball.com/database/games?season={season}&day={day}&tournament={tournament}&cache={cacheBust}";
            var jsonStr = await _client.GetStringAsync(url);

            sw.Stop();
            var timestamp = _clock.GetCurrentInstant();

            var json  = JArray.Parse(jsonStr);
            var games = json.Where(g => g["sim"].Value <string?>() == sim).ToList();

            var maxPlayCount = games.Count > 0 ? games.Max(t => t["playCount"].Value <int?>() ?? -1) : -1;

            _logger.Information("Polled games endpoint at sim {Sim} season {Season} tournament {Tournament} day {Day} (combined hash {Hash}, max PC {MaxPlayCount}, took {Duration})",
                                sim, season, tournament,
                                day, SibrHash.HashAsGuid(json), maxPlayCount, sw.Elapsed);

            var updates = games
                          .Select(game => GameUpdate.From(_sourceId, timestamp, game))
                          .ToList();

            return(updates);
        }
Exemplo n.º 10
0
        public GameUpdate GetGameUpdate()
        {
            var config = MinecraftCronConfiguration.GetConfiguration();

            var newId = Regex.Replace(this.Version, "[^0-9]", "");

            int.TryParse(newId, out var parsedId);

            var variables = new Dictionary <string, object>
            {
                { "Update", this }
            };

            var gameUpdate = new GameUpdate
            {
                Name            = config.SpigotSettings.NameTemplate.ReplaceWithVariables(variables),
                GroupName       = config.SpigotSettings.Group,
                WindowsFileName = $"{GetDownloadUrl(Version)} minecraft_server.jar",
                LinuxFileName   = $"{GetDownloadUrl(Version)} minecraft_server.jar",
                ExtractPath     = "/",
                Reinstallable   = true,
                DefaultInstall  = false,
                GameId          = config.GameId,
                Comments        = config.SpigotSettings.Description.ReplaceWithVariables(variables),
                UserAccess      = true,
                SubAdminAccess  = true,
                ResellerAccess  = true,
                ViewOrder       = config.SpigotSettings.UseVersionAsViewOrder ? parsedId : 0
            };

            gameUpdate.GenerateKey();
            return(gameUpdate);
        }
Exemplo n.º 11
0
 public IrcBot(Action<Action> pSynchronousInvoker, Controller pController)
 {
     synchronousInvoker = pSynchronousInvoker;
     gs = GameScanner.getInstance();
     gu = new GameUpdate(gs_GameLaunched);
     gs.GameLaunched += gu;
     ctrl = pController;
 }
Exemplo n.º 12
0
 public void ResetToTeamSelect()
 {
     GameUpdate.ClearPlayerSubscriptions();
     GameUpdate.ClearWorldSubscriptions();
     ShowCharacterSelect();
     _gridCamera.FocusPosition(Vector3.zero, CameraModes.MOVING);
     //Camera.main.enabled = true;
 }
Exemplo n.º 13
0
        protected virtual void OnUpdate([NotNull] GameTime gameTime)
        {
            if (!IsDesignMode)
            {
                Guard.ArgumentNotNull(gameTime, nameof(gameTime));

                GameUpdate?.Invoke(this, new TimedEventArgs(gameTime));
            }
        }
Exemplo n.º 14
0
        private void cmdAddGame_Click(object sender, RoutedEventArgs e)
        {
            GameUpdate window = new GameUpdate();

            window.ShowDialog();
            RoutedEventArgs args = new RoutedEventArgs(CmdAddGamesClickEvent);

            RaiseEvent(args);
        }
Exemplo n.º 15
0
        public void Queue_CanPush()
        {
            IGameUpdate o = new GameUpdate {
                IPAddress = "STRING", GameState = "SomeState"
            };

            _queue.Push(o);
            _queue.Size().ShouldBe(1);
        }
Exemplo n.º 16
0
        public void RunLoop()
        {
            GameUpdate update = null;

            while ((update = ServerConnection.ReadUpdate()) != null)
            {
                StateManager.HandleGameUpdate(update);
                ServerConnection.SendCommands(AIStrategy.BuildCommandList());
            }
        }
Exemplo n.º 17
0
        public void TutorialSelected(Object sender, EventArgs eventArgs)
        {
            cam.menuEnabled = false;
            startTutorial();

            gameUpdateStack.Push(MainGameUpdate);
            gameDrawStack.Push(MainGameDraw);
            gameUpdate = gameUpdateStack.Peek();
            gameDraw   = gameDrawStack.Peek();
        }
Exemplo n.º 18
0
 public void CreditsSelected(Object sender, EventArgs eventArgs)
 {
     cam.menuEnabled    = false;
     cam.creditsEnabled = true;
     cam.rollCredits();
     gameUpdateStack.Push(CreditsUpdate);
     gameDrawStack.Push(CreditsDraw);
     gameUpdate = gameUpdateStack.Peek();
     gameDraw   = gameDrawStack.Peek();
     SoundManager.Instance.playSong("creditsTheme");
 }
Exemplo n.º 19
0
        public bool UpdateGame(GameUpdate model)
        {
            using (var ctx = new ApplicationDbContext())
            {
                var entity = ctx.Games.Single(e => e.Id == model.Id);

                entity.Name = model.Name;

                return(ctx.SaveChanges() == 1);
            }
        }
Exemplo n.º 20
0
 public Game1()
 {
     graphics = new GraphicsDeviceManager(this);
     graphics.PreferredBackBufferWidth = 800;
     graphics.PreferredBackBufferHeight = 800;
     graphics.IsFullScreen = false;
     graphics.ApplyChanges();
     Content.RootDirectory = "Content";
     gameUpdate = MainGameUpdate;
     gameDraw = MainGameDraw;
 }
Exemplo n.º 21
0
        public void NewGameSelected(Object sender, EventArgs eventArgs)
        {
            //Console.Write("new game selected");
            cam.menuEnabled = false;
            startNewGame();
            //SoundManager.Instance.stopAllSounds();

            gameUpdateStack.Push(MainGameUpdate);
            gameDrawStack.Push(MainGameDraw);
            gameUpdate = gameUpdateStack.Peek();
            gameDraw   = gameDrawStack.Peek();
        }
Exemplo n.º 22
0
        public static void Secure(Action action)
        {
            GameUpdate update = null;

            update = delegate
            {
                Game.OnUpdate -= update;

                action();
            };

            Game.OnUpdate += update;
        }
Exemplo n.º 23
0
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth  = 800;
            graphics.PreferredBackBufferHeight = 800;
            graphics.IsFullScreen = false;
            graphics.ApplyChanges();
            Content.RootDirectory = "Content";
            gameUpdate            = MainGameUpdate;
            gameDraw = MainGameDraw;

            Actor.Spawn += new EventHandler <SpawnEventArgs>(Actor_Spawn);
        }
Exemplo n.º 24
0
 private void pause_resume_button_Click(object sender, EventArgs e)
 {
     if (pause_resume_button.Text == "Возобновить")
     {
         GameUpdate.Start();
         pause_resume_button.Text = "Пауза";
     }
     else
     {
         GameUpdate.Stop();
         pause_resume_button.Text = "Возобновить";
     }
 }
Exemplo n.º 25
0
 public void CreditsExited(Object sender, EventArgs eventArgs)
 {
     cam.creditsEnabled = false;
     SoundManager.Instance.stopAllSounds();
     cam.enterStartMenu();
     cam.drawSpace.X = 0;
     cam.drawSpace.Y = 0;
     gameUpdateStack.Pop();
     gameDrawStack.Pop();
     gameUpdate = gameUpdateStack.Peek();
     gameDraw   = gameDrawStack.Peek();
     SoundManager.Instance.stopSong("creditsTheme");
 }
Exemplo n.º 26
0
 public void UpdateMoney(GameUpdate update, System.Action OnMoneyUpdated)
 {
     _money.text  = "Money: $" + SessionData.Instance.GetMoney();
     _change.text = "$" + update.coinsAmountChange;
     if (update.drawResult == Result.Draw)
     {
         OnMoneyUpdated();
     }
     else
     {
         _animator.SetTrigger(update.drawResult.ToString());
         StartCoroutine(Common.WaitThenCallAction(Constants.WAIT_TIME, OnMoneyUpdated));
     }
 }
Exemplo n.º 27
0
        public void LoadWorldUpdate(GameTime gameTime)
        {
            while (isLoadingWorld)
            {
                float dt = (gameTime.ElapsedGameTime.Seconds) + (gameTime.ElapsedGameTime.Milliseconds / 1000f);
                //UpdateInput();
                //actorManager.update(dt);
                //UpdateCamera(cam, player);

                base.Update(gameTime);
            }
            gameUpdate = MainGameUpdate;
            gameDraw   = MainGameDraw;
        }
        public IHttpActionResult Put(GameUpdate game)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var service = CreateGameService();

            if (!service.UpdateGame(game))
            {
                return(InternalServerError());
            }
            return(Ok());
        }
Exemplo n.º 29
0
 public void HandleGameUpdate(GameUpdate update)
 {
     if (update.GameInfo != null)
     {
         UpdateGameInfo(update.GameInfo);
     }
     if (update.UnitUpdates != null)
     {
         UpdateUnits(update.UnitUpdates);
     }
     if (update.TileUpdates != null)
     {
         UpdateTiles(update.TileUpdates);
     }
 }
Exemplo n.º 30
0
        public bool UpdateGame(GameUpdate model)
        {
            var entity =
                new Game()
            {
                GameId = model.GameId,
                MinBet = model.MinBet,
                MaxBet = model.MaxBet
            };

            using (var ctx = new ApplicationDbContext())
            {
                ctx.Games.Add(entity);
                return(ctx.SaveChanges() == 1);
            }
        }
Exemplo n.º 31
0
        public void ForceCast(bool packetCast = false)
        {
            GameUpdate update = null;

            update = delegate(EventArgs args)
            {
                if (this.IsReady())
                {
                    this.Cast(packetCast);
                    return;
                }
                Game.OnGameUpdate -= update;
            };
            Game.OnGameUpdate += update;
            Utility.DelayAction.Add(2000, () => Game.OnGameUpdate -= update);
        }
Exemplo n.º 32
0
        public void ForceCast(Vector3 fromPosition, Vector3 toPosition)
        {
            GameUpdate update = null;

            update = delegate(EventArgs args)
            {
                if (this.IsReady())
                {
                    this.Cast(fromPosition, toPosition);
                    return;
                }
                Game.OnGameUpdate -= update;
            };
            Game.OnGameUpdate += update;
            Utility.DelayAction.Add(2000, () => Game.OnGameUpdate -= update);
        }
Exemplo n.º 33
0
        public void Test_HandleGameUpdate()
        {
            var unitManager = new Mock <IUnitManager>();
            var map         = new Mock <IMap>();

            var units  = new List <UnitUpdate>();
            var tiles  = new List <TileUpdate>();
            var update = new GameUpdate();

            update.UnitUpdates = units;
            update.TileUpdates = tiles;

            new GameStateManager(unitManager.Object, map.Object).HandleGameUpdate(update);

            unitManager.Verify(u => u.UpdateUnits(units));
            map.Verify(m => m.UpdateTiles(tiles));
        }
Exemplo n.º 34
0
        public void LoadWorldUpdate(GameTime gameTime)
        {
            while (isLoadingWorld)
            {
                float dt = (gameTime.ElapsedGameTime.Seconds) + (gameTime.ElapsedGameTime.Milliseconds / 1000f);
                //UpdateInput();
                //actorManager.update(dt);
                //UpdateCamera(cam, player);

                base.Update(gameTime);
            }
            gameUpdate = MainGameUpdate;
            gameDraw = MainGameDraw;
        }
Exemplo n.º 35
0
 public void MainGameExited(Object sender, EventArgs eventArgs){
     if(gameUpdateStack.Count > 1)
     {
         paused = false;
         player = null;
         cam.tutorialGui.Clear();
         SoundManager.Instance.stopAllSounds();
         cam.enterStartMenu();
         cam.drawSpace.X = 0;
         cam.drawSpace.Y = 0;
         gameUpdateStack.Pop();
         gameDrawStack.Pop();
         gameUpdate = gameUpdateStack.Peek();
         gameDraw = gameDrawStack.Peek();
         SoundManager.Instance.stopSong("creditsTheme");
     }
     
 }
Exemplo n.º 36
0
    void GameLoop()
    {
        // LobbyPlayer localPlayer = GetLocalPlayer();
        while (game) {
            string incomingMsg = reader.ReadLine();
            Debug.Log (incomingMsg);

            if (incomingMsg.StartsWith("MessageCustom")) {
                Debug.Log("Processing incoming message...");
                waitingForUpdate = false;
                string updateString = incomingMsg.Split(new char[] {'|'}, 2)[1];
                Debug.Log("Interpreting the message...");
                gameUpdate = JSON.JSONReader.ReadUpdate(updateString);
                Debug.Log("GameUpdate is assembled.");
                updateAvailable = true;

                Debug.Log ("NetworkComm: Update available");
            }
        }
        stream.Close();
    }
Exemplo n.º 37
0
        public void NewGameSelected(Object sender, EventArgs eventArgs)
        {
            //Console.Write("new game selected");
            cam.menuEnabled = false;
            startNewGame();
            //SoundManager.Instance.stopAllSounds();

            gameUpdateStack.Push(MainGameUpdate);
            gameDrawStack.Push(MainGameDraw);
            gameUpdate = gameUpdateStack.Peek();
            gameDraw = gameDrawStack.Peek();
        }
Exemplo n.º 38
0
        public void TutorialSelected(Object sender, EventArgs eventArgs)
        {
            cam.menuEnabled = false;
            startTutorial();

            gameUpdateStack.Push(MainGameUpdate);
            gameDrawStack.Push(MainGameDraw);
            gameUpdate = gameUpdateStack.Peek();
            gameDraw = gameDrawStack.Peek();
        }
Exemplo n.º 39
0
 public void CreditsSelected(Object sender, EventArgs eventArgs)
 {
     cam.menuEnabled = false;
     cam.creditsEnabled = true;
     cam.rollCredits();
     gameUpdateStack.Push(CreditsUpdate);
     gameDrawStack.Push(CreditsDraw);
     gameUpdate = gameUpdateStack.Peek();
     gameDraw = gameDrawStack.Peek();
     SoundManager.Instance.playSong("creditsTheme");
 }
Exemplo n.º 40
0
 public void CreditsExited(Object sender, EventArgs eventArgs)
 {
     cam.creditsEnabled = false;
     SoundManager.Instance.stopAllSounds();
     cam.enterStartMenu();
     cam.drawSpace.X = 0;
     cam.drawSpace.Y = 0;
     gameUpdateStack.Pop();
     gameDrawStack.Pop();
     gameUpdate = gameUpdateStack.Peek();
     gameDraw = gameDrawStack.Peek();
     SoundManager.Instance.stopSong("creditsTheme");
 }
Exemplo n.º 41
0
        private void Actor_Use(Object sender, EventArgs eventArgs)
        {
            Actor deadActor = (Actor)sender;
            if (deadActor.className == "player" && deadActor.health <= 0 && gameUpdateStack.Count > 1)
            {
                player = null;
                SoundManager.Instance.stopAllSounds();

                cam.enterStartMenu();
                cam.drawSpace.X = 0;
                cam.drawSpace.Y = 0;
                worldManager.restart();
                gameUpdateStack.Pop();
                gameDrawStack.Pop();
                gameUpdate = gameUpdateStack.Peek();
                gameDraw = gameDrawStack.Peek();
            }
        }
Exemplo n.º 42
0
        private void WorldManager_worldChange(Object sender, EventArgs eventArgs)
        {
            WorldManager worldManager = (WorldManager)sender;
            if (worldManager.curWorld != null && worldManager.curWorld.isTutorial && gameUpdateStack.Count > 1)
            {
                player = null;
                SoundManager.Instance.stopAllSounds();

                cam.enterStartMenu();
                cam.drawSpace.X = 0;
                cam.drawSpace.Y = 0;
                worldManager.restart();
                gameUpdateStack.Pop();
                gameDrawStack.Pop();
                gameUpdate = gameUpdateStack.Peek();
                gameDraw = gameDrawStack.Peek();
            }
        }
Exemplo n.º 43
0
        public void LoadWorldUpdate(GameTime gameTime)
        {
            while (isLoadingWorld)
            {
                // Allows the game to exit
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                    this.Exit();

                float dt = (gameTime.ElapsedGameTime.Seconds) + (gameTime.ElapsedGameTime.Milliseconds / 1000f);
                //UpdateInput();
                //actorManager.update(dt);
                //UpdateCamera(cam, player);

                base.Update(gameTime);
            }
            gameUpdate = MainGameUpdate;
            gameDraw = MainGameDraw;
        }
Exemplo n.º 44
0
        public ActionResult UpdateMain(int id, GameUpdate update)
        {
            try
            {
                DateTime start = DateTime.Now;
                Table table = db.Tables.Find(id);
                Seat currentSeat = table.Seats.ElementAt(update.playerIndex);
                if (currentSeat.Player.Name != User.Identity.Name)
                    return RedirectToAction("Index","Home");

                PythonScriptEngine.InitScriptEngine(table.Alpha || table.SoloPlayTest);
                PythonScriptEngine.LoadModules(table.Version.ModuleName, table.Version.PythonScript, table.Alpha || table.SoloPlayTest,table.Version.GameVersionID);

                ScriptScope runScope = PythonScriptEngine.GetScope(table.Alpha || table.SoloPlayTest);
                runScope.ImportModule("cPickle");

                string init_pickledState = Compression.DecompressStringState(table.GameState);
                DateTime modulesLoaded = DateTime.Now;

                // PYTHON UPDATE

                // Input state
                runScope.SetVariable("inputState", init_pickledState);
                runScope.SetVariable("update", update);
                // Input array of seats.
                Seat[] seatsArray = table.Seats.ToArray();
                runScope.SetVariable("seats", seatsArray);

                DateTime variablesSet = DateTime.Now;
                List<bool> previousWaitingStates = seatsArray.Select(s => s.Waiting).ToList();
                string errorString = PythonScriptEngine.RunCode(runScope, "gameState = cPickle.loads(inputState);gameState.update(update);gameState.set_waiting_status(seats);game_over = gameState.game_over;finalState = cPickle.dumps(gameState)", table.Alpha || table.SoloPlayTest);
                if (errorString != "")
                    return Content(errorString);

                for(int i =0; i < seatsArray.Length; i++)
                {
                    NotificationsHub.UpdateNotificationState(db, seatsArray[i], table, previousWaitingStates[i]);

                }

                string final_pickledState = runScope.GetVariable("finalState");
                bool game_over = runScope.GetVariable("game_over");
                if (game_over == true)
                {
                    if (table.TableState != (int)TableState.Complete && table.Version.DevStage == "Release")
                    {
                        table.Game.CompletedGames++;
                        // Log player wins/losses
                        foreach (Seat s in table.Seats)
                        {
                            Player p = s.Player;
                            if (p.Records == null) p.Records = new List<Record>();
                            // Find record if it exists. Otherwise create one.
                            Record r = p.Records.FirstOrDefault(record => record.GameId == table.GameId);
                            if (r == null)
                            {
                                r = new Record();
                                r.GameId = table.GameId;
                                r.PlayerId = p.PlayerID;
                                p.Records.Add(r);
                            }
                            if (table.Ranked == true)
                            {
                                r.RankedGamesPlayed++;
                                if (s.Result == "Win")
                                    r.RankedWins++;
                                if (s.Result == "Loss")
                                    r.RankedLosses++;
                                if (s.Result == "Draw")
                                    r.RankedDraws++;
                            }
                            else
                            {
                                r.GamesPlayed++;
                                if (s.Result == "Win")
                                    r.Wins++;
                                if (s.Result == "Loss")
                                    r.Losses++;
                                if (s.Result == "Draw")
                                    r.Draws++;
                            }

                        }
                        // Game just ended. Collect stats.
                        errorString = PythonScriptEngine.RunCode(runScope, "from encodings import hex_codec; import json; stats = json.dumps(gameState.stats())", table.Alpha || table.SoloPlayTest);
                        if (errorString != "")
                            return Content(errorString);
                        String latestStats = runScope.GetVariable("stats");
                        if (table.Version.StatLog == "" || table.Version.StatLog == null)
                            table.Version.StatLog = "[]";
                        table.Version.StatLog = table.Version.StatLog.Remove(table.Version.StatLog.Length - 1);
                        if (table.Version.StatLog.Length > 1)
                            table.Version.StatLog += ",";
                        table.Version.StatLog += latestStats + "]";

                        // Notify players of game end.
                        foreach (Seat s in seatsArray)
                        {
                            Notification existingNotification = db.Notifications.SingleOrDefault(n => n.PlayerID == s.PlayerId && n.TableID == id);
                            if (existingNotification != null)
                            {
                                existingNotification.Suppressed = false;
                                if(s.PlayerId==currentSeat.PlayerId)
                                    existingNotification.Read = true;
                                else
                                    existingNotification.Read = false;
                                SeatViewModel viewModel = new SeatViewModel(s);
                                existingNotification.Message = "Game Over! ";
                                if (s.Result == "Win")
                                    existingNotification.Message = "Victory! ";
                                if(s.Result == "Loss")
                                    existingNotification.Message = "Defeat! ";
                                if (s.Result == "Draw")
                                    existingNotification.Message = "Draw! ";
                                existingNotification.Message += table.Game.Name + " game with " + viewModel.formattedOpponentNames + " has ended. (TableID:" + table.TableID + ") " + DateTime.Now;
                                db.SaveChanges();
                            }
                        }

                    }
                    table.TableState = (int)TableState.Complete;
                }
                table.GameState = Compression.CompressStringState(final_pickledState);

                DateTime scriptsExecuted = DateTime.Now;

                db.SaveChanges();

                DateTime databaseSaved = DateTime.Now;

                // Send updated states to clients
                IConnectionManager connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
                dynamic clients = connectionManager.GetClients<GameList>();
                for (int i = 0; i < table.Seats.Count; i++)
                {
                    Seat s = table.Seats.ElementAt(i);
                    if (table.SoloPlayTest == false || s.Waiting == true)
                    {
                        Tuple<string,string> viewInfo = GetPythonView(table, final_pickledState, i,false);
                        if(viewInfo.Item2 != "")
                            return Content(viewInfo.Item2);
                        clients["GAME_"+s.Player.Name + id].main_updateGameState(viewInfo.Item1);
                    }
                }
                DateTime end = DateTime.Now;
                TimeSpan totalTime = end.Subtract(start);
                TimeSpan moduleLoadTime = modulesLoaded.Subtract(start);
                TimeSpan variablesSetTime = variablesSet.Subtract(modulesLoaded);
                TimeSpan scriptsExecutedTime = scriptsExecuted.Subtract(variablesSet);
                TimeSpan databaseSavedTime = databaseSaved.Subtract(scriptsExecuted);
                TimeSpan updateTime = end.Subtract(databaseSaved);
                return View();
            }
            catch (Exception e)
            {
                return Content(e.ToString());
            }
        }
Exemplo n.º 45
0
 public GameSettings(double fps, double renderFPS, GameUpdate update, GameDraw draw)
 {
     FPS = fps;
     RenderFPS = renderFPS;
     OnGameDraw = draw;
     OnGameUpdate = update;
 }