feat: v2 — queue matchmaking, procedural audio, sprite archetypes, auth
- Add queue-based matchmaking with Elo-proximity and 10s timeout - Procedural sound engine (SFX, voice announcer, 4-track music) - Sprite system refactored into 6 archetypes (standard, lobster, sheep, cyborg, blob, tank) - 42+ fight choreographies with themed/generic/wild card selection - 4 KO finish styles, super-speed mode, hyperdetail close-ups - Auth routes, JoinBout page, bot profile with stats - 7-tier ranking system (Baby through Legend) - Arena and challenge system expansions Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
335c148866
commit
47d20fbe66
@@ -0,0 +1,136 @@
|
||||
import { Hono } from 'hono'
|
||||
import { nanoid } from 'nanoid'
|
||||
import { createHash, randomBytes } from 'crypto'
|
||||
import { db, schema } from '../db/index.js'
|
||||
import { eq } from 'drizzle-orm'
|
||||
|
||||
export const authRouter = new Hono()
|
||||
|
||||
// Login with Nostr pubkey — returns bot if one exists
|
||||
authRouter.post('/login', async (c) => {
|
||||
const body = await c.req.json()
|
||||
const { pubkey } = body
|
||||
|
||||
if (!pubkey || typeof pubkey !== 'string' || pubkey.length !== 64) {
|
||||
return c.json({ error: 'Invalid pubkey.' }, 400)
|
||||
}
|
||||
|
||||
const rows = await db.select({
|
||||
id: schema.bots.id,
|
||||
name: schema.bots.name,
|
||||
avatarSeed: schema.bots.avatarSeed,
|
||||
archetype: schema.bots.archetype,
|
||||
profilePicUrl: schema.bots.profilePicUrl,
|
||||
eloRating: schema.bots.eloRating,
|
||||
wins: schema.bots.wins,
|
||||
losses: schema.bots.losses,
|
||||
winStreak: schema.bots.winStreak,
|
||||
bestStreak: schema.bots.bestStreak,
|
||||
tier: schema.bots.tier,
|
||||
}).from(schema.bots).where(eq(schema.bots.publicKey, pubkey)).limit(1)
|
||||
|
||||
if (rows.length === 0) {
|
||||
return c.json({ exists: false, pubkey })
|
||||
}
|
||||
|
||||
return c.json({ exists: true, bot: rows[0] })
|
||||
})
|
||||
|
||||
// Register a new bot with Nostr pubkey
|
||||
authRouter.post('/register', async (c) => {
|
||||
const body = await c.req.json()
|
||||
const { pubkey, name, webhookUrl, archetype, profilePicUrl } = body
|
||||
|
||||
if (!pubkey || typeof pubkey !== 'string' || pubkey.length !== 64) {
|
||||
return c.json({ error: 'Invalid pubkey.' }, 400)
|
||||
}
|
||||
|
||||
if (!name || typeof name !== 'string' || name.length < 2 || name.length > 32) {
|
||||
return c.json({ error: 'Name must be 2-32 characters.' }, 400)
|
||||
}
|
||||
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
|
||||
return c.json({ error: 'Name must be alphanumeric, hyphens, or underscores.' }, 400)
|
||||
}
|
||||
|
||||
if (!webhookUrl || typeof webhookUrl !== 'string') {
|
||||
return c.json({ error: 'webhookUrl is required.' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
new URL(webhookUrl)
|
||||
} catch {
|
||||
return c.json({ error: 'webhookUrl must be a valid URL.' }, 400)
|
||||
}
|
||||
|
||||
// Check pubkey not already used
|
||||
const existingPk = await db.select({ id: schema.bots.id })
|
||||
.from(schema.bots)
|
||||
.where(eq(schema.bots.publicKey, pubkey))
|
||||
.limit(1)
|
||||
|
||||
if (existingPk.length > 0) {
|
||||
return c.json({ error: 'This Nostr key already has a bot.' }, 409)
|
||||
}
|
||||
|
||||
// Check name not taken
|
||||
const existingName = await db.select({ id: schema.bots.id })
|
||||
.from(schema.bots)
|
||||
.where(eq(schema.bots.name, name))
|
||||
.limit(1)
|
||||
|
||||
if (existingName.length > 0) {
|
||||
return c.json({ error: 'A bot with that name already exists.' }, 409)
|
||||
}
|
||||
|
||||
const id = nanoid(12)
|
||||
const secret = randomBytes(32).toString('hex')
|
||||
|
||||
await db.insert(schema.bots).values({
|
||||
id,
|
||||
name,
|
||||
webhookUrl: webhookUrl,
|
||||
avatarSeed: name,
|
||||
archetype: archetype || 'standard',
|
||||
secretHash: createHash('sha256').update(secret).digest('hex'),
|
||||
publicKey: pubkey,
|
||||
profilePicUrl: profilePicUrl || null,
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
return c.json({
|
||||
id,
|
||||
name,
|
||||
archetype: archetype || 'standard',
|
||||
message: 'Bot registered.',
|
||||
}, 201)
|
||||
})
|
||||
|
||||
// Update bot webhook (requires pubkey match)
|
||||
authRouter.post('/update', async (c) => {
|
||||
const body = await c.req.json()
|
||||
const { pubkey, webhookUrl, profilePicUrl } = body
|
||||
|
||||
if (!pubkey || typeof pubkey !== 'string') {
|
||||
return c.json({ error: 'Invalid pubkey.' }, 400)
|
||||
}
|
||||
|
||||
const rows = await db.select({ id: schema.bots.id })
|
||||
.from(schema.bots)
|
||||
.where(eq(schema.bots.publicKey, pubkey))
|
||||
.limit(1)
|
||||
|
||||
if (rows.length === 0) {
|
||||
return c.json({ error: 'No bot found for this key.' }, 404)
|
||||
}
|
||||
|
||||
const updates: Record<string, string> = {}
|
||||
if (webhookUrl) updates.webhookUrl = webhookUrl
|
||||
if (profilePicUrl) updates.profilePicUrl = profilePicUrl
|
||||
|
||||
if (Object.keys(updates).length > 0) {
|
||||
await db.update(schema.bots).set(updates).where(eq(schema.bots.id, rows[0].id))
|
||||
}
|
||||
|
||||
return c.json({ updated: true })
|
||||
})
|
||||
@@ -2,7 +2,8 @@ import { Hono } from 'hono'
|
||||
import { nanoid } from 'nanoid'
|
||||
import { createHash, randomBytes } from 'crypto'
|
||||
import { db, schema } from '../db/index.js'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { eq, or, desc } from 'drizzle-orm'
|
||||
import { TIER_NAMES, TIER_COLORS } from '../engine/scoring.js'
|
||||
|
||||
export const botsRouter = new Hono()
|
||||
|
||||
@@ -106,6 +107,89 @@ botsRouter.get('/:name', async (c) => {
|
||||
return c.json(rows[0])
|
||||
})
|
||||
|
||||
// Get bot stats — full account page data
|
||||
botsRouter.get('/:name/stats', async (c) => {
|
||||
const name = c.req.param('name')
|
||||
const botRows = await db.select({
|
||||
id: schema.bots.id,
|
||||
name: schema.bots.name,
|
||||
avatarSeed: schema.bots.avatarSeed,
|
||||
profilePicUrl: schema.bots.profilePicUrl,
|
||||
eloRating: schema.bots.eloRating,
|
||||
wins: schema.bots.wins,
|
||||
losses: schema.bots.losses,
|
||||
winStreak: schema.bots.winStreak,
|
||||
bestStreak: schema.bots.bestStreak,
|
||||
tier: schema.bots.tier,
|
||||
isActive: schema.bots.isActive,
|
||||
createdAt: schema.bots.createdAt,
|
||||
}).from(schema.bots).where(eq(schema.bots.name, name)).limit(1)
|
||||
|
||||
if (botRows.length === 0) {
|
||||
return c.json({ error: 'Bot not found.' }, 404)
|
||||
}
|
||||
|
||||
const bot = botRows[0]
|
||||
const total = bot.wins + bot.losses
|
||||
const winRate = total > 0 ? Math.round((bot.wins / total) * 100) : 0
|
||||
|
||||
// Get rank position
|
||||
const allBots = await db.select({
|
||||
id: schema.bots.id,
|
||||
eloRating: schema.bots.eloRating,
|
||||
}).from(schema.bots)
|
||||
allBots.sort((a, b) => b.eloRating - a.eloRating)
|
||||
const rank = allBots.findIndex(b => b.id === bot.id) + 1
|
||||
|
||||
// Recent fights (last 10)
|
||||
const fights = await db.select()
|
||||
.from(schema.fights)
|
||||
.where(or(
|
||||
eq(schema.fights.botAId, bot.id),
|
||||
eq(schema.fights.botBId, bot.id),
|
||||
))
|
||||
.orderBy(desc(schema.fights.createdAt))
|
||||
.limit(10)
|
||||
|
||||
// Resolve opponent names
|
||||
const opponentIds = new Set<string>()
|
||||
for (const f of fights) {
|
||||
const oppId = f.botAId === bot.id ? f.botBId : f.botAId
|
||||
opponentIds.add(oppId)
|
||||
}
|
||||
const opponentMap = new Map<string, string>()
|
||||
for (const id of opponentIds) {
|
||||
const opp = await db.select({ name: schema.bots.name })
|
||||
.from(schema.bots).where(eq(schema.bots.id, id)).limit(1)
|
||||
if (opp[0]) opponentMap.set(id, opp[0].name)
|
||||
}
|
||||
|
||||
const recentFights = fights.map(f => {
|
||||
const oppId = f.botAId === bot.id ? f.botBId : f.botAId
|
||||
const won = f.winnerId === bot.id
|
||||
const draw = !f.winnerId
|
||||
return {
|
||||
id: f.id,
|
||||
opponent: opponentMap.get(oppId) || '???',
|
||||
result: draw ? 'DRAW' : won ? 'W' : 'L',
|
||||
rounds: f.totalRounds,
|
||||
arena: f.arena,
|
||||
date: f.endedAt || f.createdAt,
|
||||
}
|
||||
})
|
||||
|
||||
return c.json({
|
||||
...bot,
|
||||
tierName: TIER_NAMES[bot.tier] || 'BABY',
|
||||
tierColor: TIER_COLORS[bot.tier] || '#888',
|
||||
winRate,
|
||||
totalFights: total,
|
||||
rank,
|
||||
totalBots: allBots.length,
|
||||
recentFights,
|
||||
})
|
||||
})
|
||||
|
||||
// Health check a bot's webhook
|
||||
botsRouter.post('/:name/health', async (c) => {
|
||||
const name = c.req.param('name')
|
||||
|
||||
+196
-18
@@ -1,8 +1,11 @@
|
||||
import { Hono } from 'hono'
|
||||
import { streamSSE } from 'hono/streaming'
|
||||
import { db, schema } from '../db/index.js'
|
||||
import { eq, desc } from 'drizzle-orm'
|
||||
import { ARENAS } from '../engine/arenas.js'
|
||||
import { runMockFight } from '../engine/mock.js'
|
||||
import { runFight, runFightAsync } from '../engine/orchestrator.js'
|
||||
import { fightEvents } from '../engine/events.js'
|
||||
|
||||
export const fightsRouter = new Hono()
|
||||
|
||||
@@ -61,25 +64,21 @@ fightsRouter.get('/:id', async (c) => {
|
||||
|
||||
const fight = fightRows[0]
|
||||
|
||||
const botFields = {
|
||||
id: schema.bots.id,
|
||||
name: schema.bots.name,
|
||||
avatarSeed: schema.bots.avatarSeed,
|
||||
archetype: schema.bots.archetype,
|
||||
profilePicUrl: schema.bots.profilePicUrl,
|
||||
eloRating: schema.bots.eloRating,
|
||||
wins: schema.bots.wins,
|
||||
losses: schema.bots.losses,
|
||||
tier: schema.bots.tier,
|
||||
}
|
||||
|
||||
const [botARows, botBRows] = await Promise.all([
|
||||
db.select({
|
||||
id: schema.bots.id,
|
||||
name: schema.bots.name,
|
||||
avatarSeed: schema.bots.avatarSeed,
|
||||
eloRating: schema.bots.eloRating,
|
||||
wins: schema.bots.wins,
|
||||
losses: schema.bots.losses,
|
||||
tier: schema.bots.tier,
|
||||
}).from(schema.bots).where(eq(schema.bots.id, fight.botAId)).limit(1),
|
||||
db.select({
|
||||
id: schema.bots.id,
|
||||
name: schema.bots.name,
|
||||
avatarSeed: schema.bots.avatarSeed,
|
||||
eloRating: schema.bots.eloRating,
|
||||
wins: schema.bots.wins,
|
||||
losses: schema.bots.losses,
|
||||
tier: schema.bots.tier,
|
||||
}).from(schema.bots).where(eq(schema.bots.id, fight.botBId)).limit(1),
|
||||
db.select(botFields).from(schema.bots).where(eq(schema.bots.id, fight.botAId)).limit(1),
|
||||
db.select(botFields).from(schema.bots).where(eq(schema.bots.id, fight.botBId)).limit(1),
|
||||
])
|
||||
|
||||
const roundRows = await db.select()
|
||||
@@ -111,3 +110,182 @@ fightsRouter.post('/mock', async (c) => {
|
||||
|
||||
return c.json({ fightId, message: 'Mock fight completed.' })
|
||||
})
|
||||
|
||||
// Trigger a mock fight for a specific bot against a random opponent
|
||||
fightsRouter.post('/mock/:botId', async (c) => {
|
||||
const botId = c.req.param('botId')
|
||||
|
||||
const botRows = await db.select({ id: schema.bots.id })
|
||||
.from(schema.bots)
|
||||
.where(eq(schema.bots.id, botId))
|
||||
.limit(1)
|
||||
|
||||
if (botRows.length === 0) {
|
||||
return c.json({ error: 'Bot not found.' }, 404)
|
||||
}
|
||||
|
||||
const opponents = await db.select({ id: schema.bots.id })
|
||||
.from(schema.bots)
|
||||
|
||||
const others = opponents.filter(b => b.id !== botId)
|
||||
if (others.length === 0) {
|
||||
return c.json({ error: 'No opponents available.' }, 400)
|
||||
}
|
||||
|
||||
const opponent = others[Math.floor(Math.random() * others.length)]
|
||||
const fightId = await runMockFight(botId, opponent.id)
|
||||
|
||||
return c.json({ fightId, message: 'Mock fight completed.' })
|
||||
})
|
||||
|
||||
// Start a REAL fight — calls actual webhooks
|
||||
// If botId is provided, fights that bot vs a random opponent
|
||||
// If no real opponents exist, falls back to a mock opponent
|
||||
fightsRouter.post('/fight/:botId', async (c) => {
|
||||
const botId = c.req.param('botId')
|
||||
|
||||
const botRows = await db.select({ id: schema.bots.id, webhookUrl: schema.bots.webhookUrl })
|
||||
.from(schema.bots)
|
||||
.where(eq(schema.bots.id, botId))
|
||||
.limit(1)
|
||||
|
||||
if (botRows.length === 0) {
|
||||
return c.json({ error: 'Bot not found.' }, 404)
|
||||
}
|
||||
|
||||
// Find a real opponent (any other bot with a non-mock webhook)
|
||||
const allBots = await db.select({ id: schema.bots.id, webhookUrl: schema.bots.webhookUrl })
|
||||
.from(schema.bots)
|
||||
|
||||
const realOpponents = allBots.filter(b => b.id !== botId && !b.webhookUrl.startsWith('http://mock.local'))
|
||||
const mockOpponents = allBots.filter(b => b.id !== botId && b.webhookUrl.startsWith('http://mock.local'))
|
||||
|
||||
let opponentId: string
|
||||
let useMock = false
|
||||
|
||||
if (realOpponents.length > 0) {
|
||||
// Prefer real opponents
|
||||
opponentId = realOpponents[Math.floor(Math.random() * realOpponents.length)].id
|
||||
} else if (mockOpponents.length > 0) {
|
||||
// Fall back to mock opponent — but still use real fight engine for the registered bot
|
||||
opponentId = mockOpponents[Math.floor(Math.random() * mockOpponents.length)].id
|
||||
useMock = true
|
||||
} else {
|
||||
return c.json({ error: 'No opponents available.' }, 400)
|
||||
}
|
||||
|
||||
// For fights involving a mock bot, use runMockFight (since mock webhooks don't exist)
|
||||
// For two real bots, use runFight (calls actual webhooks)
|
||||
if (useMock) {
|
||||
// The registered bot gives real answers, mock bot gives fake ones
|
||||
// We need a hybrid — for now, use mock fight so it works immediately
|
||||
const fightId = await runMockFight(botId, opponentId)
|
||||
return c.json({ fightId, message: 'Fight completed (opponent was a mock bot).' })
|
||||
}
|
||||
|
||||
// Both bots are real — run a real fight with webhook calls
|
||||
// Run in background so we can return the fightId immediately
|
||||
const { nanoid } = await import('nanoid')
|
||||
const fightId = nanoid(12)
|
||||
|
||||
// Don't await — let it run while the user watches
|
||||
runFight(botId, opponentId).then(id => {
|
||||
console.log(`[botfights] real fight ${id} completed`)
|
||||
}).catch(err => {
|
||||
console.error(`[botfights] fight error:`, err)
|
||||
})
|
||||
|
||||
// Return the fight ID immediately so the frontend can navigate to it
|
||||
// The fight will be created by runFight momentarily
|
||||
return c.json({ fightId: 'pending', botId, opponentId, message: 'Real fight starting...' })
|
||||
})
|
||||
|
||||
// SSE stream for live fight events
|
||||
fightsRouter.get('/:id/stream', (c) => {
|
||||
const fightId = c.req.param('id')
|
||||
|
||||
return streamSSE(c, async (stream) => {
|
||||
const cleanup = fightEvents.on(fightId, (event) => {
|
||||
stream.writeSSE({
|
||||
event: event.type,
|
||||
data: JSON.stringify(event.data),
|
||||
})
|
||||
})
|
||||
|
||||
// Also listen for global events to catch fight_end
|
||||
const cleanupGlobal = fightEvents.onAll((event) => {
|
||||
if (event.fightId === fightId && event.type === 'fight_end') {
|
||||
stream.writeSSE({
|
||||
event: 'fight_end',
|
||||
data: JSON.stringify(event.data),
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// Keep alive until fight ends or client disconnects
|
||||
try {
|
||||
while (true) {
|
||||
await stream.writeSSE({ event: 'ping', data: '' })
|
||||
await stream.sleep(5000)
|
||||
// Check if fight is done
|
||||
const fight = await db.select({ status: schema.fights.status })
|
||||
.from(schema.fights)
|
||||
.where(eq(schema.fights.id, fightId))
|
||||
.limit(1)
|
||||
if (fight.length > 0 && fight[0].status === 'finished') break
|
||||
}
|
||||
} catch {
|
||||
// Client disconnected
|
||||
} finally {
|
||||
cleanup()
|
||||
cleanupGlobal()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// Instant matchmaking — find an opponent and start a fight NOW
|
||||
fightsRouter.post('/matchmake/:botId', async (c) => {
|
||||
const botId = c.req.param('botId')
|
||||
|
||||
const botRows = await db.select()
|
||||
.from(schema.bots)
|
||||
.where(eq(schema.bots.id, botId))
|
||||
.limit(1)
|
||||
|
||||
if (botRows.length === 0) {
|
||||
return c.json({ error: 'Bot not found.' }, 404)
|
||||
}
|
||||
|
||||
const bot = botRows[0]
|
||||
|
||||
// Find all other active bots, prefer close elo
|
||||
const allBots = await db.select()
|
||||
.from(schema.bots)
|
||||
|
||||
const opponents = allBots.filter(b => b.id !== botId)
|
||||
if (opponents.length === 0) {
|
||||
return c.json({ error: 'No opponents available.' }, 400)
|
||||
}
|
||||
|
||||
// Sort by closest elo for fair matchmaking, with some randomness
|
||||
opponents.sort((a, b) => {
|
||||
const diffA = Math.abs(a.eloRating - bot.eloRating) + Math.random() * 200
|
||||
const diffB = Math.abs(b.eloRating - bot.eloRating) + Math.random() * 200
|
||||
return diffA - diffB
|
||||
})
|
||||
|
||||
const opponent = opponents[0]
|
||||
const isRealOpponent = !opponent.webhookUrl.startsWith('http://mock.local')
|
||||
const isMockBot = bot.webhookUrl.startsWith('http://mock.local')
|
||||
|
||||
let fightId: string
|
||||
|
||||
// Start fight async — returns immediately so frontend can watch live
|
||||
fightId = await runFightAsync(botId, opponent.id)
|
||||
|
||||
return c.json({
|
||||
fightId,
|
||||
opponent: { id: opponent.id, name: opponent.name },
|
||||
message: 'Fight started.',
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Hono } from 'hono'
|
||||
import { db, schema } from '../db/index.js'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { joinQueue, leaveQueue, getQueueSize, getQueueSnapshot } from '../engine/queue.js'
|
||||
|
||||
export const queueRouter = new Hono()
|
||||
|
||||
// Get queue status
|
||||
queueRouter.get('/status', (c) => {
|
||||
return c.json({
|
||||
waiting: getQueueSize(),
|
||||
queue: getQueueSnapshot(),
|
||||
})
|
||||
})
|
||||
|
||||
// Join the queue — blocks until matched, then returns fightId
|
||||
queueRouter.post('/join/:botId', async (c) => {
|
||||
const botId = c.req.param('botId')
|
||||
|
||||
const botRows = await db.select({ id: schema.bots.id, name: schema.bots.name })
|
||||
.from(schema.bots)
|
||||
.where(eq(schema.bots.id, botId))
|
||||
.limit(1)
|
||||
|
||||
if (botRows.length === 0) {
|
||||
return c.json({ error: 'Bot not found.' }, 404)
|
||||
}
|
||||
|
||||
try {
|
||||
const fightId = await joinQueue(botId)
|
||||
return c.json({ fightId, message: 'Matched! Fight starting.' })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Queue error'
|
||||
return c.json({ error: message }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
// Leave the queue
|
||||
queueRouter.post('/leave/:botId', (c) => {
|
||||
const botId = c.req.param('botId')
|
||||
const left = leaveQueue(botId)
|
||||
return c.json({ left })
|
||||
})
|
||||
Reference in New Issue
Block a user