Exemple #1
0
        public static async Task DeleteTaxonAsync(this SQLiteDatabase database, ITaxon taxon)
        {
            string tableName         = GetTableNameForRank(taxon.GetRank());
            string subtaxaCommonName = GetTableNameForRank(taxon.GetChildRank());
            string subtaxaColumnName = GetFieldNameForRank(taxon.GetRank());

            // Set to NULL any references subtaxa have to this taxon.
            // Note that this can also happen automatically if the foreign key is set up correctly when creating the database.

            if (!string.IsNullOrEmpty(tableName) && !string.IsNullOrEmpty(subtaxaColumnName))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(string.Format("UPDATE {0} SET {1} = NULL WHERE {1} = $id", subtaxaCommonName, subtaxaColumnName))) {
                    cmd.Parameters.AddWithValue("$id", taxon.Id);

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }

            // Delete the taxon.

            if (!string.IsNullOrEmpty(tableName))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(string.Format("DELETE FROM {0} WHERE id = $id", tableName))) {
                    cmd.Parameters.AddWithValue("$id", taxon.Id);

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }
        }
Exemple #2
0
        // Public members

        public static async Task AddTaxonAsync(this SQLiteDatabase database, ITaxon taxon)
        {
            string tableName = GetTableNameForRank(taxon.Rank.Type);

            if (!string.IsNullOrEmpty(tableName))
            {
                string parentFieldName = GetFieldNameForRank(TaxonUtilities.GetParentRank(taxon.Rank.Type));

                string query;

                if (!string.IsNullOrEmpty(parentFieldName) && taxon.ParentId > 0)
                {
                    query = string.Format("INSERT OR IGNORE INTO {0}(name, description, pics, {1}) VALUES($name, $description, $pics, $parent_id)", tableName, parentFieldName);
                }
                else
                {
                    query = string.Format("INSERT OR IGNORE INTO {0}(name, description, pics) VALUES($name, $description, $pics)", tableName);
                }

                using (SQLiteCommand cmd = new SQLiteCommand(query)) {
                    cmd.Parameters.AddWithValue("$name", taxon.Name.ToLowerInvariant());
                    cmd.Parameters.AddWithValue("$description", taxon.Description);
                    cmd.Parameters.AddWithValue("$pics", taxon.Pictures.FirstOrDefault()?.Url);

                    if (!string.IsNullOrEmpty(parentFieldName) && taxon.ParentId > 0)
                    {
                        cmd.Parameters.AddWithValue("$parent_column", parentFieldName);
                        cmd.Parameters.AddWithValue("$parent_id", taxon.ParentId);
                    }

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }
        }
        public static async Task RemovePictureAsync(this SQLiteDatabase database, IPictureGallery gallery, IPicture picture)
        {
            if (gallery is null)
            {
                throw new ArgumentNullException(nameof(gallery));
            }

            if (picture is null)
            {
                throw new ArgumentNullException(nameof(picture));
            }

            if (!picture.Id.HasValue)
            {
                throw new ArgumentException(nameof(picture));
            }

            if (!gallery.Id.HasValue)
            {
                throw new ArgumentException(nameof(gallery));
            }

            using (SQLiteCommand cmd = new SQLiteCommand("DELETE FROM Picture WHERE gallery_id = $gallery_id AND id = $id")) {
                cmd.Parameters.AddWithValue("$id", picture.Id);
                cmd.Parameters.AddWithValue("$gallery_id", gallery.Id);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
Exemple #4
0
        private static async Task DeleteGenerationAsync(this SQLiteDatabase database, IGeneration generation)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("DELETE FROM Period WHERE id = $id")) {
                cmd.Parameters.AddWithValue("$id", generation.Id);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
        private static async Task RemoveZoneFieldsAsync(this SQLiteDatabase database, IZone zone)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("DELETE FROM ZoneFields WHERE zone_id = $zone_id")) {
                cmd.Parameters.AddWithValue("$zone_id", zone.Id);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
        public static async Task DeleteGotchiAsync(this SQLiteDatabase database, long gotchiId)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("DELETE FROM Gotchi WHERE id = $id")) {
                cmd.Parameters.AddWithValue("$id", gotchiId);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
        private static async Task AddGalleryAsync(this SQLiteDatabase database, string name)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("INSERT OR IGNORE INTO Gallery(name) VALUES($name)")) {
                cmd.Parameters.AddWithValue("$name", name);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
        // Public members

        public static async Task AddRoleAsync(this SQLiteDatabase database, IRole role)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("INSERT INTO Roles(name, description) VALUES($name, $description)")) {
                cmd.Parameters.AddWithValue("$name", role.Name.ToLowerInvariant());
                cmd.Parameters.AddWithValue("$description", role.Description);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
        public static async Task SetViewedTimestampAsync(this SQLiteDatabase database, long gotchiId, long viewedTimestamp)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET viewed_ts = $viewed_ts WHERE id = $id")) {
                cmd.Parameters.AddWithValue("$id", gotchiId);
                cmd.Parameters.AddWithValue("$viewed_ts", viewedTimestamp);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
Exemple #10
0
        private static async Task AddGenerationAsync(this SQLiteDatabase database, IGeneration generation)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("INSERT INTO Period(name, start_ts, end_ts) VALUES($name, $start_ts, $end_ts)")) {
                cmd.Parameters.AddWithValue("$name", generation.Name.ToLowerInvariant());
                cmd.Parameters.AddWithValue("$start_ts", DateUtilities.GetTimestampFromDate(generation.StartDate));
                cmd.Parameters.AddWithValue("$end_ts", DateUtilities.GetTimestampFromDate(generation.EndDate));

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
Exemple #11
0
        public static async Task ExecuteTradeRequestAsync(ICommandContext context, SQLiteDatabase db, GotchiTradeRequest tradeRequest)
        {
            // Get both users and their gotchis.

            IUser user1 = await context.Guild.GetUserAsync(tradeRequest.OfferedGotchi.OwnerId);

            Gotchi gotchi1 = await db.GetGotchiAsync(user1.ToCreator());

            GotchiUserInfo userInfo1 = await db.GetUserInfoAsync(user1.ToCreator());

            IUser user2 = await context.Guild.GetUserAsync(tradeRequest.ReceivedGotchi.OwnerId);

            Gotchi gotchi2 = await db.GetGotchiAsync(user2.ToCreator());

            GotchiUserInfo userInfo2 = await db.GetUserInfoAsync(user2.ToCreator());

            // Swap the owners of the gotchis.

            using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET owner_id = $owner_id WHERE id = $id")) {
                cmd.Parameters.AddWithValue("$owner_id", user1.Id);
                cmd.Parameters.AddWithValue("$id", gotchi2.Id);

                await db.ExecuteNonQueryAsync(cmd);
            }

            userInfo1.PrimaryGotchiId = gotchi2.Id;

            await db.UpdateUserInfoAsync(userInfo1);

            using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET owner_id = $owner_id WHERE id = $id")) {
                cmd.Parameters.AddWithValue("$owner_id", user2.Id);
                cmd.Parameters.AddWithValue("$id", gotchi1.Id);

                await db.ExecuteNonQueryAsync(cmd);
            }

            userInfo2.PrimaryGotchiId = gotchi1.Id;

            await db.UpdateUserInfoAsync(userInfo2);

            // Remove all existing trade requests involving either user.
            _trade_requests.RemoveAll(x => x.OfferedGotchi.OwnerId == user1.Id || x.ReceivedGotchi.OwnerId == user2.Id);
        }
        public static async Task SetGotchiNameAsync(this SQLiteDatabase database, Gotchi gotchi, string name)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET name = $name WHERE owner_id = $owner_id AND id = $id")) {
                cmd.Parameters.AddWithValue("$name", name.ToLowerInvariant());
                cmd.Parameters.AddWithValue("$owner_id", gotchi.OwnerId);
                cmd.Parameters.AddWithValue("$id", gotchi.Id);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
        public static async Task AddZoneTypeAsync(this SQLiteDatabase database, IZoneType type)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("INSERT OR REPLACE INTO ZoneTypes(name, icon, color, description) VALUES($name, $icon, $color, $description)")) {
                cmd.Parameters.AddWithValue("$name", type.Name.ToLowerInvariant());
                cmd.Parameters.AddWithValue("$icon", type.Icon);
                cmd.Parameters.AddWithValue("$color", ColorTranslator.ToHtml(type.Color).ToLowerInvariant());
                cmd.Parameters.AddWithValue("$description", type.Description);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
        public static async Task AddZoneAsync(this SQLiteDatabase database, IZone zone)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("INSERT INTO Zones(name, type, type_id, description) VALUES($name, $type, $type_id, $description)")) {
                cmd.Parameters.AddWithValue("$name", zone.Name.ToLowerInvariant());
                cmd.Parameters.AddWithValue("$type", zone.Type?.Name.ToLowerInvariant() ?? string.Empty);
                cmd.Parameters.AddWithValue("$type_id", zone.TypeId);
                cmd.Parameters.AddWithValue("$description", zone.Description);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
Exemple #15
0
        private static async Task UpdateGenerationAsync(this SQLiteDatabase database, IGeneration generation)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Period SET name = $name, start_ts = $start_ts, end_ts = $end_ts WHERE id = $id")) {
                cmd.Parameters.AddWithValue("$id", generation.Id);
                cmd.Parameters.AddWithValue("$name", generation.Name.ToLowerInvariant());
                cmd.Parameters.AddWithValue("$start_ts", DateUtilities.GetTimestampFromDate(generation.StartDate));
                cmd.Parameters.AddWithValue("$end_ts", DateUtilities.GetTimestampFromDate(generation.EndDate));

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
        public static async Task UpdateUserInfoAsync(this SQLiteDatabase database, GotchiUserInfo userInfo)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("INSERT OR REPLACE INTO GotchiUser(user_id, g, gotchi_limit, primary_gotchi_id) VALUES ($user_id, $g, $gotchi_limit, $primary_gotchi_id)")) {
                cmd.Parameters.AddWithValue("$user_id", userInfo.UserId);
                cmd.Parameters.AddWithValue("$g", userInfo.G);
                cmd.Parameters.AddWithValue("$gotchi_limit", userInfo.GotchiLimit);
                cmd.Parameters.AddWithValue("$primary_gotchi_id", userInfo.PrimaryGotchiId);

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
        public static async Task AddPictureAsync(this SQLiteDatabase database, IPictureGallery gallery, IPicture picture)
        {
            if (gallery is null)
            {
                throw new ArgumentNullException(nameof(gallery));
            }

            if (picture is null)
            {
                throw new ArgumentNullException(nameof(picture));
            }

            if (!gallery.Id.HasValue)
            {
                throw new ArgumentException(nameof(gallery));
            }

            if (!picture.Id.HasValue)
            {
                using (SQLiteCommand cmd = new SQLiteCommand("INSERT OR IGNORE INTO Picture(url, gallery_id, artist, name, description) VALUES($url, $gallery_id, $artist, $name, $description)")) {
                    cmd.Parameters.AddWithValue("$url", picture.Url);
                    cmd.Parameters.AddWithValue("$gallery_id", gallery.Id);
                    cmd.Parameters.AddWithValue("$artist", picture.Artist?.Name ?? "");
                    cmd.Parameters.AddWithValue("$name", picture.Name);
                    cmd.Parameters.AddWithValue("$description", picture.Description);

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }
            else
            {
                using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Picture SET url = $url, artist = $artist, description = $description WHERE id = $id")) {
                    cmd.Parameters.AddWithValue("$id", picture.Id);
                    cmd.Parameters.AddWithValue("$url", picture.Url);
                    cmd.Parameters.AddWithValue("$artist", picture.Artist?.Name ?? "");
                    cmd.Parameters.AddWithValue("$description", picture.Description);

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }
        }
        private static async Task AddZoneAliasesAsync(this SQLiteDatabase database, IZone zone)
        {
            foreach (string alias in zone.Aliases.Select(alias => ZoneUtilities.GetFullName(alias).ToLowerInvariant()).Distinct())
            {
                using (SQLiteCommand cmd = new SQLiteCommand("INSERT OR IGNORE INTO ZoneAliases(zone_id, alias) VALUES($zone_id, $alias)")) {
                    cmd.Parameters.AddWithValue("$zone_id", zone.Id);
                    cmd.Parameters.AddWithValue("$alias", alias.ToLowerInvariant().SafeTrim());

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }
        }
        public static async Task UpdateRoleAsync(this SQLiteDatabase database, IRole role)
        {
            if (role.IsValid())
            {
                using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Roles SET name = $name, description = $description WHERE id = $id")) {
                    cmd.Parameters.AddWithValue("$id", role.Id);
                    cmd.Parameters.AddWithValue("$name", role.Name.ToLowerInvariant());
                    cmd.Parameters.AddWithValue("$description", role.Description);

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }
        }
        public static async Task <int> FeedGotchisAsync(this SQLiteDatabase database, GotchiContext context, ulong userId)
        {
            // Although we only display the state of the primary Gotchi at the moment, update the feed time for all Gotchis owned by this user.
            // Only Gotchis that are still alive (i.e. have been fed recently enough) get their timestamp updated.

            using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET fed_ts = $fed_ts WHERE owner_id = $owner_id AND fed_ts >= $min_ts")) {
                cmd.Parameters.AddWithValue("$fed_ts", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
                cmd.Parameters.AddWithValue("$owner_id", userId);
                cmd.Parameters.AddWithValue("$min_ts", context.MinimumFedTimestamp());

                return(await database.ExecuteNonQueryAsync(cmd));
            }
        }
        public static async Task UnlockTrophyAsync(this SQLiteDatabase database, ICreator creator, ITrophy trophy)
        {
            if (creator.UserId.HasValue)
            {
                using (SQLiteCommand cmd = new SQLiteCommand("INSERT OR IGNORE INTO Trophies(user_id, trophy_name, timestamp) VALUES($user_id, $trophy_name, $timestamp);")) {
                    cmd.Parameters.AddWithValue("$user_id", creator.UserId);
                    cmd.Parameters.AddWithValue("$trophy_name", trophy.Identifier);
                    cmd.Parameters.AddWithValue("$timestamp", DateUtilities.GetCurrentTimestampUtc());

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }
        }
        private static async Task AddZoneFieldsAsync(this SQLiteDatabase database, IZone zone)
        {
            foreach (IZoneField field in zone.Fields)
            {
                using (SQLiteCommand cmd = new SQLiteCommand("INSERT OR REPLACE INTO ZoneFields(zone_id, name, value) VALUES($zone_id, $name, $value)")) {
                    cmd.Parameters.AddWithValue("$zone_id", zone.Id);
                    cmd.Parameters.AddWithValue("$name", field.Name.ToLowerInvariant().SafeTrim());
                    cmd.Parameters.AddWithValue("$value", field.Value.ToLowerInvariant().SafeTrim());

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }
        }
        // Public members

        public static async Task AddGotchiAsync(this SQLiteDatabase database, ICreator user, ISpecies species)
        {
            // Generate a unique name for the user's gotchi, but duplicate names are allowed if necessary (e.g. all generated names exhausted).

            IEnumerable <Gotchi> existingGotchis = await database.GetGotchisAsync(user);

            IGotchiNameGenerator nameGenerator = new GotchiNameGenerator();

            string    name = nameGenerator.GetName(user, species);
            const int maxNamingAttempts = 10;

            for (int i = 0; i < maxNamingAttempts && existingGotchis.Any(gotchi => gotchi.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); ++i)
            {
                name = nameGenerator.GetName(user, species);
            }

            // Add the Gotchi to the database.

            long ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

            using (SQLiteCommand cmd = new SQLiteCommand("INSERT INTO Gotchi(species_id, name, owner_id, fed_ts, born_ts, died_ts, evolved_ts) VALUES($species_id, $name, $owner_id, $fed_ts, $born_ts, $died_ts, $evolved_ts)")) {
                cmd.Parameters.AddWithValue("$species_id", species.Id);
                cmd.Parameters.AddWithValue("$owner_id", user.UserId);
                cmd.Parameters.AddWithValue("$name", name.ToLower());
                cmd.Parameters.AddWithValue("$fed_ts", ts - 60 * 60); // subtract an hour to keep it from eating immediately after creation
                cmd.Parameters.AddWithValue("$born_ts", ts);
                cmd.Parameters.AddWithValue("$died_ts", 0);
                cmd.Parameters.AddWithValue("$evolved_ts", ts);

                await database.ExecuteNonQueryAsync(cmd);
            }

            // Set this gotchi as the user's primary Gotchi.

            GotchiUserInfo user_data = await database.GetUserInfoAsync(user);

            using (SQLiteCommand cmd = new SQLiteCommand("SELECT id FROM Gotchi WHERE owner_id = $owner_id AND born_ts = $born_ts")) {
                cmd.Parameters.AddWithValue("$owner_id", user.UserId);
                cmd.Parameters.AddWithValue("$born_ts", ts);

                user_data.PrimaryGotchiId = await database.GetScalarAsync <long>(cmd);
            }

            await database.UpdateUserInfoAsync(user_data);
        }
        public static async Task UpdateZoneAsync(this SQLiteDatabase database, IZone zone)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Zones SET name = $name, type = $type, type_id = $type_id, description = $description, parent_id = $parent_id, flags = $flags WHERE id = $id")) {
                cmd.Parameters.AddWithValue("$id", zone.Id);
                cmd.Parameters.AddWithValue("$parent_id", zone.ParentId);
                cmd.Parameters.AddWithValue("$name", zone.Name.ToLowerInvariant());
                cmd.Parameters.AddWithValue("$type", zone.Type?.Name.ToLowerInvariant() ?? string.Empty);
                cmd.Parameters.AddWithValue("$type_id", zone.TypeId);
                cmd.Parameters.AddWithValue("$description", zone.Description);
                cmd.Parameters.AddWithValue("$flags", (long)zone.Flags);

                await database.ExecuteNonQueryAsync(cmd);
            }

            await database.RemoveZoneAliasesAsync(zone);

            await database.AddZoneAliasesAsync(zone);

            await database.RemoveZoneFieldsAsync(zone);

            await database.AddZoneFieldsAsync(zone);
        }
Exemple #25
0
        public static async Task UpdateTaxonAsync(this SQLiteDatabase database, ITaxon taxon)
        {
            string tableName = GetTableNameForRank(taxon.GetRank());

            if (!string.IsNullOrEmpty(tableName))
            {
                string parentColumnName      = GetFieldNameForRank(taxon.GetParentRank());
                string updateParentColumnStr = string.Empty;

                if (!string.IsNullOrEmpty(parentColumnName) && taxon.ParentId.HasValue)
                {
                    updateParentColumnStr = string.Format(", {0}=$parent_id", parentColumnName);
                }

                using (SQLiteCommand cmd = new SQLiteCommand(string.Format("UPDATE {0} SET name = $name, description = $description, pics = $pics{1}, common_name = $common_name WHERE id = $id",
                                                                           tableName, updateParentColumnStr))) {
                    cmd.Parameters.AddWithValue("$id", taxon.Id);

                    cmd.Parameters.AddWithValue("$name", taxon.Name.ToLowerInvariant());
                    cmd.Parameters.AddWithValue("$description", taxon.Description);
                    cmd.Parameters.AddWithValue("$pics", taxon.GetPictureUrl());

                    // Because this field was added in a database update, it's possible for it to be null rather than the empty string.

                    cmd.Parameters.AddWithValue("$common_name", string.IsNullOrEmpty(taxon.GetCommonName()) ? "" : taxon.GetCommonName().ToLowerInvariant());

                    if (!string.IsNullOrEmpty(parentColumnName) && taxon.ParentId.HasValue)
                    {
                        cmd.Parameters.AddWithValue("$parent_column_name", parentColumnName);
                        cmd.Parameters.AddWithValue("$parent_id", taxon.ParentId);
                    }

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }
        }
        public static async Task <bool> EvolveAndUpdateGotchiAsync(this SQLiteDatabase database, Gotchi gotchi, string desiredEvo)
        {
            bool evolved = false;

            if (string.IsNullOrEmpty(desiredEvo))
            {
                // Find all descendatants of this species.

                using (SQLiteCommand cmd = new SQLiteCommand("SELECT species_id FROM Ancestors WHERE ancestor_id=$ancestor_id;")) {
                    List <long> descendant_ids = new List <long>();

                    cmd.Parameters.AddWithValue("$ancestor_id", gotchi.SpeciesId);

                    foreach (DataRow row in await database.GetRowsAsync(cmd))
                    {
                        descendant_ids.Add(row.Field <long>("species_id"));
                    }

                    // Pick an ID at random.

                    if (descendant_ids.Count > 0)
                    {
                        gotchi.SpeciesId = descendant_ids[NumberUtilities.GetRandomInteger(descendant_ids.Count)];

                        evolved = true;
                    }
                }
            }
            else
            {
                // Get the desired evo.
                IEnumerable <ISpecies> sp = await database.GetSpeciesAsync(desiredEvo);

                if (sp is null || sp.Count() != 1)
                {
                    return(false);
                }

                // Ensure that the species evolves into the desired evo.

                using (SQLiteCommand cmd = new SQLiteCommand("SELECT COUNT(*) FROM Ancestors WHERE ancestor_id = $ancestor_id AND species_id = $species_id")) {
                    cmd.Parameters.AddWithValue("$ancestor_id", gotchi.SpeciesId);
                    cmd.Parameters.AddWithValue("$species_id", sp.First().Id);

                    if (await database.GetScalarAsync <long>(cmd) <= 0)
                    {
                        return(false);
                    }

                    gotchi.SpeciesId = (long)sp.First().Id;

                    evolved = true;
                }
            }

            // Update the gotchi in the database.

            if (evolved)
            {
                using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET species_id=$species_id, evolved_ts=$evolved_ts WHERE id=$id;")) {
                    cmd.Parameters.AddWithValue("$species_id", gotchi.SpeciesId);

                    // The "last evolved" timestamp is now only updated in the event the gotchi evolves (in order to make the "IsEvolved" check work correctly).
                    // Note that this means that the background service will attempt to evolve the gotchi at every iteration (unless it evolves by leveling).

                    cmd.Parameters.AddWithValue("$evolved_ts", DateTimeOffset.UtcNow.ToUnixTimeSeconds());

                    cmd.Parameters.AddWithValue("$id", gotchi.Id);

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }

            return(evolved);
        }
Exemple #27
0
 private async Task _executeNonQueryAsync(string command)
 {
     using (SQLiteCommand cmd = new SQLiteCommand(command))
         await database.ExecuteNonQueryAsync(cmd);
 }
        private async Task _endBattle(ICommandContext context)
        {
            PlayerState winner = player1.Gotchi.Stats.Hp <= 0.0 ? player2 : player1;
            PlayerState loser  = player1.Gotchi.Stats.Hp <= 0.0 ? player1 : player2;

            // Calculate the amount of EXP awarded to the winner.
            // The loser will get 50% of the winner's EXP.

            double exp = _getExpEarned(winner.Gotchi.Gotchi, loser.Gotchi.Gotchi, won: true);

            double exp1 = player2.Gotchi.Stats.Hp <= 0.0 ? exp : exp * .5;
            double exp2 = player1.Gotchi.Stats.Hp <= 0.0 ? exp : exp * .5;

            long levels1 = player1.Gotchi.Stats.AddExperience((int)exp1);
            long levels2 = player2.Gotchi.Stats.AddExperience((int)exp2);

            StringBuilder sb = new StringBuilder();

            sb.AppendLine(battleText);

            // Show the winner's accomplishments, then the loser's.

            if (!IsCpuGotchi(winner.Gotchi.Gotchi))
            {
                double winner_exp    = winner.Gotchi.Gotchi.Id == player1.Gotchi.Gotchi.Id ? exp1 : exp2;
                long   winner_levels = winner.Gotchi.Gotchi.Id == player1.Gotchi.Gotchi.Id ? levels1 : levels2;
                long   winner_g      = (long)Math.Round(loser.Gotchi.Stats.Level * (NumberUtilities.GetRandomInteger(150, 200) / 100.0));

                sb.AppendLine(string.Format("🏆 **{0}** won the battle! Earned **{1} EXP** and **{2}G**.",
                                            winner.Gotchi.Gotchi.Name,
                                            winner_exp,
                                            winner_g));

                if (winner_levels > 0)
                {
                    sb.AppendLine(string.Format("🆙 **{0}** leveled up to level **{1}**!", winner.Gotchi.Gotchi.Name, winner.Gotchi.Stats.Level));
                }

                if (((winner.Gotchi.Stats.Level - winner_levels) / 10) < (winner.Gotchi.Stats.Level / 10))
                {
                    if (await database.EvolveAndUpdateGotchiAsync(winner.Gotchi.Gotchi))
                    {
                        ISpecies sp = await database.GetSpeciesAsync(winner.Gotchi.Gotchi.SpeciesId);

                        sb.AppendLine(string.Format("🚩 Congratulations, **{0}** evolved into **{1}**!", winner.Gotchi.Gotchi.Name, sp.GetShortName()));
                    }
                }

                // Update the winner's G.

                GotchiUserInfo user_data = await database.GetUserInfoAsync(winner.Gotchi.Gotchi.OwnerId);

                user_data.G += winner_g;

                await database.UpdateUserInfoAsync(user_data);

                sb.AppendLine();
            }

            if (!IsCpuGotchi(loser.Gotchi.Gotchi))
            {
                double loser_exp    = loser.Gotchi.Gotchi.Id == player1.Gotchi.Gotchi.Id ? exp1 : exp2;
                long   loser_levels = loser.Gotchi.Gotchi.Id == player1.Gotchi.Gotchi.Id ? levels1 : levels2;

                sb.AppendLine(string.Format("💀 **{0}** lost the battle... Earned **{1} EXP**.", loser.Gotchi.Gotchi.Name, loser_exp));

                if (loser_levels > 0)
                {
                    sb.AppendLine(string.Format("🆙 **{0}** leveled up to level **{1}**!", loser.Gotchi.Gotchi.Name, loser.Gotchi.Stats.Level));
                }

                if (((loser.Gotchi.Stats.Level - loser_levels) / 10) < (loser.Gotchi.Stats.Level / 10))
                {
                    if (await database.EvolveAndUpdateGotchiAsync(loser.Gotchi.Gotchi))
                    {
                        ISpecies sp = await database.GetSpeciesAsync(loser.Gotchi.Gotchi.SpeciesId);

                        sb.AppendLine(string.Format("🚩 Congratulations, **{0}** evolved into **{1}**!", loser.Gotchi.Gotchi.Name, sp.GetShortName()));
                    }
                }
            }

            // Update exp in the database.

            using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET level=$level, exp=$exp WHERE id=$id;")) {
                cmd.Parameters.AddWithValue("$id", player1.Gotchi.Gotchi.Id);
                cmd.Parameters.AddWithValue("$level", DBNull.Value);
                cmd.Parameters.AddWithValue("$exp", player1.Gotchi.Stats.Experience);

                await database.ExecuteNonQueryAsync(cmd);
            }

            if (!IsCpuGotchi(player2.Gotchi.Gotchi))
            {
                using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Gotchi SET level=$level, exp=$exp WHERE id=$id;")) {
                    cmd.Parameters.AddWithValue("$id", player2.Gotchi.Gotchi.Id);
                    cmd.Parameters.AddWithValue("$level", DBNull.Value);
                    cmd.Parameters.AddWithValue("$exp", player2.Gotchi.Stats.Experience);

                    await database.ExecuteNonQueryAsync(cmd);
                }
            }

            // Deregister the battle state.

            DeregisterBattle(context.User.Id);

            battleText = sb.ToString();
        }