Browse Source

- Added in some data augmentation

pull/1/head
Dan 1 year ago
parent
commit
5dff7bfb04
  1. 221
      src/server.ts

221
src/server.ts

@ -4,8 +4,8 @@ dotenv.config();
import express from 'express'; import express from 'express';
import { Request, Response, NextFunction } from 'express'; import { Request, Response, NextFunction } from 'express';
import cors from 'cors'; import cors from 'cors';
import { open, Database } from 'sqlite';
import sqlite3 from 'sqlite3'; import sqlite3 from 'sqlite3';
import { open } from 'sqlite';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt'; import bcrypt from 'bcrypt';
import fs from 'fs/promises'; import fs from 'fs/promises';
@ -313,123 +313,156 @@ interface PokemonFamilyEntry {
Any?: number; Any?: number;
Male?: number; Male?: number;
Female?: number; Female?: number;
evolve_to_augmented?: PokemonEntry[]
breed_for_augmented?: PokemonEntry[]
} }
interface PokemonEntry {
pfic: string
name: string
}
const getDbConnection = async (): Promise<Database<sqlite3.Database, sqlite3.Statement>> => {
return open({
filename: './pokemon_forms.db', // Adjust path to your database file
driver: sqlite3.Database
});
};
app.get('/api/plan', authenticateToken, async (req: AuthRequest, res: Response) => { app.get('/api/plan', authenticateToken, async (req: AuthRequest, res: Response) => {
let db: Database<sqlite3.Database, sqlite3.Statement> | null = null;
try { try {
// Get the Pokemon database connection
db = await getDbConnection();
// Read the efficiency plan file // Read the efficiency plan file
const planData = await fs.readFile( const planData = await fs.readFile(
path.join(__dirname, '../plan.json'), path.join(__dirname, '../plan.json'),
'utf-8' 'utf-8'
); );
const efficiencyPlan: GamePlan[] = JSON.parse(planData); const efficiencyPlan: GamePlan[] = JSON.parse(planData);
efficiencyPlan.forEach((game_plan) => {
for (const key in game_plan["pokemon"]) {
game_plan["pokemon"][key]["family_pfic"] = key;
}
});
// Get the Pokemon database connection // Loop through each game plan
const db = await open({ for (let i = 0; i < efficiencyPlan.length; i++) {
filename: '../pokemon_forms.db', const game_plan = efficiencyPlan[i];
driver: sqlite3.Database for (const key in game_plan.pokemon) {
}); if (Object.hasOwnProperty.call(game_plan.pokemon, key)) {
const pokemonFamily: PokemonFamilyEntry = game_plan.pokemon[key];
// Get user's caught Pokemon pokemonFamily.family_pfic = key;
const userDb = await userDbPromise;
const caughtPokemon = await userDb.all( // Merge evolve_to into pfics array
'SELECT pfic FROM caught_pokemon WHERE user_id = ?', const pfics: string[] = pokemonFamily.evolve_to.concat(pokemonFamily.evolve_to);
[req.user.id]
); // Loop through pfics to get details from the database
const caughtPfics = new Set(caughtPokemon.map(p => p.pfic)); for (let j = 0; j < pfics.length; j++) {
const pkmn: string = pfics[j];
// Helper function to get evolution methods
async function getEvolutionMethods(fromPfic: string, toPfic: string) { try {
// Try direct evolution first const details = await db.get<{ PFIC: string; data: string }>(
const direct = await db.get(` `SELECT * FROM pokemon_forms WHERE PFIC = ?`,
SELECT method, to_pfic pkmn
FROM evolution_chains );
WHERE from_pfic = ? AND to_pfic = ?
`, [fromPfic, toPfic]); if (!details) {
console.log("Details not found for PFIC:", pkmn);
if (direct) { continue;
return [direct.method]; }
}
// Try indirect evolution path const data = JSON.parse(details.data);
const methods = await db.all(` const pokemon = {
WITH RECURSIVE evolution_path AS ( pfic: details.PFIC,
SELECT from_pfic, to_pfic, method, 1 as depth data: data,
FROM evolution_chains };
WHERE from_pfic = ?
if (!pokemonFamily.evolve_to_augmented) {
UNION ALL pokemonFamily.evolve_to_augmented = [];
}
SELECT e.from_pfic, e.to_pfic, e.method, ep.depth + 1
FROM evolution_chains e const entry = {
JOIN evolution_path ep ON e.from_pfic = ep.to_pfic pfic: key,
WHERE ep.depth < 3 name: pokemon.data.name,
) };
SELECT method
FROM evolution_path pokemonFamily.evolve_to_augmented.push(entry);
WHERE to_pfic = ?
ORDER BY depth; } catch (err) {
`, [fromPfic, toPfic]); console.error(`Error fetching details for PFIC ${pkmn}:`, err);
}
if (methods && methods.length > 0) { }
return methods.map(m => m.method); }
} }
}
res.json(efficiencyPlan);
return ['Evolution']; } catch (err) {
console.error('Error loading efficiency plan:', err);
res.status(500).json({ error: 'Internal server error' });
} finally {
if (db) {
await db.close();
} }
}
});
/*
app.get('/api/plan', authenticateToken, async (req: AuthRequest, res: Response) => {
try {
// Get the Pokemon database connection
const db = await dbPromise;
const debug_pfic = "0010-01-000-0"; // Read the efficiency plan file
// Enhance the plan with evolution methods and account for caught Pokemon const planData = await fs.readFile(
/* path.join(__dirname, '../plan.json'),
for (const game of efficiencyPlan) { 'utf-8'
for (const pokemon of game.pokemon.keys()) { );
// Set initial catch count const efficiencyPlan: GamePlan[] = JSON.parse(planData);
pokemon.catch_count = 1; for (let game_plan of efficiencyPlan){
if (pokemon.pfic === debug_pfic) { for (const key in game_plan["pokemon"]) {
console.log(`pokemon: ${pokemon.name} - ${pokemon.catch_count}`); //console.log(key)
game_plan["pokemon"][key]["family_pfic"] = key;
let pfics = []
//console.log(game_plan["pokemon"][key])
for (let pkmn of game_plan["pokemon"][key]["evolve_to"]) {
pfics.push(pkmn)
}
for (let pkmn of game_plan["pokemon"][key]["evolve_to"]) {
pfics.push(pkmn)
} }
for (let pkmn of pfics) {
// Add evolution targets to catch count console.log(pkmn)
if (pokemon.evolve_to) { const details = await db.get(`
pokemon.catch_count += pokemon.evolve_to.length; SELECT *
if (pokemon.pfic === debug_pfic) { FROM pokemon_forms
console.log(`pokemon: ${pokemon.name} - ${pokemon.catch_count}`); WHERE PFIC = ?
`, pkmn);
if(!details) {
console.log("oh noes")
continue;
} }
// Add evolution methods const data = JSON.parse(details.data)
for (const evolution of pokemon.evolve_to) { const pokemon = {
const methods = await getEvolutionMethods(pokemon.pfic, evolution.pfic); "pfic": details.PFIC,
evolution.method = methods.join(' → '); "data": data
} }
}
// Reduce catch count for already caught Pokemon if (!game_plan["pokemon"][key].evolve_to_augmented) {
if (caughtPfics.has(pokemon.pfic)) { game_plan["pokemon"][key].evolve_to_augmented = []
pokemon.catch_count = Math.max(0, pokemon.catch_count - 1);
if (pokemon.pfic === debug_pfic) {
console.log(`B pokemon: ${pokemon.name} - ${pokemon.catch_count}`);
} }
} let entry = {
pfic: key,
// Check evolution targets name: pokemon.data.name
if (pokemon.evolve_to) {
for (const evolution of pokemon.evolve_to) {
if (caughtPfics.has(evolution.pfic)) {
pokemon.catch_count = Math.max(0, pokemon.catch_count - 1);
if (pokemon.pfic === debug_pfic) {
console.log(`C pokemon: ${pokemon.name} - ${pokemon.catch_count} (${evolution.pfic})`);
}
}
} }
game_plan["pokemon"][key].evolve_to_augmented.push(entry)
} }
} }
} }
*/
await db.close(); await db.close();
res.json(efficiencyPlan); res.json(efficiencyPlan);
@ -439,7 +472,7 @@ app.get('/api/plan', authenticateToken, async (req: AuthRequest, res: Response)
res.status(500).json({ error: 'Internal server error' }); res.status(500).json({ error: 'Internal server error' });
} }
}); });
*/
// Update the caught Pokemon routes // Update the caught Pokemon routes
app.get('/api/pokemon/caught', authenticateToken, (req: AuthRequest, res: Response) => { app.get('/api/pokemon/caught', authenticateToken, (req: AuthRequest, res: Response) => {
void userDbPromise.then(async (db) => { void userDbPromise.then(async (db) => {

Loading…
Cancel
Save