コード例 #1
0
ファイル: FuelCommand.cs プロジェクト: Fooxboy/HydraBot
        public void Execute(Message msg, IMessageSenderService sender, IBot bot)
        {
            if (!Main.Api.Users.CheckUser(msg))
            {
                var kb2 = new KeyboardBuilder(bot);
                kb2.AddButton("➕ Зарегистрироваться", "start");
                sender.Text("❌ Вы не зарегистрированы, нажмите на кнопку ниже, чтобы начать", msg.ChatId, kb2.Build());
                return;
            }

            var user = Main.Api.Users.GetUser(msg);

            //todo: проверка

            var array = msg.Text.Split(" ");

            Models.Garage garageUser = null;
            try
            {
                var id = long.Parse(array[1]);
                garageUser = Main.Api.Garages.GetGarage(id);
            }catch
            {
                sender.Text("❌ Вы указали неверно Id пользователя", msg.ChatId);
                return;
            }

            long count;

            try
            {
                count = long.Parse(array[2]);
            }catch
            {
                sender.Text("❌ Вы указали неверно количество топлива", msg.ChatId);
                return;
            }

            var fuel = Main.Api.Garages.AddFuel(garageUser.UserId, count);

            sender.Text($"✔ У пользователя с ID {garageUser.UserId} теперь {fuel} топлива!", msg.ChatId);
        }
コード例 #2
0
        protected override void Seed(GoaGaraget.DataAccessLayer.GarageDbContext context)
        {
            List <ParkingSpace> pss = new List <ParkingSpace>();

            Models.VehicleType vt1 = new Models.VehicleType(1, "Car", 1);
            Models.VehicleType vt2 = new Models.VehicleType(2, "Motorcycle", 1);
            Models.VehicleType vt3 = new Models.VehicleType(3, "Lorry", 3);
            Models.VehicleType vt4 = new Models.VehicleType(4, "Truck", 5);
            context.VehicleTypes.AddOrUpdate(vt1);
            context.VehicleTypes.AddOrUpdate(vt2);
            context.VehicleTypes.AddOrUpdate(vt3);
            context.VehicleTypes.AddOrUpdate(vt4);

            Models.Member M1 = new Models.Member(1, "Kalle", "Svensson", 1234, 20, "010101-1234");
            Models.Member M2 = new Models.Member(2, "Peter", "Stalefäldt", 1234, 20, "990101-1234");
            context.Members.AddOrUpdate(M1);
            context.Members.AddOrUpdate(M2);

            Models.Garage G1 = new Models.Garage("Garage 2.1", 30, 24);
            G1.Id = 0;
            context.Garages.AddOrUpdate(G1);

            for (int i = 0; i < 30; i++)
            {
                ParkingSpace ps = new ParkingSpace
                {
                    Id               = i,
                    Price            = 35,
                    IsEmpty          = true,
                    IsMcParkingSpace = false,
                    ParkedVehicles   = new List <ParkedVehicle>(),
                    McCountMax       = 3,
                    TotalIncome      = 0,
                    VisitorCount     = 0,
                    AverageTime      = new TimeSpan(0, 0, 0),
                    Garage           = G1
                };
                context.ParkingSpaces.AddOrUpdate(ps);
                pss.Add(ps);
            }
            Models.ParkedVehicle pv1  = new Models.ParkedVehicle(M1, "ABC123", "röd", vt3, "Volvo", 4, DateTime.Now);
            Models.ParkedVehicle pv2  = new Models.ParkedVehicle(M2, "ABC124", "blue", vt1, "Lancia", 4, DateTime.Now);
            Models.ParkedVehicle pv3  = new Models.ParkedVehicle(M2, "ABC125", "grön", vt4, "Tesla", 8, DateTime.Now);
            Models.ParkedVehicle pv4  = new Models.ParkedVehicle(M1, "ABC623", "röd", vt3, "Renault", 4, DateTime.Now);
            Models.ParkedVehicle pv5  = new Models.ParkedVehicle(M1, "ABf124", "blue", vt1, "Lancia", 4, DateTime.Now);
            Models.ParkedVehicle pv6  = new Models.ParkedVehicle(M2, "ABs125", "grön", vt4, "Mitsubishi", 8, DateTime.Now);
            Models.ParkedVehicle pv7  = new Models.ParkedVehicle(M2, "ABj143", "röd", vt3, "Fiat", 6, DateTime.Now);
            Models.ParkedVehicle pv8  = new Models.ParkedVehicle(M1, "gfC194", "blue", vt1, "Lancia", 4, DateTime.Now);
            Models.ParkedVehicle pv9  = new Models.ParkedVehicle(M1, "tyC625", "Grå", vt2, "Yamaha CBR", 2, DateTime.Now);
            Models.ParkedVehicle pv10 = new Models.ParkedVehicle(M1, "tyC624", "Grå", vt2, "Suzuki", 2, DateTime.Now);
            Models.ParkedVehicle pv11 = new Models.ParkedVehicle(M1, "tyC627", "Grå", vt2, "Honda Lead", 2, DateTime.Now);
            Models.ParkedVehicle pv12 = new Models.ParkedVehicle(M1, "tyC620", "Grå", vt2, "Bmw 15000", 2, DateTime.Now);
            Models.ParkedVehicle pv13 = new Models.ParkedVehicle(M1, "tyC621", "Grå", vt2, "Hyundai", 2, DateTime.Now);
            pv1.Id = 1; pv2.Id = 2; pv3.Id = 3; pv4.Id = 4; pv5.Id = 5;
            pv6.Id = 6; pv7.Id = 7; pv8.Id = 8; pv9.Id = 9;; pv9.Id = 10;; pv9.Id = 11;; pv9.Id = 12;; pv9.Id = 13;
            context.ParkedVehicles.AddOrUpdate(pv1);
            context.ParkedVehicles.AddOrUpdate(pv2);
            context.ParkedVehicles.AddOrUpdate(pv3);
            context.ParkedVehicles.AddOrUpdate(pv4);
            context.ParkedVehicles.AddOrUpdate(pv5);
            context.ParkedVehicles.AddOrUpdate(pv6);
            context.ParkedVehicles.AddOrUpdate(pv7);
            context.ParkedVehicles.AddOrUpdate(pv8);
            context.ParkedVehicles.AddOrUpdate(pv9);
            context.ParkedVehicles.AddOrUpdate(pv10);
            context.ParkedVehicles.AddOrUpdate(pv11);
            context.ParkedVehicles.AddOrUpdate(pv12);
            context.ParkedVehicles.AddOrUpdate(pv13);
        }
コード例 #3
0
ファイル: RaceStartCommand.cs プロジェクト: Fooxboy/HydraBot
        public void Execute(Message msg, IMessageSenderService sender, IBot bot)
        {
            if (Main.Api.Users.IsBanned(msg))
            {
                return;
            }

            if (!Main.Api.Users.CheckUser(msg))
            {
                var kb2 = new KeyboardBuilder(bot);
                kb2.AddButton("➕ Зарегистрироваться", "start");
                sender.Text("❌ Вы не зарегистрированы, нажмите на кнопку ниже, чтобы начать", msg.ChatId, kb2.Build());
                return;
            }

            Models.Race race        = null;
            User        userEnemy   = null;
            User        userCreator = null;

            Models.Garage garageEnemy        = null;
            Models.Garage garageCreator      = null;
            var           kb                 = new KeyboardBuilder(bot);
            Car           carCreator         = null;
            Car           carEnemy           = null;
            bool          sendMessageToEnemy = true;
            bool          isBot              = false;
            bool          isFriendStart      = false;

            if (msg.Payload.Arguments.Count == 0)
            {
                if (msg.Payload.Arguments[0] == "222")
                {
                    isFriendStart = true;
                }
                userEnemy = Main.Api.Users.GetUser(msg);
                if (userEnemy.OnWork)
                {
                    sender.Text("❌ Вы не можете идти в гонку, пока находитесь на работе, дождитесь завершения и возвращайтесь!", msg.ChatId);
                    return;
                }
                //Пользователь принимает гонку.
                isBot = false;
                using (var db = new Database())
                {
                    try
                    {
                        race = db.Races.FirstOrDefault(r => r.Enemy == userEnemy.Id && r.IsRequest == true);
                    }catch
                    {
                        kb.AddButton(ButtonsHelper.ToHomeButton());
                        sender.Text("❌ Ваш противник уже отменил гонку!", msg.ChatId, kb.Build());
                        var a = db.Users.Single(u => u.Id == userEnemy.Id);
                        a.Race = 0;
                        db.SaveChanges();
                        return;
                    }

                    if (race is null)
                    {
                        kb.AddButton(ButtonsHelper.ToHomeButton());
                        sender.Text("❌ Мы не смогли найти эту гонку в базе данных.", msg.ChatId, kb.Build());
                        var a = db.Users.Single(u => u.Id == userEnemy.Id);
                        a.Race = 0;
                        db.SaveChanges();
                        return;
                    }

                    userCreator   = db.Users.Single(u => u.Id == race.Creator);
                    garageCreator = db.Garages.Single(g => g.UserId == userCreator.Id);
                    carCreator    = db.Cars.Single(c => c.Id == garageCreator.SelectCar);

                    race.IsRequest = false;
                    garageEnemy    = db.Garages.Single(g => g.UserId == userEnemy.Id);
                    var usrE = db.Users.Single(u => u.Id == userEnemy.Id);
                    carEnemy  = db.Cars.Single(c => c.Id == garageEnemy.SelectCar);
                    usrE.Race = race.Id;
                    db.SaveChanges();
                }
            }
            else
            {
                //если какой-то тип
                var typeRace = msg.Payload.Arguments[0].ToLong();
                if (typeRace == 1) //если это быстрая гонка
                {
                    var enemyId = msg.Payload.Arguments[1].ToLong();

                    race           = new Models.Race();
                    userCreator    = Main.Api.Users.GetUser(msg);
                    garageCreator  = Main.Api.Garages.GetGarage(userCreator.Id);
                    race.Creator   = userCreator.Id;
                    race.Enemy     = enemyId;
                    race.IsRequest = false;

                    using (var db = new Database())
                    {
                        carCreator = db.Cars.Single(c => c.Id == garageCreator.SelectCar);
                        race.Id    = db.Races.Count() + 1;
                        db.Races.Add(race);
                        db.SaveChanges();
                    }



                    if (enemyId == -2) //генерим бота
                    {
                        sendMessageToEnemy = false;
                        isBot          = true;
                        userEnemy      = new User();
                        userEnemy.Id   = -2;
                        userEnemy.Name = "Бот без имени";

                        garageEnemy           = new Models.Garage();
                        carEnemy              = new Car();
                        carEnemy.Id           = -2;
                        carEnemy.Manufacturer = "abc";
                        carEnemy.Model        = "def";

                        var r = new Random();

                        int a = r.Next(1, 3);

                        carEnemy.Power = a == 2 ? carCreator.Power + 1 : carCreator.Power - 1;

                        int b = r.Next(1, 3);
                    }
                    else
                    {
                        using (var db = new Database())
                        {
                            userEnemy   = db.Users.Single(u => u.Id == enemyId);
                            garageEnemy = db.Garages.Single(g => g.UserId == enemyId);
                            carEnemy    = db.Cars.Single(c => c.Id == garageEnemy.SelectCar);
                        }
                    }
                }
            }

            long enemyChatId   = 0;
            long creatorChatId = 0;

            if (sender.Platform == Fooxboy.NucleusBot.Enums.MessengerPlatform.Vkontakte)
            {
                if (sendMessageToEnemy && !isBot)
                {
                    enemyChatId = userEnemy.VkId;
                }
                creatorChatId = userCreator.VkId;
            }
            else
            {
                if (sendMessageToEnemy && !isBot)
                {
                    enemyChatId = userEnemy.TgId;
                }
                creatorChatId = userCreator.TgId;
            }
            if (sendMessageToEnemy && !isBot)
            {
                Task.Run(() => sender.Text($"🏁 Гонка с игроком {userCreator.Name} на автомобиле {carCreator.Manufacturer} {carCreator.Model} ({carCreator.Number}) началась! Не переходите по разделам во время гонки", enemyChatId));
            }
            Task.Run(() => sender.Text($"🏁 Гонка с игроком {userEnemy.Name} на автомобиле {carEnemy.Manufacturer} {carEnemy.Model} ({carEnemy.Number}) началась! Не переходите по разделам во время гонки", creatorChatId));


            Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(5));
                long scoreCreator = 0;
                long scoreEnemy   = 0;
                if (carEnemy.Power > carCreator.Power)
                {
                    scoreEnemy += 5;
                }
                else
                {
                    scoreCreator += 5;
                }

                if (carEnemy.Weight > carCreator.Weight)
                {
                    scoreCreator += 3;
                }
                else
                {
                    scoreEnemy += 3;
                }

                Skills skillsCretor = null;
                Skills skillsEnemy  = null;

                using (var db = new Database())
                {
                    try
                    {
                        skillsCretor = db.Skillses.Single(s => s.UserId == userCreator.Id);
                    }
                    catch
                    {
                        skillsCretor = new Skills();
                    }

                    try
                    {
                        if (isBot)
                        {
                            //генерируем рандомный скилл
                            skillsEnemy         = new Skills();
                            var r               = new Random();
                            int i               = r.Next(1, 3);
                            skillsEnemy.Driving = i == 2? skillsCretor.Driving - 1 : skillsCretor.Driving + 1;
                        }
                        else
                        {
                            skillsEnemy = db.Skillses.Single(s => s.UserId == userEnemy.Id);
                        }
                    }
                    catch
                    {
                        if (isBot)
                        {
                            //генерируем рандомный скилл
                            skillsEnemy         = new Skills();
                            skillsEnemy.Driving = 0;
                        }
                        else
                        {
                            skillsEnemy = new Skills();
                        }
                    }
                }

                //тут считаем навыки

                scoreCreator += skillsCretor.Driving;
                scoreEnemy   += skillsEnemy.Driving;

                var winner = scoreEnemy > scoreCreator ? userEnemy : userCreator;

                using (var db = new Database())
                {
                    var raceLocal = db.Races.Single(r => r.Id == race.Id);
                    if (raceLocal.Winner != 0)
                    {
                        winner = db.Users.Single(u => u.Id == raceLocal.Winner);
                    }
                    raceLocal.Winner = winner.Id;

                    if (winner.Id != -2)
                    {
                        if (!isFriendStart)
                        {
                            //Добавляем опыта и денег победителю.
                            var winnerLocal = db.Users.Single(u => u.Id == winner.Id);
                            int factor      = 1;
                            if (winnerLocal.Access >= 1)
                            {
                                factor = 2;
                            }
                            winnerLocal.Money += (winnerLocal.Level * factor * 50);
                            winnerLocal.Score += (10 * factor);
                        }
                    }
                    var usr1 = db.Users.Single(u => u.Id == raceLocal.Creator);
                    var gar1 = db.Garages.Single(u => u.UserId == usr1.Id);
                    var car1 = db.Cars.Single(c => c.Id == carCreator.Id);
                    //gar1.Fuel = gar1.Fuel - 5;
                    car1.Health = car1.Health - 5;
                    if (!isBot)
                    {
                        var usr2 = db.Users.Single(u => u.Id == raceLocal.Enemy);
                        var gar2 = db.Garages.Single(u => u.UserId == usr2.Id);
                        var car2 = db.Cars.Single(c => c.Id == carEnemy.Id);
                        // gar2.Fuel = gar2.Fuel - 5;
                        car2.Health = car2.Health - 5;
                        usr2.Race   = 0;
                    }
                    usr1.Race = 0;
                    db.SaveChanges();
                }

                if (winner.Id != -2)
                {
                    Task.Run(() =>
                    {
                        var kb1 = new KeyboardBuilder(bot);
                        kb1.AddButton("🏁 Назад в гонки", "race");
                        var t = isFriendStart
                            ? "🎉 Поздравляю с победой  над своим другом!"
                            : $"🎉 Поздравляю с победой! Вы получили: 💵 {(winner.Access >=1? $"{winner.Level *50 *2}": $"{winner.Level * 50}")} рублей и ⭐ {(winner.Access >=1? $"{10 *2}": $"{10}")} опыта";
                        sender.Text(
                            t,
                            winner.Id == userEnemy.Id ? enemyChatId : creatorChatId, kb1.Build());

                        sender.Text($"🏁 Вы проиграли в этой гонке.", winner.Id == userEnemy.Id ? creatorChatId : enemyChatId, kb1.Build());
                    });
                }
コード例 #4
0
ファイル: StartCommand.cs プロジェクト: Fooxboy/HydraBot
        public void Execute(Fooxboy.NucleusBot.Models.Message msg, IMessageSenderService sender, IBot bot)
        {
            if (Main.Api.Users.IsBanned(msg))
            {
                return;
            }

            //проверка на регистрацию.
            if (_api.Users.CheckUser(msg))
            {
                var kb2 = new KeyboardBuilder(bot);
                kb2.AddButton(ButtonsHelper.ToHomeButton());
                sender.Text("✔ Вы уже зарегистрированы, перейдите на главный экран!", msg.ChatId, kb2.Build());
                return;
            }

            //регистрация нового юзера.
            var user = new HydraBot.Models.User();

            user.Access          = 0;
            user.IsBanned        = false;
            user.Level           = 1;
            user.Prefix          = "Игрок";
            user.Score           = 0;
            user.TimeBan         = 0;
            user.BonusDay        = 1;
            user.SubOnNews       = true;
            user.Money           = 100000;
            user.DriverLicense   = "";
            user.IsAvailbleBonus = true;
            user.TimeBonus       = 0;
            if (msg.Platform == MessengerPlatform.Vkontakte)
            {
                //устанавливаем id ВКонтакте в зависимости от того куда написал пользователь. В беседу или в лс.
                if (msg.ChatId < 2000000000)
                {
                    user.VkId = msg.ChatId;
                }
                else
                {
                    user.VkId = msg.MessageVK.FromId.Value;
                }

                //устанавливаем никнейм
                var vkapi = new VkApi();
                vkapi.Authorize(new ApiAuthParams()
                {
                    AccessToken = Main.Token
                });
                var userName = vkapi.Users.Get(new List <long>()
                {
                    msg.MessageVK.FromId.Value
                })[0].FirstName;
                user.Name = userName;
            }
            //устанавливаем id Телеграмма.
            else
            {
                user.TgId = msg.MessageTG.From.Id;
                user.Name = msg.MessageTG.From.FirstName;
            }

            //добавляем пользователя в бд.
            var id = _api.Users.AddUser(user);

            user.Id = id;

            var garage = new Models.Garage()
            {
                Cars = "", PhoneNumber = null, Name = "no", IsPhone = false, Engines = "", Fuel = 9999999999999, GarageModelId = -1, SelectCar = -1, ParkingPlaces = 0, UserId = id
            };

            Main.Api.Garages.RegisterGarage(garage);

            var skills = new Skills();

            skills.UserId = id;
            using (var db = new Database())
            {
                db.Skillses.Add(skills);
                db.SaveChanges();
            }

            var kb = new KeyboardBuilder(bot);

            kb.AddButton(ButtonsHelper.ToHomeButton());
            sender.Text("✔ Вы успешно зарегистрировались! Перейдите на главный экран, нажав на кнопку домой.", msg.ChatId, kb.Build());
        }