Esempio n. 1
0
        void ExplodingInit(TimePieceStates previous)
        {
            //
            // Initial burst of the time piece.
            //

            tp.physics = (APhysics)tp.AddComponent(new SimpleGravity(/* friction */ 0.84f, /* gravity */ 1.5f));

            tp.physics.AddVelocity(tp.transform.direction * (300 + (float)GameManager.random.NextDouble() * 50));
            tp.transform.direction = Vector2.Zero;

            var time = 0.7 + GameManager.random.NextDouble() * 0.4;

            TaskScheduler.AddTask(() =>
            {
                if (tp.objectFollowing != null)
                {
                    Init(TimePieceStates.Following);
                }
                else
                {
                    tp.done = true;
                }
            }, time, time, tp.id);
        }
Esempio n. 2
0
        void OpenedStateInit(string previous)
        {
            TaskScheduler.AddTask(() => {
                GameObjectManager.AddObject(
                    new Explosion(
                        this.transform.position + new Vector2(
                            8 + (float)GameManager.random.NextDouble() * 8 - 4,
                            8 + (float)GameManager.random.NextDouble() * 8 - 4)));
                ((Camera)GameObjectManager.FindObjectWithTag("camera"))?.AddShake(0.1);
            },
                                  0.3, 1.8, this.id
                                  );

            TaskScheduler.AddTask(() => {
                done = true;
                for (int i = 0; i < 4; i += 1)
                {
                    GameObjectManager.AddObject(
                        new Explosion(
                            this.transform.position + new Vector2(
                                8 + (float)GameManager.random.NextDouble() * 8 - 4,
                                8 + (float)GameManager.random.NextDouble() * 8 - 4)));
                }
                ((Camera)GameObjectManager.FindObjectWithTag("camera"))?.AddShake(0.4);

                //
                // Remove map cell.
                //

                var celPos = util.CorrespondingCelIndex(this.transform.position);
                GameManager.pico8.Memory.Mset((int)celPos.X, (int)celPos.Y, 0);
            },
                                  2, 2, this.id
                                  );
        }
Esempio n. 3
0
        public static void Start(string[] args)
        {
            Console.WriteLine("Press \'q\' to quit.");
            BrowserWatcherBase.InitializeEnvironment();
            var schedule = new Schedule(ConfigurationManager.AppSettings["Frequency"],
                                        ConfigurationManager.AppSettings["FrequencyValue"],
                                        ConfigurationManager.AppSettings["Skip"],
                                        ConfigurationManager.AppSettings["SkipValue"]);

            if (!schedule.IsSingleRun())
            {
                Logger.Info("Start in Scheduled Mode");
                int interval = 1;
                int.TryParse(ConfigurationManager.AppSettings["SchedulerBaseInterval"], out interval);
                TaskScheduler scheduler = new TaskScheduler(interval);
                scheduler.AddTask(StartReconsiliation, schedule);
                scheduler.Start();
                while (Console.Read() != 'q')
                {
                    ;
                }
            }
            else
            {
                Logger.Info("Start in Single Run Mode");
                StartReconsiliation();
                Logger.Info("Checking Finished");
            }
        }
Esempio n. 4
0
        void HalfInit(SpikeStates previous)
        {
            _spike.sprite.index = 121;
            _spike.collisionBox = null;

            task = TaskScheduler.AddTask(() => Init(SpikeStates.Full), changeStateTime, changeStateTime, _spike.id);
        }
Esempio n. 5
0
        void RunningInit(TortugaStates previous)
        {
            _tortuga.GetComponent <APhysics>().maxSpeed = 15f;
            vanishingStateTask = TaskScheduler.AddTask(() => Init(TortugaStates.Vanishing), vanishingTime, vanishingTime, _tortuga.id);

            //
            // Choose a direction away from the player.
            //

            Action directionChooser = () =>
            {
                var player = GameObjectManager.FindObjectWithTag("player");
                if (player != null)
                {
                    var awayDir = _tortuga.transform.position - player.transform.position;

                    // Find a random direction vector that is the direction away from the player rotated
                    // by at most 90 or -90 degrees, making sure that the resulting vector is still facing
                    // away from the player.
                    var randAngle = GameManager.random.NextDouble() * Math.PI - Math.PI / 2;
                    _tortuga.transform.direction = new Vector2(
                        awayDir.X * (float)Math.Cos(randAngle) - awayDir.Y * (float)Math.Sin(randAngle),
                        awayDir.X * (float)Math.Sin(randAngle) + awayDir.Y * (float)Math.Cos(randAngle));
                }
            };

            directionChooser();

            directionChooserTask = TaskScheduler.AddTask(directionChooser, changeDirectionTime, -1, _tortuga.id);
        }
Esempio n. 6
0
        void StillInit(GooseStates previous)
        {
            _goose.transform.direction = Vector2.Zero;

            TaskScheduler.AddTask(() => { if (State == GooseStates.Still)
                                          {
                                              Init(GooseStates.Wondering);
                                          }
                                  }, 2, 2, _goose.id);
        }
Esempio n. 7
0
        /// <inheritdoc />
        protected override void DoOnStart()
        {
            SetupEventGenerators(_scheduler);
            MessageBuilder messageBuilder = new MessageBuilder();

            _scheduler.AddTask(messageBuilder, LocalConfiguration.General.ConsumerInterval, DateTime.UtcNow);

            // This will take over the current running thread - this flag can be changed if we want this thread to detach and execute something else
            _scheduler.Start(runInCurrentThread: true);
        }
        /// <summary>
        /// Sets up the generation of events, as defined in the configuration, wit hthe proper intervals between them, to avoid overloading the system
        /// </summary>
        /// <param name="scheduler">The scheduler to setup the event generators in</param>
        protected void SetupEventGenerators(TaskScheduler scheduler)
        {
            DateTime timeToStartTask = DateTime.UtcNow;
            TimeSpan timeSpanBetweenGeneratorInvocation = new TimeSpan(LocalConfiguration.General.ProducerInterval.Ticks / EventGenerators.Count());

            foreach (var generator in EventGenerators)
            {
                EventProducer producer = new EventProducer(generator);
                scheduler.AddTask(producer, LocalConfiguration.General.ProducerInterval, timeToStartTask);
                timeToStartTask = timeToStartTask.Add(timeSpanBetweenGeneratorInvocation);
            }
        }
Esempio n. 9
0
        void WonderingInit(GooseStates previous)
        {
            var physics = _goose.GetComponent <APhysics>();

            if (physics != null)
            {
                physics.maxSpeed = _goose.baseSpeed;
            }

            _goose.transform.direction = Vector2.Zero;

            Action wonderingDirFunc = () =>
            {
                // Find a random direction vector that is the direction away from the player rotated
                // by at most 90 or -90 degrees, making sure that the resulting vector is still facing
                // away from the player.
                var randAngle = GameManager.random.NextDouble() * 2 * Math.PI;
                targetDir = new Vector2((float)Math.Sin(randAngle), (float)Math.Cos(randAngle));
                targetDir.Normalize();

                Debug.Log($"{_goose.GetType().FullName} Wondering State direction angle is {randAngle}");

                targetPosition = _goose.transform.position + targetDir * 20;
            };

            wonderingDirTask = TaskScheduler.AddTask(wonderingDirFunc, changeDirTime, -1, _goose.id);

            //
            // Choose a direction away from the player at first.
            //

            var p = GameObjectManager.FindObjectWithTag("player");

            if (p != null)
            {
                var awayDir = _goose.transform.position - p.transform.position;

                // Find a random direction vector that is the direction away from the player rotated
                // by at most 90 or -90 degrees, making sure that the resulting vector is still facing
                // away from the player.
                var randAngle = GameManager.random.NextDouble() * Math.PI - Math.PI / 2;
                targetDir = new Vector2(
                    awayDir.X * (float)Math.Cos(randAngle) - awayDir.Y * (float)Math.Sin(randAngle),
                    awayDir.X * (float)Math.Sin(randAngle) + awayDir.Y * (float)Math.Cos(randAngle));
                targetDir.Normalize();

                Debug.Log($"{_goose.GetType().FullName} Wondering State direction angle is {randAngle}");

                targetPosition = _goose.transform.position + targetDir * 10;
            }
        }
Esempio n. 10
0
 public void OnActive()
 {
     if (_weapon != null)
     {
         _ts.AddTask(new Task(
                         () =>
         {
             Debug.Log("Action!");
             var obj = Instantiate(_weapon, transform);
             obj.GetComponent <Weapon>().Launch();
         }
                         ));
     }
 }
Esempio n. 11
0
        public virtual double TakeHit(double hitAmount)
        {
            if (isInvincible)
            {
                return(0);
            }

            isInvincible = true;
            TaskScheduler.AddTask(() => { isInvincible = false; }, invTime, invTime, this.id);
            TaskScheduler.AddTask(() => isInvisible = !isInvisible, invisibleTime, invTime, this.id);

            if (doesDamage)
            {
                doesDamage = false;
                TaskScheduler.AddTask(() => { doesDamage = true; }, invTime / 2, invTime / 2, this.id);
            }

            lifeTime -= hitAmount;

            // If enemy is very close to being dead, kill it anyway
            if (lifeTime < 0.5)
            {
                lifeTime = 0;
            }

            if (lifeTime <= 0)
            {
                deathType = DeathType.HIT;
            }

            //
            // Play audio effect
            //

            GameManager.pico8.Audio.Sfx(0);

            //
            // Give a bonus time in the last hit.
            //

            var timeAmount = hitAmount;

            if (lifeTime <= 0.5)
            {
                ControllerVibration.SetVibration(0, 1f, 1f, 0.1);
                timeAmount *= 1.5f;
            }

            return(Math.Ceiling(timeAmount));
        }
Esempio n. 12
0
        void DyingInit(PlayerStates prev)
        {
            _player.RemoveComponent <AInput>();

            TaskScheduler.AddTask(() => {
                _player.fadeOut     = true;
                _player.fadeOutTime = 2 * deadTime / 3;
            }, deadTime / 3, deadTime / 3, _player.id);

            TaskScheduler.AddTask(() => {
                Init(PlayerStates.Dead);
            }, deadTime, deadTime, _player.id);

            ControllerVibration.SetVibration(0, 1, 1, deadTime);
        }
        public DialogueBox(List <string> messages) : base(Vector2.Zero, null)
        {
            _messages = messages;

            // Task to advance each letter in the message.
            TaskScheduler.AddTask(() => {
                if (_currentLength < _messages[_currentMessage].Length)
                {
                    _currentLength += 1;
                }
            }, _letterTime, -1, this.id);

            AddComponent(new InteractableInput());

            depth = 10000;
        }
Esempio n. 14
0
        public Altar(Vector2 position) : base(position)
        {
            _key = new Key(position + new Vector2(4, -2));
            GameObjectManager.AddObject(_key);

            TaskScheduler.AddTask(() => {
                var smoke = new Smoke(position + new Vector2(4 + (float)GameManager.random.NextDouble() * 8, 8));
                smoke.SetColor(9);
                smoke.SetRadius(1, 1.5f);
                ParticleManager.AddParticle(smoke);
            }, 0.1f, -1, this.id);

            AddComponent(new P8Sprite(78, 2, 2));

            depth = -1000;
        }
        /// <inheritdoc />
        protected override void DoOnStart()
        {
            SetupEventGenerators(_producerScheduler);

            MessageBuilder messageBuilder = new MessageBuilder();

            _consumerScheduler.AddTask(messageBuilder, LocalConfiguration.General.ConsumerInterval, DateTime.UtcNow);

            _producerScheduler.Start();
            _consumerScheduler.Start();

            // TODO: keep alive properly
            while (!CancellationTokenSource.IsCancellationRequested)
            {
                Thread.Sleep(5000);
            }
        }
Esempio n. 16
0
        public override void OnDestroy()
        {
            base.OnDestroy();

            //
            // Schedule a respawn only if it has previously died.
            //

            if (lifeTime <= 0)
            {
                var celPos = new Vector2((float)Math.Floor(startPosition.X / 8), (float)Math.Floor(startPosition.Y / 8));
                GameManager.pico8.Memory.Mset((int)celPos.X, (int)celPos.Y, 0);
                TaskScheduler.AddTask(() => {
                    GameManager.pico8.Memory.Mset((int)celPos.X, (int)celPos.Y, (byte)spriteIndex);
                }, respawnTime, respawnTime, -1
                                      );
            }
        }
Esempio n. 17
0
        public override void Update(GameTime gameTime)
        {
            var pi = GameObjectManager.playerInstance;

            if (pi == null)
            {
                return;
            }

            Vector2 nextIndex = util.CorrespondingMapIndex(pi.collisionBox.middle);

            if (currentIndex.X != nextIndex.X || currentIndex.Y != nextIndex.Y)
            {
                Debug.Log($"Got into map index ( {nextIndex.X}, {nextIndex.Y} )");

                if (toDestroy != null)
                {
                    foreach (var obj in toDestroy)
                    {
                        obj.done = true;
                    }

                    toDestroy = null;
                }

                currentIndex = nextIndex;
                toDestroy    = GameObjectManager.FindObjectsWithTag("nonpersistent");
                if (toDestroy != null)
                {
                    foreach (var obj in toDestroy)
                    {
                        obj.isPaused = true;
                        TaskScheduler.AddTask(() => {
                            obj.done = true;
                            Debug.Log($"{obj.GetType().FullName} is done");
                        }, 0.5, 0.5, this.id);
                    }
                }

                TaskScheduler.AddTask(() => toDestroy = null, 0.5, 0.5, this.id);

                InstantiateEntities(currentIndex);
            }
        }
Esempio n. 18
0
        void WonderingInit(BatStates previous)
        {
            var physics = _bat.GetComponent <APhysics>();

            physics.friction     = 0.99f;
            physics.maxSpeed     = _bat.baseSpeed / 4;
            physics.acceleration = physics.maxSpeed / 4;

            _bat.transform.direction = Vector2.Zero;

            //
            // Set correct animation.
            //

            _bat.RemoveComponent <SpriteAnimation>();

            _bat.flyingAnim.Reset();
            _bat.flyingAnim.animationFrameLength = _bat.animationLength / (_bat.flyingAnim.spriteList.Count);

            _bat.AddComponent(_bat.flyingAnim);

            //
            // Chooses a new position after some time.
            //

            targetPosition = _bat.transform.position;

            Action func = () =>
            {
                var dir    = GameManager.random.NextDouble() * 2 * Math.PI;
                var length = (float)GameManager.random.NextDouble() * (wonderingLengthMax - wonderingLengthMin) + wonderingLengthMin;
                targetPosition = new Vector2((float)Math.Sin(dir), (float)Math.Cos(dir)) * length + _bat.transform.position;
                targetDir      = targetPosition - _bat.transform.position;
                if (targetDir != Vector2.Zero)
                {
                    targetDir.Normalize();
                }
            };

            func();

            targetPosTask = TaskScheduler.AddTask(func, newPositionInterval, -1, _bat.id);
        }
Esempio n. 19
0
        public double TakeHit(double hitAmount)
        {
            if (IsInvincible)
            {
                return(0);
            }

            IsInvincible = true;
            CanAttack    = false;
            TaskScheduler.AddTask(() => { IsInvincible = false; isInvisible = false; }, invTime, invTime, this.id);
            TaskScheduler.AddTask(() => { CanAttack = true; }, invTime / 2, invTime / 2, this.id);
            TaskScheduler.AddTask(() => isInvisible = !isInvisible, invisibleTime, invTime - 0.1, this.id);

            lifeTime -= hitAmount;

            ControllerVibration.SetVibration(0, 1f, 1f, 0.2);
            GameManager.pico8.Audio.Sfx(1);

            return(lifeTime > 0 ? hitAmount : hitAmount + lifeTime);
        }
Esempio n. 20
0
        void FullInit(SpikeStates previous)
        {
            _spike.sprite.index = 122;

            for (int i = 0; i < particleNumber; i += 1)
            {
                var smoke =
                    new Smoke(_spike.transform.position + new Vector2(1 + GameManager.random.Next(6), GameManager.random.Next(6)));
                smoke.SetRadius(1, 1.5f);
                smoke.SetMaxMoveSpeed(10f + (float)GameManager.random.NextDouble() * 5f);
                smoke.SetRadiusDecreaseSpeed(3f + (float)GameManager.random.NextDouble());
                ParticleManager.AddParticle(smoke);
            }

            _spike.collisionBox = new Box(_spike.transform.position, new Vector2(6, 6), false, new Vector2(1, 1));

            ((Camera)GameObjectManager.FindObjectWithTag("camera"))?.AddShake(0.1);

            task = TaskScheduler.AddTask(() => Init(SpikeStates.Down), changeStateTime, changeStateTime, _spike.id);
        }
Esempio n. 21
0
        void ChargingInit(BatStates previous)
        {
            TaskScheduler.AddTask(() => Init(BatStates.Attacking), 1.5f, 1.5f, _bat.id);

            var physics = _bat.GetComponent <APhysics>();

            physics.friction     = 0.98f;
            physics.acceleration = _bat.baseSpeed / 10;
            physics.maxSpeed     = _bat.baseSpeed / 5;

            //
            // Set correct animation.
            //

            //_bat.RemoveComponent<AGraphics>();

            //_bat.chargingAnim.Reset();
            //_bat.chargingAnim.animationFrameLength = _bat.animationLength;

            //_bat.AddComponent(_bat.chargingAnim);
        }
Esempio n. 22
0
        public override void OnCollision(GameObject other)
        {
            base.OnCollision(other);

            if (timePiecesSpawned != null)
            {
                foreach (var tp in timePiecesSpawned)
                {
                    tp.objectFollowing = this;
                }
            }

            if (other.tags.Contains("player_attack"))
            {
                if (gooseStateMachine.State != GooseStates.Chasing)
                {
                    gooseStateMachine.Init(GooseStates.Still);
                    TaskScheduler.AddTask(() => gooseStateMachine.Init(GooseStates.Chasing), 1, 1, this.id);
                }
            }
        }
Esempio n. 23
0
        void DeadInit(EnemyStates prev)
        {
            TaskScheduler.AddTask(() => _enemy.done = true, deadTime, deadTime, _enemy.id);

            _enemy.fadeOut     = true;
            _enemy.fadeOutTime = 2 * deadTime / 3;

            var p = _enemy.GetComponent <APhysics>();

            if (p == null)
            {
                return;
            }

            p.maxSpeed /= 2;

            if (_enemy.deathType == Enemy.DeathType.HIT)
            {
                _enemy.collisionBox = null;
            }
            _enemy.doesDamage = false;
        }
Esempio n. 24
0
        void WonderingInit(TortugaStates previous)
        {
            _tortuga.GetComponent <APhysics>().maxSpeed = 10f;

            //
            // Chooses a new position after some time.
            //

            targetPosition = _tortuga.transform.position;

            Action func = () =>
            {
                var dir    = GameManager.random.NextDouble() * 2 * Math.PI;
                var length = (float)GameManager.random.NextDouble() * (wonderingLengthMax - wonderingLengthMin) + wonderingLengthMin;
                targetPosition = new Vector2((float)Math.Sin(dir), (float)Math.Cos(dir)) * length + _tortuga.transform.position;
                targetDir      = targetPosition - _tortuga.transform.position;
                if (targetDir != Vector2.Zero)
                {
                    targetDir.Normalize();
                }
            };

            targetPosTask = TaskScheduler.AddTask(func, newPositionInterval, -1, _tortuga.id);
        }
Esempio n. 25
0
 private void AddTask(ScheduledTask task)
 {
     TaskScheduler.AddTask(task);
 }
Esempio n. 26
0
        public GamblingModule()
        {
            if (!Global.Config.IsMainBot)
            {
                lotteryId = taskScheduler.AddTask(0, (s) =>
                {
                    long size = (Global.RedisClient as StackExchangeCacheClient).Client.GetDatabase(0).ListLength(lotteryKey);

                    if (size == 0)
                    {
                        return;
                    }

                    string value = (Global.RedisClient as StackExchangeCacheClient).Client.GetDatabase(0).ListGetByIndex(lotteryKey, MikiRandom.Next(size));

                    ulong winnerId = ulong.Parse(value);
                    int wonAmount  = (int)Math.Round(size * 100 * 0.75);

                    IDiscordUser user = null;                     //Bot.Instance.ChatClient.GetUser(winnerId);

                    using (var context = new MikiContext())
                    {
                        long id          = winnerId.ToDbLong();
                        User profileUser = context.Users.Find(id);

                        if (user != null)
                        {
                            IDiscordChannel channel = user.GetDMChannel().Result;

                            EmbedBuilder embed = new EmbedBuilder()
                            {
                                Author = new EmbedAuthor()
                                {
                                    Name    = "Winner winner chicken dinner",
                                    IconUrl = user.GetAvatarUrl()
                                },
                                Description = $"Wow! You won the lottery and gained {wonAmount} mekos!"
                            };

                            profileUser.AddCurrencyAsync(wonAmount, channel);

                            embed.ToEmbed().QueueToChannel(channel);

                            context.SaveChanges();

                            Global.RedisClient.RemoveAsync(lotteryKey);
                            Global.RedisClient.UpsertAsync("lottery:winner", profileUser.Name ?? "unknown");
                            lotteryDict.ClearAsync();

                            var lotteryAchievement = AchievementManager.Instance.GetContainerById("lottery");

                            if (wonAmount > 100000)
                            {
                                lotteryAchievement.Achievements[0].UnlockAsync(channel, user, 0);
                            }

                            if (wonAmount > 10000000)
                            {
                                lotteryAchievement.Achievements[1].UnlockAsync(channel, user, 1);
                            }

                            if (wonAmount > 250000000)
                            {
                                lotteryAchievement.Achievements[2].UnlockAsync(channel, user, 1);
                            }
                        }
                    }
                }, "", new TimeSpan(0, 1, 0, 0), true);
            }
        }
Esempio n. 27
0
        public static void RunCommand(string command)
        {
            string[] args = CommandInterpreter.ParseCommand(command);
            if (args.Length > 0)
            {
                switch (args[0].ToLower())
                {
                case "exit":
                    Application.Exit();
                    break;

                case "mmrl":
                    ModuleManager.UnloadModules();
                    ModuleManager.LoadModules(Settings.ModulePath, false);
                    break;

                case "settings":
                    string[] setargs = new string[args.Length - 1];
                    Array.Copy(args, 1, setargs, 0, setargs.Length);
                    Settings.Execute(setargs);
                    break;

                case "task":
                    // Will create a task on a separate thread to run the input following "task"
                    // as a module command.
                    string[] modargs = new string[args.Length - 1];
                    Array.Copy(args, 1, modargs, 0, modargs.Length);
                    Scheduler.AddTask(modargs);
                    break;

                default:
                    // Default command line action is to interpret the input as a module command
                    // and execute the module on the same thread. Modules must already be loaded to be received.
                    // Will execute all modules registered with that command in the order of loading.
                    if (args.Length > 0)
                    {
                        string cmd = args[0];
                        // See if the second argument is a module command.
                        if (ModuleManager.CommandRegistry.ContainsKey(cmd))
                        {
                            IModule mod = ModuleManager.GetExistingModule(ModuleManager.CommandRegistry[cmd]);
                            mod.OnLoad();
                            if (args.Length > 1)
                            {
                                string[] extraargs = new string[args.Length - 1];
                                Array.Copy(args, 1, extraargs, 0, extraargs.Length);
                                mod.Execute(extraargs);
                            }
                            else
                            {
                                mod.Execute(new string[] { });
                            }
                            mod.OnExit();
                        }
                        else
                        {
                            Core.Output("Command not recognized. No module loaded with registered command '" + cmd + "'.");
                        }
                    }
                    break;
                }
            }
        }
Esempio n. 28
0
        public async Task GiveawayAsync(EventContext e)
        {
            DiscordEmoji emoji = new DiscordEmoji();

            emoji.Name = "🎁";

            e.Arguments.Take(out string giveawayText);

            while (!e.Arguments.Pack.Peek().StartsWith("-"))
            {
                giveawayText += " " + e.Arguments.Pack.Take();
            }

            var mml = new MMLParser(e.Arguments.Pack.TakeAll()).Parse();

            int      amount   = mml.Get("amount", 1);
            TimeSpan timeLeft = mml.Get("time", "1h").GetTimeFromString();

            if (amount > 10)
            {
                await e.ErrorEmbed("We can only allow up to 10 picks per giveaway")
                .ToEmbed().QueueToChannelAsync(e.Channel);

                return;
            }

            giveawayText = giveawayText + ((amount > 1) ? " x " + amount : "");

            List <IDiscordUser> winners = new List <IDiscordUser>();

            IDiscordMessage msg = await CreateGiveawayEmbed(e, giveawayText)
                                  .AddField("Time", timeLeft.ToTimeString(e.Locale), true)
                                  .AddField("React to participate", "good luck", true)
                                  .ToEmbed().SendToChannel(e.Channel);

            await msg.CreateReactionAsync(emoji);

            int updateTask = -1;

            int task = taskScheduler.AddTask(e.Author.Id, async(desc) =>
            {
                msg = await e.Channel.GetMessageAsync(msg.Id);

                if (msg != null)
                {
                    await msg.DeleteReactionAsync(emoji);

                    await Task.Delay(1000);

                    var reactions = await msg.GetReactionsAsync(emoji);

                    //do
                    //{
                    //	reactions.AddRange();
                    //	reactionsGained += 100;
                    //} while (reactions.Count == reactionsGained);

                    // Select random winners
                    for (int i = 0; i < amount; i++)
                    {
                        if (reactions.Count == 0)
                        {
                            break;
                        }

                        int index = MikiRandom.Next(reactions.Count);
                        winners.Add(reactions[index]);
                    }

                    if (updateTask != -1)
                    {
                        taskScheduler.CancelReminder(e.Author.Id, updateTask);
                    }

                    string winnerText = string.Join("\n", winners.Select(x => x.Username + "#" + x.Discriminator).ToArray());
                    if (string.IsNullOrEmpty(winnerText))
                    {
                        winnerText = "nobody!";
                    }

                    await msg.EditAsync(new EditMessageArgs
                    {
                        embed = CreateGiveawayEmbed(e, giveawayText)
                                .AddField("Winners", winnerText)
                                .ToEmbed()
                    });
                }
            }, "description var", timeLeft);
        }
Esempio n. 29
0
        public async Task GiveawayAsync(EventContext e)
        {
            //Emoji emoji = new Emoji("🎁");

            var    arg          = e.Arguments.FirstOrDefault();
            string giveAwayText = arg?.Argument ?? "";

            arg = arg?.Next();

            while (!(arg?.Argument ?? "-").StartsWith("-"))
            {
                giveAwayText += " " + arg.Argument;
                arg           = arg?.Next();
            }

            var mml = new MMLParser(arg?.TakeUntilEnd()?.Argument ?? "").Parse();

            bool     isUnique = mml.Get("unique", false);
            int      amount   = mml.Get("amount", 1);
            TimeSpan timeLeft = mml.Get("time", "1h").GetTimeFromString();

            if (amount > 10)
            {
                e.ErrorEmbed("We can only allow up to 10 picks per giveaway")
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            giveAwayText = giveAwayText + ((amount > 1) ? " x " + amount : "");

            List <IDiscordUser> winners = new List <IDiscordUser>();

            IDiscordMessage msg = await CreateGiveawayEmbed(e, giveAwayText)
                                  .AddField("Time", (DateTime.Now + timeLeft).ToShortTimeString(), true)
                                  .AddField("React to participate", "good luck", true)
                                  .ToEmbed().SendToChannel(e.Channel);

            //await (msg as IUserMessage).AddReactionAsync(emoji);

            int updateTask = -1;

            int task = taskScheduler.AddTask(e.Author.Id, async(desc) =>
            {
                //msg = await e.Channel.GetMessageAsync(msg.Id);

                if (msg != null)
                {
                    //await msg.RemoveReactionAsync(emoji, await e.Guild.GetCurrentUserAsync());

                    List <IDiscordUser> reactions = new List <IDiscordUser>();

                    int reactionsGained = 0;

                    do
                    {
                        //reactions.AddRange(await (msg as  IUserMessage).GetReactionUsersAsync(emoji, 100, reactions.LastOrDefault()?.Id ?? null));
                        reactionsGained += 100;
                    } while (reactions.Count == reactionsGained);

                    // Select random winners
                    for (int i = 0; i < amount; i++)
                    {
                        if (reactions.Count == 0)
                        {
                            break;
                        }

                        int index = MikiRandom.Next(reactions.Count);

                        winners.Add(reactions[index]);

                        if (isUnique)
                        {
                            reactions.RemoveAt(index);
                        }
                    }

                    if (updateTask != -1)
                    {
                        taskScheduler.CancelReminder(e.Author.Id, updateTask);
                    }

                    string winnerText = string.Join("\n", winners.Select(x => x.Username + "#" + x.Discriminator).ToArray());
                    if (string.IsNullOrEmpty(winnerText))
                    {
                        winnerText = "nobody!";
                    }

                    await msg.EditAsync(new EditMessageArgs
                    {
                        embed = CreateGiveawayEmbed(e, giveAwayText)
                                .AddField("Winners", winnerText)
                                .ToEmbed()
                    });
                }
            }, "description var", timeLeft);
        }