예제 #1
0
        public void CommandUnban(MiNET.Player player, string playerName)
        {
            if (!(player is SkyPlayer skyPlayer) || !skyPlayer.PlayerGroup.IsAtLeast(PlayerGroup.Mod))
            {
                player.SendMessage("§c§l(!)§r §cYou do not have permission for this command.");
                return;
            }

            RunnableTask.RunTask(() =>
            {
                string targetXuid = StatisticsCore.GetXuidForPlayername(playerName);
                if (targetXuid == null)
                {
                    player.SendMessage($"§f[PUNISH] §7{playerName} §cis not a Skytonia user.");
                    return;
                }

                if (PunishCore.GetPunishmentsFor(targetXuid).RemoveActive(PunishmentType.Ban))
                {
                    player.SendMessage($"§f[PUNISH] §7{playerName} §chas been unbanned.");
                }
                else
                {
                    player.SendMessage($"§f[PUNISH] §7{playerName} §cis not currently banned.");
                }
            });
        }
예제 #2
0
        public void OnDisable()
        {
            IsDisabled = true;

            if (!GameType.Equals("hub"))
            {
                foreach (Level level in Server.LevelManager.Levels)
                {
                    foreach (MiNET.Player player in level.Players.Values)
                    {
                        ExternalGameHandler.AddPlayer(player as SkyPlayer, "hub");
                    }
                }

                Thread.Sleep(1000);
            }

            foreach (Level level in Server.LevelManager.Levels)
            {
                foreach (MiNET.Player player in level.Players.Values)
                {
                    player.Disconnect("                      §d§lSkytonia §f§lNetwork§r\n" +
                                      "§7Skytonia is currently rebooting, try joining again soon!");
                }
            }

            RunnableTask.CancelAllTasks();

            PunishCore.Close();
            StatisticsCore.Close();
        }
예제 #3
0
        public void CommandKick(MiNET.Player player, string playerName, string[] reason)
        {
            if (!(player is SkyPlayer skyPlayer) || !skyPlayer.PlayerGroup.IsAtLeast(PlayerGroup.Helper))
            {
                player.SendMessage("§c§l(!)§r §cYou do not have permission for this command.");
                return;
            }

            RunnableTask.RunTask(() =>
            {
                string targetXuid = StatisticsCore.GetXuidForPlayername(playerName);
                if (targetXuid == null)
                {
                    player.SendMessage($"§f[PUNISH] §7{playerName} §cis not a Skytonia user.");
                    return;
                }

                string punishReason = GetReasonFromArgs(reason);

                PunishCore.AddKick(targetXuid, punishReason, player.CertificateData.ExtraData.Xuid);

                SkyPlayer target = SkyCoreAPI.Instance.GetPlayer(playerName);
                target?.Disconnect($"§cYou have been kicked from the server.\n" +
                                   $"§6Reason: {punishReason}");

                player.SendMessage($"§f[PUNISH] §7{playerName} §chas been kicked for: §f\"{punishReason}\"");
            });
        }
예제 #4
0
 public WorkerTask(RunnableTask task, WorkFinishedHandler handler, params object[] args)
 {
     this.Task = task;
     this.Arguments = args;
     if (handler!=null)
         this.WorkFinished += handler;
 }
예제 #5
0
        public HubLevel(SkyCoreAPI plugin, string gameId, string levelPath, GameLevelInfo gameLevelInfo, bool modifiable = false) :
            base(plugin, "hub", gameId, levelPath, gameLevelInfo, modifiable)
        {
            AddPendingTask(() =>
            {
                PlayerLocation portalInfoLocation = new PlayerLocation(256.5, 79.5, 276.5);

                const string hologramContent = "  §d§lSkytonia§r §f§lNetwork§r" + "\n" +
                                               " §7Enter the portal and§r" + "\n" +
                                               "§7enjoy your adventure!§r" + "\n" +
                                               "     §ewww.skytonia.com§r";

                new Hologram(hologramContent, this, portalInfoLocation).SpawnEntity();

                RunnableTask.RunTaskLater(() =>
                {
                    try
                    {
                        PlayerNPC.SpawnAllHubNPCs(this);

                        //SpawnHubMaps();
                    }
                    catch (Exception e)
                    {
                        BugSnagUtil.ReportBug(e, this);
                    }
                }, 250);
            });
        }
예제 #6
0
        private WorkerWindow(RunnableTask task, params object[] args)
        {
            InitializeComponent();
            this.task = task;
            this.args = args;

            this.worker = new BackgroundWorker();
            this.worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            this.WorkFinished += WorkerWindow_WorkFinished;
        }
예제 #7
0
        //

        public void OnEnable(PluginContext context)
        {
            context.PluginManager.LoadCommands(new SkyCommands(this));      //Initialize Generic Commands
            context.PluginManager.LoadCommands(Permissions);                //Initialize Permission Commands
            context.PluginManager.LoadCommands(new GameCommands());         //Initialize GameController Commands (/gameedit)
            context.PluginManager.LoadCommands(new Whitelist());            //Initialize Whitelist Commands (/whitelist)

            //Register listeners
            context.Server.PlayerFactory.PlayerCreated += (sender, args) =>
            {
                _shouldSchedule = false;         //Avoid scheduling pending tasks once a player has joined

                MiNET.Player player = args.Player;

                player.PlayerLeave += OnPlayerLeave;

                if (_pendingTasks.Count > 0)
                {
                    foreach (PendingTask pendingTask in _pendingTasks)
                    {
                        RunnableTask.RunTaskLater(() =>
                        {
                            try
                            {
                                pendingTask.Invoke();
                            }
                            catch (Exception e)
                            {
                                BugSnagUtil.ReportBug(e, new AnonMetadatable((metadata) =>
                                {
                                    metadata.AddToTab("PendingTask", "Target", pendingTask.Target);
                                    metadata.AddToTab("PendingTask", "Method", pendingTask.Method);
                                }));
                            }
                        }, 5000);
                    }

                    _pendingTasks.Clear();
                }
            };

            //Trigger any post-launch tasks that cannot be run during startup
            foreach (GameController coreGameController in GameModes.Values)
            {
                coreGameController.PostLaunchTask();
            }

            //Start RestartHandler for Automatic Reboots
            RestartHandler.Start();

            SkyUtil.log("Initialized!");
        }
예제 #8
0
        static PunishCore()
        {
            SkyCoreAPI.Instance.Server.PluginManager.LoadCommands(new PunishmentCommands());              //Initialize Punishment Commands

            RunnableTask.RunTask(() =>
            {
                //TODO: Remove

                /*new DatabaseAction().Query(
                 *      "DROP TABLE `punishments`;",
                 *      null, null, null);*/

                //TODO: Un-delay once db is finalized
                RunnableTask.RunTaskLater(() =>
                {
                    new DatabaseAction().Query(
                        "CREATE TABLE IF NOT EXISTS `punishments` (\n" +
                        "`player_xuid`       varchar(50) NOT NULL,\n" +
                        "`punish_type`       ENUM\n" +
                        "					 ('Ban', 'Kick', 'Mute') DEFAULT 'Ban' NOT NULL,\n"+
                        "`issuer`			 varchar(50) NOT NULL,\n"+                                              //Issuer XUID
                        "`reason`			 varchar(128),\n"+
                        "`active`			 BOOLEAN,\n"+
                        "`duration_amount`	 TINYINT(1) UNSIGNED DEFAULT 0,\n"+                                      //0-255 possible units
                        "`duration_unit`  	 ENUM\n"+
                        "					 ('minutes', 'Hours', 'Days', 'Weeks', 'Months', 'Years', 'Permanent') DEFAULT 'Permanent' NOT NULL,\n"+
                        "`issue_time`        DATETIME(1) NOT NULL,\n" +
                        " PRIMARY KEY(`player_xuid`, `punish_type`, `issue_time`)\n" +
                        ");",
                        null, null, null);
                }, 1000);
            });

            /*
             * Loops through all players and ensures active punishments
             * are actually active.
             *
             * (Active is a boolean, separate from the Expiry DateTime)
             */
            PunishmentUpdateThread = new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                while (!SkyCoreAPI.IsDisabled)
                {
                    Thread.Sleep(60000);                     //60 Second Delay

                    RunUpdateTask();
                }
            });
            PunishmentUpdateThread.Start();
        }
예제 #9
0
        public void CommandMute(MiNET.Player player, string playerName, params string[] args)
        {
            if (!(player is SkyPlayer skyPlayer) || !skyPlayer.PlayerGroup.IsAtLeast(PlayerGroup.Helper))
            {
                player.SendMessage("§c§l(!)§r §cYou do not have permission for this command.");
                return;
            }

            RunnableTask.RunTask(() =>
            {
                RunPunishmentCommand(player, PunishmentType.Mute, playerName, args);
            });
        }
예제 #10
0
        //

        static PlayerGroup()
        {
            RunnableTask.RunTask(() =>
            {
                new DatabaseAction().Query(
                    "CREATE TABLE IF NOT EXISTS `player_groups` (\n" +
                    "`player_xuid`       varchar(50),\n" +
                    "`group_name`        varchar(50),\n" +
                    " PRIMARY KEY(`player_xuid`)\n" +
                    ");",
                    null, null, null);
            });
        }
예제 #11
0
        public static void Start()
        {
            if (Timer != null)
            {
                throw new Exception("RestartHandler already running!");
            }

            RunnableTask.RunTask(() =>
            {
                var autoEvent = new AutoResetEvent(false);

                Timer = new Timer(RestartTask.RestartTick, autoEvent, 1000, 1000);

                autoEvent.WaitOne();

                TriggerReboot();
            });
        }
예제 #12
0
        public void InitializeNewGame()
        {
			RunnableTask.RunTask(() =>
			{
				lock (GameLevels)
				{
					if (GameLevels.Count >= MaxGames)
					{
						return; //Cannot create any more games.
					}

					GameLevel gameLevel = _initializeNewGame();

					if (gameLevel != null)
					{
						GameLevels.TryAdd(gameLevel.GameId, gameLevel);
					}
				}
			});
		}
예제 #13
0
        static StatisticsCore()
        {
            RunnableTask.RunTask(() =>
            {
                new DatabaseAction().Query(
                    "CREATE TABLE IF NOT EXISTS `player_info` (\n" +
                    "`player_xuid`       varchar(32),\n" +
                    "`current_name`      varchar(16),\n" +
                    "PRIMARY KEY(`player_xuid`)\n" +
                    ");",
                    null, null, null);

                new DatabaseAction().Query(
                    "CREATE TABLE IF NOT EXISTS `player_global_stats` (\n" +
                    "`player_xuid`       varchar(32),\n" +
                    "`first_join`        DATETIME(1) NOT NULL,\n" +
                    "`experience`        INT(4) DEFAULT 0,\n" +
                    "`coins`             INT(4) DEFAULT 0,\n" +
                    "PRIMARY KEY(`player_xuid`)\n" +
                    ");",
                    null, null, null);
            });

            StatisticUpdateThread = new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                while (!SkyCoreAPI.IsDisabled)
                {
                    Thread.Sleep(15000);                     //15 Second Delay

                    RunUpdateTask();
                }
            });
            StatisticUpdateThread.Start();
        }
예제 #14
0
        public override void InitializePlayer()
        {
            if (_hasJoined)
            {
                return;
            }

            try
            {
                if (CertificateData.ExtraData.Xuid == null)
                {
                    Disconnect("§cAn §2§lXBOX§r §caccount required to login to §dSkytonia §eNetwork");
                    return;
                }

                if (Whitelist.IsEnabled() && !Whitelist.OnWhitelist(Username))
                {
                    Disconnect(Whitelist.GetWhitelistMessage());
                    return;
                }

                StatisticsCore.AddPlayer(CertificateData.ExtraData.Xuid, Username);

                //Sync retrieve any active punishments
                PlayerPunishments playerPunishments = PunishCore.GetPunishmentsFor(CertificateData.ExtraData.Xuid);
                Punishment        activePunishment  = playerPunishments.GetActive(PunishmentType.Ban);
                if (activePunishment != null)
                {
                    Disconnect("§cYou are currently banned from the §dSkytonia §eNetwork\n" +
                               $"§c({PunishmentMessages.GetNeatExpiryForPunishment(activePunishment)})\n" +
                               $"§cReason: {activePunishment.PunishReason}");
                    return;
                }

                BarHandler = new BarHandler(this);

                SetPlayerGroup(PlayerGroup.Player);

                _hasJoined = true;

                RunnableTask.RunTask(() =>
                {
                    new DatabaseAction().Query(
                        "SELECT `group_name` FROM player_groups WHERE `player_xuid`=@id",
                        (command) =>
                    {
                        command.Parameters.AddWithValue("@id", CertificateData.ExtraData.Xuid);
                    },
                        (reader) =>
                    {
                        PlayerGroup.ValueOf(reader.GetString(0), out var playerGroup);

                        if (playerGroup == null)
                        {
                            //Simply set, then update perms in the post-delegate
                            playerGroup = PlayerGroup.Player;
                        }

                        PlayerGroup = playerGroup;
                    },
                        new Action(delegate
                    {
                        //Update permission levels
                        SetPlayerGroup(PlayerGroup);

                        _isRankLoaded = true;
                        //SkyUtil.log($"Initialized as {PlayerGroup.GroupName}({CommandPermission})");

                        SetGameMode(GameMode.Adventure);

                        if (SkyCoreApi.GameType.Equals("hub") && PlayerGroup.IsAtLeast(PlayerGroup.Mvp))
                        {
                            SetAllowFly(true);
                        }

                        foreach (Action action in _postLoginActions)
                        {
                            action.Invoke();
                        }
                        _postLoginActions.Clear();

                        if (Username.Equals("OhBlihv") || Username.Equals("Erazeo"))
                        {
                            if (PlayerGroup != PlayerGroup.Admin)
                            {
                                SetPlayerGroup(PlayerGroup.Admin);
                                //SkyUtil.log($"Overriding {Username}'s group to Admin");
                            }
                        }

                        RunnableTask.RunTaskLater(() =>
                        {
                            SendTitle("§f", TitleType.Clear);
                            SendTitle("§f", TitleType.AnimationTimes, 6, 6, 20 * 10);
                            SendTitle("§f", TitleType.ActionBar, 6, 6, 20 * 10);
                            SendTitle("§f", TitleType.Title, 6, 6, 20 * 10);
                            SendTitle("§f", TitleType.SubTitle, 6, 6, 20 * 10);
                        }, 500);

                        //Traditional Loading

                        IsSpawned = true;

                        //Should already be in a 'GameLevel'.
                        //Check and force-spawn them in if they're missing.
                        if (Level is GameLevel level && !level.PlayerTeamDict.ContainsKey(Username))
                        {
                            level.AddPlayer(this);
                        }

                        GameInfo targetedGame = ExternalGameHandler.GetGameForIncomingPlayer(Username);
                        if (targetedGame != null && (!(Level is GameLevel) || !((GameLevel)Level).GameId.Equals(targetedGame.GameId)))
                        {
                            SkyCoreApi.GameModes[SkyCoreApi.GameType].InstantQueuePlayer(this, targetedGame);
                        }

                        //Search this players pending groups
                        new DatabaseAction().Query(
                            "SELECT `group_name` FROM player_pending_groups WHERE `player_name`=@name",
                            (command) => { command.Parameters.AddWithValue("@name", Username); },
                            (reader) =>
                        {
                            PlayerGroup.ValueOf(reader.GetString(0), out var playerGroup);

                            if (playerGroup == null)
                            {
                                return;
                            }

                            SetPlayerGroup(playerGroup);

                            new DatabaseAction().Execute(
                                "DELETE FROM player_pending_groups WHERE `player_name`=@name",
                                (command) => { command.Parameters.AddWithValue("@name", Username); },
                                null);

                            new DatabaseAction().Execute(
                                "INSERT INTO `player_groups`\n" +
                                "  (`player_xuid`, `group_name`)\n" +
                                "VALUES\n" +
                                "  (@xuid, @group)\n" +
                                "ON DUPLICATE KEY UPDATE\n" +
                                "  `player_xuid`    = VALUES(`player_xuid`),\n" +
                                "  `group_name`     = VALUES(`group_name`);",
                                (command) =>
                            {
                                command.Parameters.AddWithValue("@xuid", CertificateData.ExtraData.Xuid);
                                command.Parameters.AddWithValue("@group", PlayerGroup.GroupName);
                            },
                                null
                                );
                        },
                            null);
                    })
                        );
                });

                //Initialize once we've loaded the group etc.
                base.InitializePlayer();
            }
예제 #15
0
        public void CommandPermSet(MiNET.Player player, string targetName, string targetGroupName)
        {
            if (!(player is SkyPlayer skyPlayer) || !skyPlayer.PlayerGroup.IsAtLeast(PlayerGroup.Admin))
            {
                player.SendMessage("§c§l(!)§r §cYou do not have permission for this command.");
                return;
            }

            if (String.IsNullOrEmpty(targetName))
            {
                player.SendMessage($"{ChatColors.Red}Enter a valid player name.");
                return;
            }

            SkyPlayer target = _skyCoreApi.GetPlayer(targetName);

            if (target == null || !target.IsConnected)
            {
                player.SendMessage($"{ChatColors.Red}Target player is not online.");
                return;
            }

            //Format as our Enums
            targetGroupName = targetGroupName.ToLower();
            targetGroupName = Char.ToUpper(targetGroupName.ToCharArray()[0]) + targetGroupName.Substring(1);

            if (!PlayerGroup.ValueOf(targetGroupName, out var targetGroup))
            {
                player.SendMessage($"{ChatColors.Red}Unrecognized group name '{targetGroupName}'.");
                string possibleGroups = "";
                foreach (PlayerGroup groupLoop in PlayerGroup.Values)
                {
                    possibleGroups += groupLoop.GroupName + ",";
                }

                player.SendMessage($"Possible Groups: {possibleGroups}");
                return;
            }

            target.SetPlayerGroup(targetGroup);

            RunnableTask.RunTask(() =>
            {
                new DatabaseAction().Execute(
                    "INSERT INTO `player_groups`\n" +
                    "  (`player_xuid`, `group_name`)\n" +
                    "VALUES\n" +
                    "  (@xuid, @group)\n" +
                    "ON DUPLICATE KEY UPDATE\n" +
                    "  `player_xuid`    = VALUES(`player_xuid`),\n" +
                    "  `group_name`     = VALUES(`group_name`);",
                    (command) =>
                {
                    command.Parameters.AddWithValue("@xuid", target.CertificateData.ExtraData.Xuid);
                    command.Parameters.AddWithValue("@group", targetGroup.GroupName);
                },
                    new Action(delegate
                {
                    player.SendMessage($"{ChatColors.Yellow}Updated {target.Username}'s group to {targetGroup.GroupName}");
                })
                    );
            });
        }
예제 #16
0
        public override void InitializePlayer(GameLevel gameLevel, SkyPlayer player)
        {
            if (!player.Effects.ContainsKey(EffectType.NightVision))
            {
                NightVision nightVision = new NightVision
                {
                    Duration  = int.MaxValue,
                    Level     = 0,
                    Particles = false
                };
                player.SetEffect(nightVision);
            }

            if (!(player.Inventory.Slots[4] is ItemNavigationCompass))
            {
                player.Inventory.SetInventorySlot(4, new ItemNavigationCompass());

                //Wait until the compass has appeared to change held slots
                RunnableTask.RunTaskLater(() =>
                {
                    player.Inventory.SetHeldItemSlot(4);
                }, 500);
            }

            /*try
             * {
             *      ISet<long> mapIds = MapUtil.GetLevelMapIds(gameLevel);
             *      if (mapIds == null)
             *      {
             *              SkyUtil.log(
             *                      $"Attempted to respawn missing maps for {player.Username}, but no maps were registered for {gameLevel.GameId}");
             *      }
             *      else
             *      {
             *              RunnableTask.RunTaskLater(() =>
             *              {
             *                      //Murder one as example
             *                      Block block = gameLevel.GetBlock(new BlockCoordinates(260, 77, 270));
             *
             *                      var message = McpeUpdateBlock.CreateObject();
             *                      message.blockId = block.Id;
             *                      message.coordinates = block.Coordinates;
             *                      message.blockMetaAndPriority = (byte)(0xb << 4 | (block.Metadata & 0xf));
             *                      player.SendPackage(message);
             *
             *                      /*MapUtil.SpawnMapImage(@"C:\Users\Administrator\Desktop\dl\map-images\comingsoonmapimage.png", 1, 1, this,
             *                              new BlockCoordinates(249, 77, 268), MapUtil.MapDirection.West);
             *                      MapUtil.SpawnMapImage(@"C:\Users\Administrator\Desktop\dl\map-images\buildbattlemapimage.png", 1, 1, this,
             *                              new BlockCoordinates(252, 77, 270), MapUtil.MapDirection.West);
             *                      MapUtil.SpawnMapImage(@"C:\Users\Administrator\Desktop\dl\map-images\murdermapimage.png", 1, 1, this,
             *                              new BlockCoordinates(260, 77, 270), MapUtil.MapDirection.West);
             *                      MapUtil.SpawnMapImage(@"C:\Users\Administrator\Desktop\dl\map-images\comingsoonmapimage.png", 1, 1, this,
             *                              new BlockCoordinates(263, 77, 268), MapUtil.MapDirection.West);#1#
             *
             *                      /*foreach (long mapEntityId in mapIds)
             *                      {
             *                              if (gameLevel.GetEntity(mapEntityId) is MapEntity mapEntity)
             *                              {
             *                                      player.SendPackage(((MapImageProvider)mapEntity.ImageProvider).Batch);
             *                              }
             *                      }#1#
             *              }, 1000);
             *      }
             * }
             * catch (Exception e)
             * {
             *      Console.WriteLine(e);
             * }*/
        }
예제 #17
0
 public WorkerWindow(Window owner, RunnableTask task, WorkFinishedHandler workFinishedHandler, params object[] args)
     : this(task, workFinishedHandler, args)
 {
     if (owner != this)
         this.Owner = owner;
 }
예제 #18
0
 public WorkerWindow(RunnableTask task, WorkFinishedHandler workFinishedHandler, params object[] args)
     : this(task, args)
 {
     if (workFinishedHandler!=null)
         this.WorkFinished += workFinishedHandler;
 }
예제 #19
0
        public override bool DoInteractAtEntity(GameLevel gameLevel, int interactId, SkyPlayer player, SkyPlayer target)
        {
            MurderLevel murderLevel = (MurderLevel)gameLevel;
            Item        itemInHand  = player.Inventory.GetItemInHand();

            if (player == murderLevel.Murderer && itemInHand is ItemMurderKnife && target != null)
            {
                KillPlayer((MurderLevel)gameLevel, target);
                player.Inventory.SetInventorySlot(0, new ItemMurderKnife());                 //Update Knife
            }
            //Left click only (Right click charges up)
            else if (interactId != 2 && itemInHand is ItemInnocentGun && PlayerAmmoCounts[player.Username] > 0)
            {
                if (player.Experience > 0.05f)
                {
                    return(true);
                }

                var arrow = new GunProjectile(player, gameLevel)
                {
                    Damage        = 0,
                    KnownPosition = (PlayerLocation)player.KnownPosition.Clone()
                };
                arrow.KnownPosition.Y += 1.62f;

                arrow.Velocity            = arrow.KnownPosition.GetHeadDirection() * (2 * 2.0f * 1.5f);
                arrow.KnownPosition.Yaw   = (float)arrow.Velocity.GetYaw();
                arrow.KnownPosition.Pitch = (float)arrow.Velocity.GetPitch();
                arrow.BroadcastMovement   = true;
                arrow.DespawnOnImpact     = true;
                arrow.SpawnEntity();

                int currentAmmo = --PlayerAmmoCounts[player.Username];
                if (currentAmmo <= 0)
                {
                    player.Inventory.SetInventorySlot(0, new ItemAir());                     //Remove Gun
                }
                else
                {
                    //Ensure the gun is updated to a 'ItemInnocentGun' rather than an ItemBow
                    RunnableTask.RunTaskLater(() => player.Inventory.SetInventorySlot(0, new ItemInnocentGun()), 50);
                }

                const float levelOneFullBarXp = 6.65f;

                player.Experience = 0;
                player.AddExperience(levelOneFullBarXp);

                player.Inventory.SetInventorySlot(9, new ItemAir());

                const int updateTicks = 60;
                const int timerMillis = 50;
                RunnableTask.RunTaskTimer(() =>
                {
                    player.AddExperience(-(levelOneFullBarXp / updateTicks));

                    if (currentAmmo > 0 && player.Experience <= 0.1)
                    {
                        player.Inventory.SetInventorySlot(9, new ItemArrow());
                    }
                }, timerMillis, updateTicks + 2);
            }

            return(true);
        }
예제 #20
0
        public override void EnterState(GameLevel gameLevel)
        {
            base.EnterState(gameLevel);

            GunPartLocations.Clear();
            PlayerSpawnLocations.Clear();

            GunPartLocations.AddRange(((MurderLevelInfo)((MurderLevel)gameLevel).GameLevelInfo).GunPartLocations);
            PlayerSpawnLocations.AddRange(((MurderLevelInfo)((MurderLevel)gameLevel).GameLevelInfo).PlayerSpawnLocations);

            while (PlayerSpawnLocations.Count < gameLevel.GetMaxPlayers())
            {
                PlayerSpawnLocations.Add(((MurderLevelInfo)((MurderLevel)gameLevel).GameLevelInfo).PlayerSpawnLocations[0]);
            }

            EndTick = gameLevel.Tick + MaxGameTime + PreStartTime;

            try
            {
                RunnableTask.RunTask(() =>
                {
                    //Create new collection due to iterating over a live list
                    ICollection <SkyPlayer> players = gameLevel.GetAllPlayers();
                    foreach (SkyPlayer player in players)
                    {
                        player.SetEffect(new Blindness {
                            Duration = 80, Particles = false
                        });                                                                           //Should be 3 seconds?

                        player.SetHideNameTag(true);
                        player.IsAlwaysShowName = false;
                        player.SetNameTagVisibility(false);
                    }

                    List <PlayerLocation> usedSpawnLocations = new List <PlayerLocation>();
                    gameLevel.DoForAllPlayers(player =>
                    {
                        //Pre-add all players to the map to avoid any unnecessary contains
                        if (PlayerAmmoCounts.ContainsKey(player.Username))
                        {
                            PlayerAmmoCounts[player.Username] = 0;
                        }
                        else
                        {
                            PlayerAmmoCounts.Add(player.Username, 0);
                        }

                        if (PlayerGunPartCounts.ContainsKey(player.Username))
                        {
                            PlayerGunPartCounts[player.Username] = 0;
                        }
                        else
                        {
                            PlayerGunPartCounts.Add(player.Username, 0);
                        }

                        player.SetGameMode(GameMode.Adventure);

                        //Avoid spawning two players in the same location
                        PlayerLocation spawnLocation;
                        while (usedSpawnLocations.Contains((spawnLocation = PlayerSpawnLocations[Random.Next(PlayerSpawnLocations.Count)])))
                        {
                            //
                        }

                        usedSpawnLocations.Add(spawnLocation);

                        //Mark spawn position for AFK Check
                        player.SpawnPosition = spawnLocation;
                        player.Teleport(spawnLocation);

                        player.SetHideNameTag(true);
                        player.IsAlwaysShowName = false;
                        player.SetNameTagVisibility(false);

                        player.Freeze(true);

                        player.HungerManager.Hunger = 6;                       //Set food to 'unable to run' level.
                        player.SendUpdateAttributes();                         //TODO: Not required? Or is this required for Hunger
                    });

                    List <MurderTeam> teamRotation = new List <MurderTeam> {
                        MurderTeam.Murderer, MurderTeam.Detective, MurderTeam.Innocent
                    };
                    int offset = Random.Next(teamRotation.Count);
                    for (int i = 0; i < 12; i++)
                    {
                        MurderTeam team = teamRotation[(offset + i) % 3];
                        foreach (SkyPlayer player in players)
                        {
                            TitleUtil.SendCenteredSubtitle(player, team.TeamPrefix + "§l" + team.TeamName);

                            //Poorly enforce speed
                            if (i == 0 || i == 11)
                            {
                                player.Freeze(true);
                                player.SetHideNameTag(true);
                                player.IsAlwaysShowName = false;
                                player.SetNameTagVisibility(false);
                            }
                        }

                        //SkyUtil.log($"Printed scroll {i}/12, with {team.TeamPrefix + "§l" + team.TeamName}");
                        Thread.Sleep(250);
                    }

                    int murdererIdx = Random.Next(players.Count),
                    detectiveIdx    = 0;

                    int idx = 0;
                    while (++idx < 50 && (detectiveIdx = Random.Next(players.Count)) == murdererIdx)
                    {
                        //
                    }

                    //Console.WriteLine($"Rolled Murderer as {murdererIdx} Detective as {detectiveIdx} with 0-{players.Count - 1} possible indexes");

                    idx = 0;
                    foreach (SkyPlayer player in players)
                    {
                        if (idx == murdererIdx)
                        {
                            gameLevel.SetPlayerTeam(player, MurderTeam.Murderer);
                        }
                        else if (idx == detectiveIdx)
                        {
                            gameLevel.SetPlayerTeam(player, MurderTeam.Detective);
                        }
                        else
                        {
                            gameLevel.SetPlayerTeam(player, MurderTeam.Innocent);
                        }

                        idx++;
                    }

                    //Workaround for one player (single murderer)
                    if (((MurderLevel)gameLevel).Detective == null)
                    {
                        ((MurderLevel)gameLevel).Detective = ((MurderLevel)gameLevel).Murderer;
                    }

                    gameLevel.DoForPlayersIn(player =>
                    {
                        TitleUtil.SendCenteredSubtitle(player, "§a§lInnocent §r\n§7Track down the murderer!");
                    }, MurderTeam.Innocent);

                    gameLevel.DoForPlayersIn(player =>
                    {
                        TitleUtil.SendCenteredSubtitle(player, "§9§lDetective §r\n§7Track down the murderer!");

                        player.Inventory.SetInventorySlot(0, new ItemInnocentGun());
                        //SkyUtil.log($"In Slot 0 = {player.Inventory.GetSlots()[0].GetType().FullName}");
                        player.Inventory.SetInventorySlot(9, new ItemArrow());

                        PlayerAmmoCounts[player.Username] = int.MaxValue;
                    }, MurderTeam.Detective);

                    gameLevel.DoForPlayersIn(InitializeMurderer, MurderTeam.Murderer);

                    gameLevel.DoForAllPlayers(player =>
                    {
                        player.SendAdventureSettings();

                        player.Freeze(false);

                        //Ensure this player is at the correct spawn location
                        if (gameLevel.GetBlock(player.KnownPosition).Id != 0)
                        {
                            PlayerLocation newLocation = (PlayerLocation)player.KnownPosition.Clone();
                            newLocation.Y++;

                            player.Teleport(newLocation);
                        }
                    });
                });
            }
            catch (Exception e)
            {
                BugSnagUtil.ReportBug(e, this, gameLevel);
            }
        }
예제 #21
0
        //New GameLevel Method
        public void AddPlayer(SkyPlayer player)
        {
            if (player.Level != this && player.Level is GameLevel level)
            {
                level.RemovePlayer(player, true);         //Clear from old world
            }

            //Remove a player from _incomingPlayers only if it's non-empty.
            //Avoid claiming a lock for a useless check
            if (_incomingPlayers.Count > 0)
            {
                lock (_incomingPlayers)
                {
                    if (_incomingPlayers.ContainsKey(player.Username))
                    {
                        _incomingPlayers.Remove(player.Username);
                    }
                }
            }

            GameTeam defaultTeam = GetDefaultTeam();

            SetPlayerTeam(player, defaultTeam);
            //SkyUtil.log($"Added {player.Username} to team {defaultTeam.DisplayName} in game {GameId}");

            /*if (player.Level != this)
             * {
             *      //Only show the level transition screen to players changing games on this instance
             * //player.SpawnLevel(this, GameLevelInfo.LobbyLocation, !_incomingPlayers.ContainsKey(player.Username));
             * player.SpawnLevel(this, GameLevelInfo.LobbyLocation, false); //Remove loading screen to prevent 'building terrain' issue
             * }
             * else //Still teleport the player to the spawn location
             * {
             * player.Teleport(GameLevelInfo.LobbyLocation);
             * }*/

            //Fix for maps on first join to an instance
            player.SpawnLevel(this, GameLevelInfo.LobbyLocation, false);             //Remove loading screen to prevent 'building terrain' issue

            try
            {
                CurrentState.InitializePlayer(this, player);
            }
            catch (Exception e)
            {
                BugSnagUtil.ReportBug(e, this, CurrentState, player);
            }

            //Update Time
            McpeSetTime message = McpeSetTime.CreateObject();

            message.time = GameLevelInfo.WorldTime;
            player.SendPackage(message);

            //

            //Pending Tasks
            //Attempts to execute tasks like spawning NPCs in once a single player has loaded the world
            if (_shouldSchedule)
            {
                _shouldSchedule = false;

                if (_pendingTasks.Count > 0)
                {
                    foreach (SkyCoreAPI.PendingTask pendingTask in _pendingTasks)
                    {
                        RunnableTask.RunTaskLater(() =>
                        {
                            try
                            {
                                pendingTask.Invoke();
                            }
                            catch (Exception e)
                            {
                                BugSnagUtil.ReportBug(e, new AnonMetadatable((metadata) =>
                                {
                                    metadata.AddToTab("PendingTask", "Target", pendingTask.Target);
                                    metadata.AddToTab("PendingTask", "Method", pendingTask.Method);
                                }));
                            }
                        }, 250);                 //Small delay for the level to initialize
                    }

                    _pendingTasks.Clear();
                }
            }
        }
예제 #22
0
        public static void SpawnHubNPC(GameLevel level, string npcName, PlayerLocation spawnLocation, string command)
        {
            NPCSpawnTask spawnTask = (gameLevel) =>
            {
                try
                {
                    if (String.IsNullOrEmpty(npcName))
                    {
                        Console.WriteLine("§c§l(!) §r§cInvalid NPC text. /hologram <text>");
                        return;
                    }

                    npcName = npcName.Replace("_", " ").Replace("&", "§");

                    if (npcName.Equals("\"\""))
                    {
                        npcName = "";
                    }

                    string     gameName = command;
                    onInteract action   = null;
                    if (!String.IsNullOrEmpty(command))
                    {
                        if (command.StartsWith("GID:"))
                        {
                            gameName = command.Split(':')[1];

                            switch (gameName)
                            {
                            case "murder":
                            case "build-battle":
                            {
                                action = player =>
                                {
                                    //Freeze the players movement
                                    player.Freeze(true);
                                    RunnableTask.RunTaskLater(() => ExternalGameHandler.AddPlayer(player, gameName), 200);
                                };
                                break;
                            }
                            }
                        }
                    }

                    if (gameName.Equals(command))
                    {
                        SkyUtil.log($"Unknown game command '{command}'");
                        return;
                    }

                    //Ensure this NPC can be seen
                    PlayerNPC npc;

                    /*if (action != null)
                     * {
                     *      npc = new PlayerNPC("§a(Punch to play)", gameLevel, spawnLocation, action, gameName) { Scale = 1.5 };
                     * }
                     * else
                     * {
                     *      npc = new PlayerNPC("§e(Coming Soon)", gameLevel, spawnLocation, null, gameName) { Scale = 1.5 };
                     * }*/
                    npc = new PlayerNPC("", gameLevel, spawnLocation, action, gameName)
                    {
                        Scale = 1.5
                    };

                    SkyCoreAPI.Instance.AddPendingTask(() =>
                    {
                        npc.KnownPosition = spawnLocation;
                        //npc.Width = 0D;
                        //npc.Height = 1.0D;
                        npc.SpawnEntity();
                    });

                    {
                        PlayerLocation playerCountLocation = (PlayerLocation)spawnLocation.Clone();

                        //Spawn a hologram with player counts
                        PlayerCountHologram hologram = new PlayerCountHologram(npcName, gameLevel, playerCountLocation, gameName);

                        SkyCoreAPI.Instance.AddPendingTask(() => hologram.SpawnEntity());
                    }

                    {
                        PlayerLocation gameNameLocation = (PlayerLocation)spawnLocation.Clone();
                        gameNameLocation.Y += 3.1f;

                        Hologram gameNameHologram = new Hologram(npcName, gameLevel, gameNameLocation);

                        SkyCoreAPI.Instance.AddPendingTask(() => gameNameHologram.SpawnEntity());
                    }

                    Console.WriteLine($"§e§l(!) §r§eSpawned NPC with text '{npcName}§r'");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            };

            if (String.IsNullOrWhiteSpace(command))
            {
                SkyUtil.log("Found null command as key. Using npc game name instead.");
                command = npcName;
            }

            GameNPCs.Add(command, spawnTask);

            if (level != null)
            {
                spawnTask.Invoke(level);
            }
        }
예제 #23
0
        public override void EnterState(GameLevel gameLevel)
        {
            EndTick = gameLevel.Tick + MaxGameTime + PreStartTime;

            RunnableTask.RunTask(() =>
            {
                ICollection <MiNET.Player> players = new List <MiNET.Player>(gameLevel.Players.Values);

                foreach (BuildBattleTeam gameTeam in ((BuildBattleLevel)gameLevel).BuildTeams)
                {
                    foreach (SkyPlayer player in gameLevel.GetPlayersInTeam(gameTeam))
                    {
                        player.IsWorldImmutable = true;                         //Prevent Breaking
                        //player.IsWorldBuilder = false;
                        player.Teleport(gameTeam.SpawnLocation);

                        player.SetAllowFly(true);
                        player.IsFlying = true;

                        player.SendAdventureSettings();

                        player.UseCreativeInventory = true;
                        player.UpdateGameMode(GameMode.Creative, false);

                        player.SetNameTagVisibility(false);
                    }
                }

                List <BuildBattleTheme> categoryRotation = ((BuildBattleLevel)gameLevel).ThemeList;
                {
                    int initialTheme = Random.Next(categoryRotation.Count);
                    for (int i = initialTheme; i < (initialTheme + 12); i++)
                    {
                        BuildBattleTheme category = categoryRotation[i % categoryRotation.Count];
                        foreach (MiNET.Player player in players)
                        {
                            TitleUtil.SendCenteredSubtitle(player, category.ThemeName);
                        }

                        Thread.Sleep(250);
                    }
                }

                SelectedCategory = categoryRotation[Random.Next(categoryRotation.Count)];
                gameLevel.DoForAllPlayers(player =>
                {
                    player.IsWorldImmutable = true;                     //Allow breaking
                    //player.IsWorldBuilder = false;
                    player.SendAdventureSettings();

                    player.UpdateGameMode(GameMode.Creative, true);

                    string secondLine = "§fYou have §75 minutes§f, let's go!";

                    TitleUtil.SendCenteredSubtitle(player, $"{SelectedCategory.ThemeName}\n{secondLine}");

                    player.Inventory.Clear();
                    for (int i = 0; i < SelectedCategory.TemplateItems.Count; i++)
                    {
                        player.Inventory.SetInventorySlot(i, SelectedCategory.TemplateItems[i].GetItem());
                    }

                    //Ensure this player is at the correct spawn location
                    if (gameLevel.GetBlock(player.KnownPosition).Id != 0)
                    {
                        PlayerLocation newLocation = (PlayerLocation)player.KnownPosition.Clone();
                        newLocation.Y++;

                        player.Teleport(newLocation);
                    }
                });

                gameLevel.AllowBreak = true;
                gameLevel.AllowBuild = true;
            });
        }
        public override void EnterState(GameLevel gameLevel)
        {
            base.EnterState(gameLevel);

            gameLevel.DoForAllPlayers(player =>
            {
                player.Inventory.Clear();
            });

            SkyPlayer winningPlayer = null;
            List <KeyValuePair <SkyPlayer, int> > topPlayers = null;

            if (_voteTally != null)
            {
                topPlayers = new List <KeyValuePair <SkyPlayer, int> >();
                foreach (SkyPlayer player in _voteTally.Keys)
                {
                    topPlayers.Add(new KeyValuePair <SkyPlayer, int>(player, _voteTally[player]));
                }

                topPlayers.Sort((x, y) => 0 - x.Value.CompareTo(y.Value));

                int i = 0;
                foreach (KeyValuePair <SkyPlayer, int> topPlayer in topPlayers)
                {
                    if (++i > 1)                     //Top 1 Player for now
                    {
                        break;
                    }

                    //If the player has left, skip them.
                    if (!gameLevel.PlayerTeamDict.ContainsKey(topPlayer.Key.Username))
                    {
                        i = 0;
                    }
                    else
                    {
                        winningPlayer = topPlayer.Key;
                    }
                }
            }

            string winningPlayerName = winningPlayer == null ? "Unknown..." : winningPlayer.Username;

            List <PlayerLocation> podiumLocations;

            if (winningPlayer == null)
            {
                BuildBattleTeam podiumCentre;
                if (topPlayers == null || topPlayers.Count == 0)
                {
                    //Pick a random team
                    podiumCentre = ((BuildBattleLevel)gameLevel).BuildTeams[0];
                }
                else
                {
                    //Pick a random player
                    podiumCentre = (BuildBattleTeam)topPlayers[0].Key.GameTeam;
                }

                podiumLocations = ((BuildBattleLevel)gameLevel).GetVoteLocations(podiumCentre);
            }
            else
            {
                podiumLocations = ((BuildBattleLevel)gameLevel).GetVoteLocations((BuildBattleTeam)winningPlayer.GameTeam);
            }

            int j = 0;

            gameLevel.DoForAllPlayers(player =>
            {
                player.SetAllowFly(true);
                player.IsFlying = true;

                player.SendAdventureSettings();

                player.Inventory.Clear();

                TitleUtil.SendCenteredSubtitle(player, $"§a§lWinning Builder\n§7{winningPlayerName}");

                if (player == winningPlayer)
                {
                    PlayerLocation teleportLocation = (PlayerLocation)((BuildBattleTeam)player.GameTeam).SpawnLocation.Clone();
                    teleportLocation.Y += 10;

                    player.Teleport(teleportLocation);
                }
                else
                {
                    player.Teleport(podiumLocations[j]);

                    j++;
                }
            });

            RunnableTask.RunTaskLater(() =>
            {
                gameLevel.UpdateGameState(GetNextGameState(gameLevel));
            }, 5000);
        }
예제 #25
0
        public override bool HandleGameEditCommand(SkyPlayer player, GameLevel level, GameLevelInfo gameLevelInfo, params string[] args)
        {
            if (!(gameLevelInfo is MurderLevelInfo murderLevelInfo))
            {
                player.SendMessage("§cThe current levels game info is not in the correct format to be a Murder Level Info.");
                player.SendMessage("§cUpdating as MurderLevelInfo and saving with default options.");

                murderLevelInfo = new MurderLevelInfo(gameLevelInfo.LevelName, gameLevelInfo.WorldTime, gameLevelInfo.LobbyLocation,
                                                      new List <PlayerLocation>(), new List <PlayerLocation>());
            }

            if (args[0].Equals("add"))
            {
                if (args.Length < 2)
                {
                    player.SendMessage("§c/location add <spawn/gunpart>");
                    player.SendMessage("§cNot Enough Arguments.");
                    return(true);
                }

                List <PlayerLocation> locationList = null;
                if (args[1].Equals("spawn"))
                {
                    locationList = murderLevelInfo.PlayerSpawnLocations;
                }
                else if (args[1].Equals("gunpart"))
                {
                    locationList = murderLevelInfo.GunPartLocations;
                }

                if (locationList == null)
                {
                    player.SendMessage($"§cAction invalid. Must be 'spawn' or 'gunpart', but was '{args[1]}'");
                    return(true);
                }

                PlayerLocation addedLocation = (PlayerLocation)player.KnownPosition.Clone();
                addedLocation.X = (float)(Math.Floor(addedLocation.X) + 0.5f);
                addedLocation.Y = (float)Math.Floor(addedLocation.Y);
                addedLocation.Z = (float)(Math.Floor(addedLocation.Z) + 0.5f);

                addedLocation.HeadYaw = (float)Math.Floor(addedLocation.HeadYaw);
                addedLocation.HeadYaw = addedLocation.HeadYaw;
                addedLocation.Pitch   = (float)Math.Floor(addedLocation.Pitch);

                locationList.Add(addedLocation);

                string fileName =
                    $"C:\\Users\\Administrator\\Desktop\\worlds\\{RawName}\\{RawName}-{level.LevelName}.json";

                SkyUtil.log($"Saving as '{fileName}' -> {level.GameType} AND {level.LevelName}");

                File.WriteAllText(fileName, JsonConvert.SerializeObject(gameLevelInfo, Formatting.Indented));

                player.SendMessage($"§cUpdated {args[0]} location list ({locationList.Count}) with current location.");

                //Update current level info
                ((MurderLevel)player.Level).GameLevelInfo = gameLevelInfo;
            }
            else if (args[0].Equals("visualize"))
            {
                if (_currentVisualizationTasks.ContainsKey(player.Username))
                {
                    _currentVisualizationTasks[player.Username].Cancelled = true;

                    _currentVisualizationTasks.Remove(player.Username);

                    player.SendMessage("§eCancelling Visualization Task");
                }
                else
                {
                    player.SendMessage("§eVisualizing Gun Part and Player Spawn Locations...");

                    _currentVisualizationTasks.Add(player.Username, RunnableTask.RunTaskIndefinitely(() =>
                    {
                        foreach (PlayerLocation location in murderLevelInfo.GunPartLocations)
                        {
                            PlayerLocation displayLocation = (PlayerLocation)location.Clone();
                            displayLocation.Y += 0.5f;

                            Vector3 particleLocation = displayLocation.ToVector3();

                            new FlameParticle(player.Level)
                            {
                                Position = particleLocation
                            }.Spawn(new MiNET.Player[] { player });
                        }

                        foreach (PlayerLocation location in murderLevelInfo.PlayerSpawnLocations)
                        {
                            PlayerLocation displayLocation = (PlayerLocation)location.Clone();
                            displayLocation.Y += 0.5f;

                            Vector3 particleLocation = displayLocation.ToVector3();

                            new HeartParticle(player.Level)
                            {
                                Position = particleLocation
                            }.Spawn(new MiNET.Player[] { player });
                        }
                    }, 500));
                }
            }
            else if (args[0].Equals("tp"))
            {
                player.SendMessage("§eTeleporting to a random spawn location");
                player.Teleport(murderLevelInfo.PlayerSpawnLocations[Random.Next(murderLevelInfo.PlayerSpawnLocations.Count)]);
            }
            else
            {
                //Falls through, no specific handling
                return(false);
            }

            //One if-branch was used, this counts enough as usage
            return(true);
        }