[NEW] Lotto System

Pollak

Active Member
Oct 12, 2017
161
51
Hii again xd! I'm sharing lotto system i coded.
I won't teach you how to do everything right. If you want to add this feature, have some idea how to add it in the emulator.

1- Create a new file with the name: LottoParticipateCommand.cs
C#:
#region
using Saturn.HabboHotel.Lotto;
using Saturn.Communication.Packets.Outgoing.Inventory.Purse;
using Saturn.HabboHotel.GameClients;
using System;
#endregion

namespace Saturn.HabboHotel.Rooms.Chat.Commands.User
{
    internal class LottoParticipateCommand : IChatCommand
    {
        public string PermissionRequired => "command_lotto_participate";

        public string Parameters => "";

        public string Description => "Join the lottery.";

        public void Execute(GameClient Session, Room Room, string[] Params)
        {
            int LottoDiscount = Convert.ToInt32(SaturnEnvironment.GetDBConfig().DBData["lotto.discount.credits"]);
            int LottoMaxParticipants = Convert.ToInt32(SaturnEnvironment.GetDBConfig().DBData["lotto.max.participants.per.user"]);
            int LottoIdentificator = Convert.ToInt32(SaturnEnvironment.GetDBConfig().DBData["lotto.id"]);

            LottoItem lotto = null;
            if (SaturnEnvironment.GetGame().GetLotto().TryGet(LottoIdentificator, out lotto))
            {
                if (!lotto.Enabled)
                {
                    Session.SendWhisper("Oops, the lottery is off!", 34);
                    return;
                }

                if (Session.GetHabbo().Credits < LottoDiscount)
                {
                    Session.SendWhisper("Oops, you don't have enough credits!", 34);
                    return;
                }

                if (LottoDiscount > Session.GetHabbo().Credits)
                {
                    Session.SendWhisper("Oops, you don't have enough credits!", 34);
                    return;
                }

                if (LottoDiscount <= 0)
                    return;

                int count = 0;
                if (lotto.Users.Contains(Session.GetHabbo().Id))
                {
                    foreach(var howmuch in lotto.Users)
                    {
                        if (howmuch == Session.GetHabbo().Id)
                            count++;
                    }
                }

                if (count >= LottoMaxParticipants)
                {
                    Session.SendWhisper("Oops, you can only participate in this Lottery " + LottoMaxParticipants + " times!", 3);
                    return;
                }

                Session.GetHabbo().Credits -= LottoDiscount;
                Session.SendMessage(new CreditBalanceComposer(Session.GetHabbo().Credits));

                lotto.Users.Add(Session.GetHabbo().Id);

                string users = "";
                foreach (int userst in lotto.Users)
                {
                    users += userst + ",";
                }

                if (!string.IsNullOrEmpty(users))
                    users = users.Substring(0, users.Length - 1);

                Session.SendWhisper("Is participating in the Lottery " + lotto.LottoName + "! Cost " + LottoDiscount + " credits!", 34);

                LottoManager.UpdatesInfos(LottoIdentificator, users, LottoDiscount, true, true);
                SaturnEnvironment.GetGame().GetLotto().Init(SaturnEnvironment.GetDatabaseManager().GetQueryReactor());
            }
            else
            {
                Session.SendWhisper("Oops, the lottery is not available!", 34);
                return;
            }
        }
    }
}

2- Create another file with name: LottoOpenCommand.cs
C#:
#region
using Saturn.Communication.Packets.Outgoing.Inventory.Purse;
using Saturn.Core;
using Saturn.HabboHotel.GameClients;
using Saturn.HabboHotel.Lotto;
using System;
using System.Collections.Generic;
#endregion

namespace Saturn.HabboHotel.Rooms.Chat.Commands.Administrator
{
    class LottoOpenCommand : IChatCommand
    {
        public string PermissionRequired => "command_lotto_open";

        public string Parameters => "";

        public string Description => "Open the lottery pot.";

        public void Execute(GameClient Session, Room Room, string[] Params)
        {
            int LottoIdentificator = Convert.ToInt32(SaturnEnvironment.GetDBConfig().DBData["lotto.id"]);

            LottoItem lotto = null;
            if (SaturnEnvironment.GetGame().GetLotto().TryGet(LottoIdentificator, out lotto))
            {
                if (!lotto.Enabled)
                {
                    Session.SendWhisper("Oops, the lottery is off!", 34);
                    return;
                }

                try
                {
                    var RANDOM_WIN = new List<int>();
                    int RandomUser = 0;
                    foreach (int user in lotto.Users)
                    {
                        if (!RANDOM_WIN.Contains(user))
                            RANDOM_WIN.Add(user);

                        RandomUser = new Random().Next(RANDOM_WIN.Count);
                    }

                    var TargetClient = SaturnEnvironment.GetHabboById(RANDOM_WIN[RandomUser]);

                    Session.SendWhisper("The random user was: " + TargetClient.Username + " ! Won " + lotto.ValueTotal + " credits!", 34);

                    LottoManager.Desactive(LottoIdentificator, true);
                    SaturnEnvironment.GetGame().GetLotto().Init(SaturnEnvironment.GetDatabaseManager().GetQueryReactor());

                    if (!TargetClient.Online)
                    {
                        LottoManager.UpdateTypesCoins(RANDOM_WIN[RandomUser], lotto.ValueTotal, true);
                        return;
                    }
                    else
                    {
                        TargetClient.Credits += lotto.ValueTotal;
                        TargetClient.GetClient().SendMessage(new CreditBalanceComposer(TargetClient.Credits));

                        TargetClient.GetClient().SendNotification("Hi! You won the lottery " + lotto.LottoName + " and with an amazing pot of " + lotto.ValueTotal + " credits!");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Logging.LogCriticalException(e.ToString());
                }
            }
            else
            {
                Session.SendWhisper("Oops, the lottery is not available!", 34);
                return;
            }
        }
    }
}

3- Now go to folder HabboHotel> and create new folder "Lotto"
Create a new file with the name: LottoItem.cs
C#:
using System;
using System.Collections.Generic;

namespace Saturn.HabboHotel.Lotto
{
    internal class LottoItem
    {
        public int Id;
        public string LottoName;
        public List<int> Users;
        public int ValueTotal;
        public bool Enabled;

        public LottoItem(int id, string lottoName, string users, int valueTotal, bool enabled)
        {
            this.Id = id;
            this.LottoName = lottoName;
            this.Users = new List<int>();
            this.ValueTotal = valueTotal;
            this.Enabled = enabled;

            foreach (var userId in users.ToString().Split(','))
            {
                if (string.IsNullOrEmpty(userId.ToString()))
                    continue;

                Users.Add(Convert.ToInt32(userId));
            }
        }
    }
}

Create new file with the name: LottoManager.cs
C#:
#region
using Saturn.Database.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
#endregion

namespace Saturn.HabboHotel.Lotto
{
    internal class LottoManager
    {
        public Dictionary<int, LottoItem> lotto;

        internal LottoManager()
        {
            lotto = new Dictionary<int, LottoItem>();
            Init(SaturnEnvironment.GetDatabaseManager().GetQueryReactor());
        }

        internal void Init(IQueryAdapter dbClient)
        {
            if (lotto.Count > 0)
                lotto.Clear();

            dbClient.SetQuery("SELECT `id`, `lotto_name`, `users`, `value_total`, `enabled` FROM `lotto_config`");
            DataTable GetLotto = dbClient.getTable();

            if (GetLotto != null)
            {
                foreach(DataRow row in GetLotto.Rows)
                {
                    lotto.Add(Convert.ToInt32(row["id"]), new LottoItem(Convert.ToInt32(row["id"]), Convert.ToString(row["lotto_name"]), Convert.ToString(row["users"]), Convert.ToInt32(row["value_total"]), SaturnEnvironment.EnumToBool(row["enabled"].ToString())));
                }
            }
        }

        public static string UpdatesInfos(int Id, string Users, int Discount, bool UpdateUsers, bool UpdateValueTotal)
        {
            string name = "";

            if (UpdateUsers)
            {
                using (IQueryAdapter dbClient = SaturnEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.runFastQuery("UPDATE `lotto_config` SET `users`='" + Users + "' WHERE `id`=" + Id + "");
                }
            }

            if (UpdateValueTotal)
            {
                using (IQueryAdapter dbClient = SaturnEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.runFastQuery("UPDATE `lotto_config` SET `value_total`=value_total + " + Discount + " WHERE `id`=" + Id + "");
                }
            }

            return name;
        }

        public static int UpdateTypesCoins(int UserId, int ValueTotal, bool Credits)
        {
            int value = 0;

            if (Credits)
            {
                using (IQueryAdapter dbClient = SaturnEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.runFastQuery("UPDATE `users` SET `credits`= credits + " + ValueTotal + " WHERE `id`=" + UserId + " LIMIT 1");
                }
            }

            return value;
        }

        public static string Desactive(int Id, bool Desactive)
        {
            string name = "";

            if (Desactive)
            {
                using (IQueryAdapter dbClient = SaturnEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.runFastQuery("UPDATE `lotto_config` SET `enabled`='0' WHERE `id`=" + Id + "");
                }
            }

            return name;
        }

        public bool TryGet(int Id, out LottoItem Ident)
        {
            if (this.lotto.TryGetValue(Id, out Ident))
                return true;
            return false;
        }
    }
}

4- Open the file Game.cs (Plus>HabboHotel)
and insert after:
public class Game
{
this:​
Code:
   private readonly LottoManager _lottoM;

After:
public Game()
{
add:​
Code:
            this._lottoM = new LottoManager();

after public void StopGameLoop()
{
code etc..
}
add this:

Code:
internal LottoManager GetLotto()
        {
            return _lottoM;
        }

Don't forget add the using​
Code:
using Saturn.HabboHotel.Lotto;

5- Open the file CommandManager.cs (commands xd)
After:
private void RegisterUser()
{
add:​
Code:
            Register("plotto", new LottoParticipateCommand());

After:
private void RegisterAdministrator()
{
add:​
Code:
            Register("lottopen", new LottoOpenCommand());

6- Add in your table permissions_commands:
command_lotto_participate and command_lotto_open

7- Run this:​
SQL:
INSERT INTO `server_settings` (`variable`, `value`, `description`) VALUES ('lotto.id', '1', 'Lotto Identificator to use (id).');
INSERT INTO `server_settings` (`variable`, `value`, `description`) VALUES ('lotto.max.participants.per.user', '10', 'Limit participants per user (10).');
INSERT INTO `server_settings` (`variable`, `value`, `description`) VALUES ('lotto.discount.credits', '100', 'Discount credits (100).')

8- Create the table:​
Code:
CREATE TABLE `lotto_config` (
    `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
    `lotto_name` VARCHAR(125) NOT NULL,
    `users` MEDIUMTEXT NOT NULL,
    `value_total` INT(11) NOT NULL DEFAULT '0',
    `enabled` ENUM('0','1') NOT NULL DEFAULT '1',
    PRIMARY KEY (`id`),
    UNIQUE INDEX `lotto_name` (`lotto_name`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2
;

Debug and be happy!

Credits:
Pollak (Snaiker)

 

Damien

Don't need glasses if you can C#
Feb 26, 2012
425
638
Some parts of this release are badly coded. I'll just bring up the one big mistake you are doing below:


C#:
            int LottoDiscount = Convert.ToInt32(SaturnEnvironment.GetDBConfig().DBData["lotto.discount.credits"]);
            int LottoMaxParticipants = Convert.ToInt32(SaturnEnvironment.GetDBConfig().DBData["lotto.max.participants.per.user"]);
            int LottoIdentificator = Convert.ToInt32(SaturnEnvironment.GetDBConfig().DBData["lotto.id"]);

Why are you using server_settings for a feature? Make a table lotto_settings place it there instead.

This is wrong way of thinking.
The server settings contain all the configurable data for the server. This is exactly how I'd do it if I was creating a lottery system or anything else for that matter. Creating a settings table for every feature you have is bad (imo), it gets confusing very quickly and if anyone decided to use your work they could easily get lost or annoyed having to configure settings in numerous database tables.
 

Pollak

Active Member
Oct 12, 2017
161
51
Some parts of this release are badly coded. I'll just bring up the one big mistake you are doing below:


C#:
            int LottoDiscount = Convert.ToInt32(SaturnEnvironment.GetDBConfig().DBData["lotto.discount.credits"]);
            int LottoMaxParticipants = Convert.ToInt32(SaturnEnvironment.GetDBConfig().DBData["lotto.max.participants.per.user"]);
            int LottoIdentificator = Convert.ToInt32(SaturnEnvironment.GetDBConfig().DBData["lotto.id"]);

Why are you using server_settings for a feature? Make a table lotto_settings place it there instead.

This is wrong way of thinking.
I decided use the table server_settings because is more simple :)
Post automatically merged:

The server settings contain all the configurable data for the server. This is exactly how I'd do it if I was creating a lottery system or anything else for that matter. Creating a settings table for every feature you have is bad (imo), it gets confusing very quickly and if anyone decided to use your work they could easily get lost or annoyed having to configure settings in numerous database tables.
Exactly.
 

Users who are viewing this thread

Top