diff --git a/.agents/agent_assets_metadata.toml b/.agents/agent_assets_metadata.toml new file mode 100644 index 0000000000000000000000000000000000000000..e49ad868ddda8864dd43df62c3d1da7bc1a48ac6 --- /dev/null +++ b/.agents/agent_assets_metadata.toml @@ -0,0 +1,8 @@ +uploads = [] +generated = [] + +[[outputs]] +id = "w_y6GAxuQ-z03XgEUHxmH" +uri = "file://exports/ecoclean-3d.tar.gz" +type = "unspecified" +title = "EcoClean 3D — full source (with advanced features + owner panel)" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..12bc7fa7e05091e2d413d235ef695c1d95805c8a --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +# See https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files for more about ignoring files. + +# compiled output +dist +tmp +out-tsc +*.tsbuildinfo +.expo +.expo-shared + +# dependencies +node_modules + +# IDEs and editors +/.idea +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# IDE - VSCode +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +# misc +/.sass-cache +/connect.lock +/coverage +/libpeerconnection.log +npm-debug.log +yarn-error.log +testem.log +/typings + +# System Files +.DS_Store +Thumbs.db + +.cursor/rules/nx-rules.mdc +.github/instructions/nx.instructions.md + +# Replit +.cache/ +.local/ diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000000000000000000000000000000000000..61e34c2e5dde6b5b6b9d1a478945726c27993d4b --- /dev/null +++ b/.npmrc @@ -0,0 +1,2 @@ +auto-install-peers=false +strict-peer-dependencies=false diff --git a/.replit b/.replit new file mode 100644 index 0000000000000000000000000000000000000000..ce638e75ab09689474c0b9c62663e3471601db28 --- /dev/null +++ b/.replit @@ -0,0 +1,32 @@ +modules = ["nodejs-24"] + +[deployment] +router = "application" +deploymentTarget = "autoscale" + +[deployment.postBuild] +args = ["pnpm", "store", "prune"] +env = { "CI" = "true" } + +[workflows] +runButton = "Project" + +[agent] +stack = "PNPM_WORKSPACE" +expertMode = true + +[postMerge] +path = "scripts/post-merge.sh" +timeoutMs = 20000 + +[[ports]] +localPort = 8080 +externalPort = 8080 + +[[ports]] +localPort = 8081 +externalPort = 80 + +[[ports]] +localPort = 18257 +externalPort = 3000 diff --git a/.replitignore b/.replitignore new file mode 100644 index 0000000000000000000000000000000000000000..9eb019cd54e4f8ea1737967adb19aa1f53562cf2 --- /dev/null +++ b/.replitignore @@ -0,0 +1,5 @@ +# The format of this file is identical to `.dockerignore`. +# It is used to reduce the size of deployed images to make the process of publishing faster. + +# No need to store the pnpm store twice. +.local diff --git a/artifacts/api-server/.replit-artifact/artifact.toml b/artifacts/api-server/.replit-artifact/artifact.toml new file mode 100644 index 0000000000000000000000000000000000000000..814b9ad51b47b2302b7364ccb37849767aec680e --- /dev/null +++ b/artifacts/api-server/.replit-artifact/artifact.toml @@ -0,0 +1,32 @@ +kind = "api" +previewPath = "/api" # TODO - should be excluded from preview in the first place +title = "API Server" +version = "1.0.0" +id = "3B4_FFSkEVBkAeYMFRJ2e" + +[[services]] +localPort = 8080 +name = "API Server" +paths = ["/api"] + +[services.development] +run = "pnpm --filter @workspace/api-server run dev" + +[services.production] + +[services.production.build] +args = ["pnpm", "--filter", "@workspace/api-server", "run", "build"] + +[services.production.build.env] +NODE_ENV = "production" + +[services.production.run] +# we don't run through pnpm to make startup faster in production +args = ["node", "--enable-source-maps", "artifacts/api-server/dist/index.mjs"] + +[services.production.run.env] +PORT = "8080" +NODE_ENV = "production" + +[services.production.health.startup] +path = "/api/healthz" diff --git a/artifacts/api-server/build.mjs b/artifacts/api-server/build.mjs new file mode 100644 index 0000000000000000000000000000000000000000..86ebf7faaa9322b1ab55cdbbda7febaad27b35cd --- /dev/null +++ b/artifacts/api-server/build.mjs @@ -0,0 +1,126 @@ +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { build as esbuild } from "esbuild"; +import esbuildPluginPino from "esbuild-plugin-pino"; +import { rm } from "node:fs/promises"; + +// Plugins (e.g. 'esbuild-plugin-pino') may use `require` to resolve dependencies +globalThis.require = createRequire(import.meta.url); + +const artifactDir = path.dirname(fileURLToPath(import.meta.url)); + +async function buildAll() { + const distDir = path.resolve(artifactDir, "dist"); + await rm(distDir, { recursive: true, force: true }); + + await esbuild({ + entryPoints: [path.resolve(artifactDir, "src/index.ts")], + platform: "node", + bundle: true, + format: "esm", + outdir: distDir, + outExtension: { ".js": ".mjs" }, + logLevel: "info", + // Some packages may not be bundleable, so we externalize them, we can add more here as needed. + // Some of the packages below may not be imported or installed, but we're adding them in case they are in the future. + // Examples of unbundleable packages: + // - uses native modules and loads them dynamically (e.g. sharp) + // - use path traversal to read files (e.g. @google-cloud/secret-manager loads sibling .proto files) + external: [ + "*.node", + "sharp", + "better-sqlite3", + "sqlite3", + "canvas", + "bcrypt", + "argon2", + "fsevents", + "re2", + "farmhash", + "xxhash-addon", + "bufferutil", + "utf-8-validate", + "ssh2", + "cpu-features", + "dtrace-provider", + "isolated-vm", + "lightningcss", + "pg-native", + "oracledb", + "mongodb-client-encryption", + "nodemailer", + "handlebars", + "knex", + "typeorm", + "protobufjs", + "onnxruntime-node", + "@tensorflow/*", + "@prisma/client", + "@mikro-orm/*", + "@grpc/*", + "@swc/*", + "@aws-sdk/*", + "@azure/*", + "@opentelemetry/*", + "@google-cloud/*", + "@google/*", + "googleapis", + "firebase-admin", + "@parcel/watcher", + "@sentry/profiling-node", + "@tree-sitter/*", + "aws-sdk", + "classic-level", + "dd-trace", + "ffi-napi", + "grpc", + "hiredis", + "kerberos", + "leveldown", + "miniflare", + "mysql2", + "newrelic", + "odbc", + "piscina", + "realm", + "ref-napi", + "rocksdb", + "sass-embedded", + "sequelize", + "serialport", + "snappy", + "tinypool", + "usb", + "workerd", + "wrangler", + "zeromq", + "zeromq-prebuilt", + "playwright", + "puppeteer", + "puppeteer-core", + "electron", + ], + sourcemap: "linked", + plugins: [ + // pino relies on workers to handle logging, instead of externalizing it we use a plugin to handle it + esbuildPluginPino({ transports: ["pino-pretty"] }) + ], + // Make sure packages that are cjs only (e.g. express) but are bundled continue to work in our esm output file + banner: { + js: `import { createRequire as __bannerCrReq } from 'node:module'; +import __bannerPath from 'node:path'; +import __bannerUrl from 'node:url'; + +globalThis.require = __bannerCrReq(import.meta.url); +globalThis.__filename = __bannerUrl.fileURLToPath(import.meta.url); +globalThis.__dirname = __bannerPath.dirname(globalThis.__filename); + `, + }, + }); +} + +buildAll().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/artifacts/api-server/package.json b/artifacts/api-server/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0b3c68b77a979c50f1760650d49439785d24f2df --- /dev/null +++ b/artifacts/api-server/package.json @@ -0,0 +1,34 @@ +{ + "name": "@workspace/api-server", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "export NODE_ENV=development && pnpm run build && pnpm run start", + "build": "node ./build.mjs", + "start": "node --enable-source-maps ./dist/index.mjs", + "typecheck": "tsc -p tsconfig.json --noEmit" + }, + "dependencies": { + "@workspace/api-zod": "workspace:*", + "@workspace/db": "workspace:*", + "cookie-parser": "^1.4.7", + "cors": "^2", + "drizzle-orm": "catalog:", + "express": "^5", + "pino": "^9", + "pino-http": "^10", + "ws": "^8.20.0" + }, + "devDependencies": { + "@types/cookie-parser": "^1.4.10", + "@types/cors": "^2.8.19", + "@types/express": "^5.0.6", + "@types/node": "catalog:", + "@types/ws": "^8.18.1", + "esbuild": "^0.27.3", + "esbuild-plugin-pino": "^2.3.3", + "pino-pretty": "^13", + "thread-stream": "3.1.0" + } +} diff --git a/artifacts/api-server/src/app.ts b/artifacts/api-server/src/app.ts new file mode 100644 index 0000000000000000000000000000000000000000..f32f71eb2abef174efb08a2cc118c7e76c6df951 --- /dev/null +++ b/artifacts/api-server/src/app.ts @@ -0,0 +1,34 @@ +import express, { type Express } from "express"; +import cors from "cors"; +import pinoHttp from "pino-http"; +import router from "./routes"; +import { logger } from "./lib/logger"; + +const app: Express = express(); + +app.use( + pinoHttp({ + logger, + serializers: { + req(req) { + return { + id: req.id, + method: req.method, + url: req.url?.split("?")[0], + }; + }, + res(res) { + return { + statusCode: res.statusCode, + }; + }, + }, + }), +); +app.use(cors()); +app.use(express.json()); +app.use(express.urlencoded({ extended: true })); + +app.use("/api", router); + +export default app; diff --git a/artifacts/api-server/src/index.ts b/artifacts/api-server/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b59079de931ddf90cd069518793dcd70fc67402 --- /dev/null +++ b/artifacts/api-server/src/index.ts @@ -0,0 +1,30 @@ +import { createServer } from "http"; +import app from "./app"; +import { logger } from "./lib/logger"; +import { attachMultiplayer } from "./multiplayer/wsHandler.js"; + +const rawPort = process.env["PORT"]; + +if (!rawPort) { + throw new Error( + "PORT environment variable is required but was not provided.", + ); +} + +const port = Number(rawPort); + +if (Number.isNaN(port) || port <= 0) { + throw new Error(`Invalid PORT value: "${rawPort}"`); +} + +const server = createServer(app); +attachMultiplayer(server); + +server.listen(port, () => { + logger.info({ port }, "Server listening (HTTP + WebSocket)"); +}); + +server.on("error", (err) => { + logger.error({ err }, "Server error"); + process.exit(1); +}); diff --git a/artifacts/api-server/src/lib/.gitkeep b/artifacts/api-server/src/lib/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/artifacts/api-server/src/lib/logger.ts b/artifacts/api-server/src/lib/logger.ts new file mode 100644 index 0000000000000000000000000000000000000000..d9c67f79a82872af8336ab384014fa69bbe0695f --- /dev/null +++ b/artifacts/api-server/src/lib/logger.ts @@ -0,0 +1,20 @@ +import pino from "pino"; + +const isProduction = process.env.NODE_ENV === "production"; + +export const logger = pino({ + level: process.env.LOG_LEVEL ?? "info", + redact: [ + "req.headers.authorization", + "req.headers.cookie", + "res.headers['set-cookie']", + ], + ...(isProduction + ? {} + : { + transport: { + target: "pino-pretty", + options: { colorize: true }, + }, + }), +}); diff --git a/artifacts/api-server/src/middlewares/.gitkeep b/artifacts/api-server/src/middlewares/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/artifacts/api-server/src/multiplayer/rooms.ts b/artifacts/api-server/src/multiplayer/rooms.ts new file mode 100644 index 0000000000000000000000000000000000000000..ae055d5b35a46c3dfbef68df437946ea633ede6e --- /dev/null +++ b/artifacts/api-server/src/multiplayer/rooms.ts @@ -0,0 +1,541 @@ +/** + * Multiplayer game rooms for EcoClean 3D — v2 with game modes + new levels. + */ + +import type { WebSocket } from "ws"; +import { logger } from "../lib/logger.js"; + +export type Level = "park" | "beach" | "city" | "nightcity" | "arctic" | "jungle"; +export type TrashType = "plastic" | "metal" | "organic" | "paper"; +export type Difficulty = "easy" | "normal" | "hard"; +export type PowerUpKind = "magnet" | "speed" | "bonus"; +export type GameMode = "speedrun" | "percent100" | "powerup"; + +export const WORLD_HALF = 28; +export const COLLECT_RADIUS_SQ = 4.5; +export const POSITION_BROADCAST_HZ = 12; +export const END_HOLD_SEC = 8; +export const BASE_TRASH_POINTS = 10; +export const COMBO_WINDOW_MS = 4000; +export const COMBO_MAX = 5; +export const EMOTE_COOLDOWN_MS = 1500; +export const POWERUP_LIFETIME_SEC = 25; +export const POWERUP_EFFECT_SEC = 8; +export const POWERUP_BONUS_POINTS = 50; +export const POWERUP_PICKUP_RADIUS_SQ = 4; + +export const DIFFICULTY_CONFIG: Record< + Difficulty, + { roundDuration: number; trashCount: number; winThreshold: number; label: string } +> = { + easy: { roundDuration: 180, trashCount: 24, winThreshold: 0.6, label: "Easy" }, + normal: { roundDuration: 120, trashCount: 32, winThreshold: 0.8, label: "Normal" }, + hard: { roundDuration: 90, trashCount: 44, winThreshold: 0.9, label: "Hard" }, +}; + +/** Per-mode overrides applied on top of difficulty settings. */ +export const MODE_CONFIG: Record = { + speedrun: { + winThresholdOverride: null, // uses difficulty threshold + roundDurationScale: 0.7, // 70% of normal time = hectic + trashCountScale: 1.3, + powerUpSpawnIntervalSec: 22, + maxActivePowerUps: 3, + label: "Speedrun", + }, + percent100: { + winThresholdOverride: 1.0, // must collect EVERYTHING + roundDurationScale: 2.0, // generous time + trashCountScale: 0.8, + powerUpSpawnIntervalSec: 18, + maxActivePowerUps: 4, + label: "100% Clean", + }, + powerup: { + winThresholdOverride: null, + roundDurationScale: 1.0, + trashCountScale: 1.0, + powerUpSpawnIntervalSec: 6, // power-ups rain down + maxActivePowerUps: 8, + label: "Power-Up Party", + }, +}; + +export const VALID_LEVELS: Level[] = ["park", "beach", "city", "nightcity", "arctic", "jungle"]; +export const VALID_DIFFICULTIES: Difficulty[] = ["easy", "normal", "hard"]; +export const VALID_GAME_MODES: GameMode[] = ["speedrun", "percent100", "powerup"]; + +export const OWNER_PASSWORD = "Slayers"; + +/** Public room code from level + mode. */ +export function publicCode(level: Level, mode: GameMode): string { + const lv: Record = { + park: "PK", beach: "BC", city: "CT", nightcity: "NK", arctic: "AC", jungle: "JG", + }; + const md: Record = { speedrun: "SR", percent100: "PC", powerup: "PU" }; + return `${lv[level]}-${md[mode]}`; +} + +const RESERVED = new Set( + VALID_LEVELS.flatMap(l => VALID_GAME_MODES.map(m => publicCode(l, m))) +); + +function generateCode(): string { + const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + let s = ""; + for (let i = 0; i < 4; i++) s += alphabet[Math.floor(Math.random() * alphabet.length)]; + return s; +} + +export type EmoteKind = "wave" | "thumbsup" | "recycle" | "smile" | "cheer"; +const VALID_EMOTES: EmoteKind[] = ["wave", "thumbsup", "recycle", "smile", "cheer"]; + +export type ClientToServer = + | { type: "join"; level: Level; name: string; color: string } + | { type: "move"; x: number; z: number; rot: number } + | { type: "collect"; trashId: string } + | { type: "collectPowerUp"; powerUpId: string } + | { type: "emote"; kind: EmoteKind } + | { type: "ping"; t: number } + | { type: "admin.endRound"; password: string; result: "won" | "lost" } + | { type: "admin.spawnTrash"; password: string; count: number } + | { type: "admin.spawnPowerUp"; password: string; kind: PowerUpKind } + | { type: "admin.kick"; password: string; playerId: string } + | { type: "admin.setTimer"; password: string; seconds: number } + | { type: "admin.identify"; password: string }; + +export type ServerToClient = + | { + type: "init"; + selfId: string; + level: Level; + difficulty: Difficulty; + gameMode: GameMode; + code: string; + isPublic: boolean; + roundId: number; + timeLeft: number; + roundDuration: number; + winThreshold: number; + status: "playing" | "ended"; + players: SerializedPlayer[]; + trash: SerializedTrash[]; + powerUps: SerializedPowerUp[]; + mvpId: string | null; + } + | { type: "playerJoined"; player: SerializedPlayer } + | { type: "playerLeft"; id: string } + | { type: "positions"; players: { id: string; x: number; z: number; rot: number }[] } + | { + type: "trashCollected"; + trashId: string; trashType: TrashType; byId: string; byName: string; + score: number; pointsGained: number; combo: number; comboExpiresInMs: number; totalCollected: number; + } + | { type: "powerUpSpawned"; powerUp: SerializedPowerUp } + | { + type: "powerUpCollected"; + powerUpId: string; kind: PowerUpKind; byId: string; byName: string; + score: number; effectMs: number; bonusPoints: number; + } + | { type: "powerUpExpired"; powerUpId: string } + | { + type: "roundEnd"; + result: "won" | "lost"; cleanedPct: number; + scores: { id: string; name: string; color: string; score: number }[]; + mvpId: string | null; restartIn: number; + } + | { + type: "roundStart"; + roundId: number; trash: SerializedTrash[]; powerUps: SerializedPowerUp[]; + timeLeft: number; roundDuration: number; mvpId: string | null; gameMode: GameMode; + } + | { type: "emote"; playerId: string; kind: EmoteKind } + | { type: "kicked"; reason: string } + | { type: "adminAck"; ok: boolean; message: string } + | { type: "pong"; t: number } + | { type: "error"; message: string }; + +interface Player { + id: string; name: string; color: string; + x: number; z: number; rot: number; + score: number; combo: number; lastCollectAt: number; lastEmoteAt: number; + socket: WebSocket; alive: boolean; +} + +interface TrashItem { + id: string; type: TrashType; x: number; z: number; collected: boolean; +} + +interface PowerUp { + id: string; kind: PowerUpKind; x: number; z: number; expiresAt: number; collected: boolean; +} + +interface SerializedPlayer { + id: string; name: string; color: string; x: number; z: number; rot: number; score: number; +} +interface SerializedTrash { id: string; type: TrashType; x: number; z: number; } +interface SerializedPowerUp { id: string; kind: PowerUpKind; x: number; z: number; } + +const PLAYER_COLORS = [ + "#ff7043","#42a5f5","#ab47bc","#ffca28","#26a69a", + "#ec407a","#7e57c2","#5c6bc0","#66bb6a","#8d6e63", +]; + +function pickTrashType(level: Level): TrashType { + const r = Math.random(); + if (level === "beach") { + if (r < 0.55) return "plastic"; if (r < 0.75) return "metal"; if (r < 0.9) return "paper"; return "organic"; + } + if (level === "city" || level === "nightcity") { + if (r < 0.4) return "plastic"; if (r < 0.65) return "paper"; if (r < 0.85) return "metal"; return "organic"; + } + if (level === "arctic") { + if (r < 0.5) return "plastic"; if (r < 0.75) return "metal"; if (r < 0.9) return "paper"; return "organic"; + } + if (level === "jungle") { + if (r < 0.5) return "organic"; if (r < 0.75) return "plastic"; if (r < 0.9) return "paper"; return "metal"; + } + // park + if (r < 0.4) return "plastic"; if (r < 0.6) return "organic"; if (r < 0.8) return "paper"; return "metal"; +} + +function randomTrashPos(): { x: number; z: number } { + for (let a = 0; a < 10; a++) { + const x = (Math.random() * 2 - 1) * WORLD_HALF; + const z = (Math.random() * 2 - 1) * WORLD_HALF; + if (Math.abs(x) > 2 || Math.abs(z) > 2) return { x, z }; + } + return { x: WORLD_HALF * Math.random(), z: WORLD_HALF * Math.random() }; +} + +function generateTrash(level: Level, count: number): TrashItem[] { + const items: TrashItem[] = []; + for (let i = 0; i < count; i++) { + const { x, z } = randomTrashPos(); + items.push({ + id: `t-${Date.now().toString(36)}-${i}-${Math.random().toString(36).slice(2,6)}`, + type: pickTrashType(level), x, z, collected: false, + }); + } + return items; +} + +const POWERUP_KINDS: PowerUpKind[] = ["magnet", "speed", "bonus"]; +function pickPowerUpKind(): PowerUpKind { return POWERUP_KINDS[Math.floor(Math.random() * POWERUP_KINDS.length)]; } +let nextPowerUpSeq = 0; +function makePowerUp(kind?: PowerUpKind, lifetimeSec = POWERUP_LIFETIME_SEC): PowerUp { + const { x, z } = randomTrashPos(); + return { + id: `pu-${Date.now().toString(36)}-${nextPowerUpSeq++}`, + kind: kind ?? pickPowerUpKind(), x, z, + expiresAt: Date.now() + lifetimeSec * 1000, collected: false, + }; +} + +function serializePlayer(p: Player): SerializedPlayer { + return { id: p.id, name: p.name, color: p.color, x: p.x, z: p.z, rot: p.rot, score: p.score }; +} +function serializeTrash(t: TrashItem): SerializedTrash { return { id: t.id, type: t.type, x: t.x, z: t.z }; } +function serializePowerUp(p: PowerUp): SerializedPowerUp { return { id: p.id, kind: p.kind, x: p.x, z: p.z }; } + +function send(socket: WebSocket, msg: ServerToClient) { + if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(msg)); +} + +class Room { + level: Level; + difficulty: Difficulty; + gameMode: GameMode; + code: string; + isPublic: boolean; + players = new Map(); + trash: TrashItem[] = []; + powerUps: PowerUp[] = []; + status: "playing" | "ended" = "playing"; + result: "won" | "lost" | null = null; + timeLeft: number; + roundDuration: number; + trashCount: number; + winThreshold: number; + powerUpSpawnIntervalSec: number; + maxActivePowerUps: number; + roundId = 1; + endHold = 0; + usedColors = new Set(); + mvpId: string | null = null; + nextPowerUpAt: number; + + constructor(level: Level, code: string, isPublic: boolean, difficulty: Difficulty, gameMode: GameMode = "speedrun") { + this.level = level; + this.code = code; + this.isPublic = isPublic; + this.difficulty = difficulty; + this.gameMode = gameMode; + const dc = DIFFICULTY_CONFIG[difficulty]; + const mc = MODE_CONFIG[gameMode]; + this.roundDuration = Math.round(dc.roundDuration * mc.roundDurationScale); + this.trashCount = Math.max(8, Math.round(dc.trashCount * mc.trashCountScale)); + this.winThreshold = mc.winThresholdOverride ?? dc.winThreshold; + this.powerUpSpawnIntervalSec = mc.powerUpSpawnIntervalSec; + this.maxActivePowerUps = mc.maxActivePowerUps; + this.timeLeft = this.roundDuration; + this.trash = generateTrash(level, this.trashCount); + this.nextPowerUpAt = Date.now() + 8000; + } + + pickColor(): string { + for (const c of PLAYER_COLORS) if (!this.usedColors.has(c)) { this.usedColors.add(c); return c; } + return `hsl(${Math.floor(Math.random() * 360)}, 65%, 55%)`; + } + freeColor(c: string) { this.usedColors.delete(c); } + + broadcast(msg: ServerToClient, exceptId?: string) { + for (const p of this.players.values()) { + if (p.id === exceptId) continue; + send(p.socket, msg); + } + } + + addPlayer(player: Player) { + this.players.set(player.id, player); + send(player.socket, { + type: "init", + selfId: player.id, level: this.level, difficulty: this.difficulty, gameMode: this.gameMode, + code: this.code, isPublic: this.isPublic, roundId: this.roundId, + timeLeft: Math.ceil(this.timeLeft), roundDuration: this.roundDuration, + winThreshold: this.winThreshold, status: this.status, + players: Array.from(this.players.values()).map(serializePlayer), + trash: this.trash.filter(t => !t.collected).map(serializeTrash), + powerUps: this.powerUps.filter(p => !p.collected).map(serializePowerUp), + mvpId: this.mvpId, + }); + this.broadcast({ type: "playerJoined", player: serializePlayer(player) }, player.id); + logger.info({ level: this.level, difficulty: this.difficulty, gameMode: this.gameMode, playerId: player.id, total: this.players.size }, "Player joined room"); + } + + removePlayer(id: string) { + const p = this.players.get(id); if (!p) return; + this.players.delete(id); this.freeColor(p.color); + this.broadcast({ type: "playerLeft", id }); + logger.info({ level: this.level, playerId: id, total: this.players.size }, "Player left room"); + } + + handleMove(id: string, x: number, z: number, rot: number) { + const p = this.players.get(id); if (!p) return; + p.x = Math.max(-WORLD_HALF, Math.min(WORLD_HALF, x)); + p.z = Math.max(-WORLD_HALF, Math.min(WORLD_HALF, z)); + p.rot = rot; + } + + handleCollect(id: string, trashId: string) { + if (this.status !== "playing") return; + const p = this.players.get(id); if (!p) return; + const item = this.trash.find(t => t.id === trashId); + if (!item || item.collected) return; + const dx = item.x - p.x; const dz = item.z - p.z; + if (dx * dx + dz * dz > COLLECT_RADIUS_SQ * 4) return; + item.collected = true; + const now = Date.now(); + p.combo = (now - p.lastCollectAt <= COMBO_WINDOW_MS) ? Math.min(COMBO_MAX, p.combo + 1) : 1; + p.lastCollectAt = now; + const pointsGained = BASE_TRASH_POINTS * p.combo; + p.score += pointsGained; + const totalCollected = this.trash.filter(t => t.collected).length; + this.broadcast({ + type: "trashCollected", trashId, trashType: item.type, byId: id, byName: p.name, + score: p.score, pointsGained, combo: p.combo, comboExpiresInMs: COMBO_WINDOW_MS, totalCollected, + }); + if (totalCollected / this.trash.length >= this.winThreshold) this.endRound("won"); + } + + handleCollectPowerUp(id: string, powerUpId: string) { + if (this.status !== "playing") return; + const p = this.players.get(id); if (!p) return; + const pu = this.powerUps.find(x => x.id === powerUpId); + if (!pu || pu.collected) return; + const dx = pu.x - p.x; const dz = pu.z - p.z; + if (dx * dx + dz * dz > POWERUP_PICKUP_RADIUS_SQ * 4) return; + pu.collected = true; + let bonusPoints = 0; + if (pu.kind === "bonus") { bonusPoints = POWERUP_BONUS_POINTS; p.score += bonusPoints; } + this.broadcast({ + type: "powerUpCollected", powerUpId, kind: pu.kind, byId: id, byName: p.name, + score: p.score, effectMs: pu.kind === "bonus" ? 0 : POWERUP_EFFECT_SEC * 1000, bonusPoints, + }); + } + + handleEmote(id: string, kind: EmoteKind) { + const p = this.players.get(id); if (!p) return; + if (!VALID_EMOTES.includes(kind)) return; + const now = Date.now(); + if (now - p.lastEmoteAt < EMOTE_COOLDOWN_MS) return; + p.lastEmoteAt = now; + this.broadcast({ type: "emote", playerId: id, kind }); + } + + endRound(result: "won" | "lost") { + if (this.status === "ended") return; + this.status = "ended"; this.result = result; this.endHold = END_HOLD_SEC; + const cleaned = this.trash.filter(t => t.collected).length; + const cleanedPct = Math.round((cleaned / this.trash.length) * 100); + const scores = Array.from(this.players.values()) + .map(p => ({ id: p.id, name: p.name, color: p.color, score: p.score })) + .sort((a, b) => b.score - a.score); + this.mvpId = scores[0] && scores[0].score > 0 ? scores[0].id : null; + this.broadcast({ type: "roundEnd", result, cleanedPct, scores, mvpId: this.mvpId, restartIn: END_HOLD_SEC }); + logger.info({ level: this.level, gameMode: this.gameMode, result, cleanedPct, mvpId: this.mvpId }, "Round ended"); + } + + startNewRound() { + this.roundId += 1; this.status = "playing"; this.result = null; + this.timeLeft = this.roundDuration; + this.trash = generateTrash(this.level, this.trashCount); + this.powerUps = []; this.nextPowerUpAt = Date.now() + 8000; + for (const p of this.players.values()) { p.score = 0; p.combo = 0; p.lastCollectAt = 0; } + this.broadcast({ + type: "roundStart", roundId: this.roundId, + trash: this.trash.map(serializeTrash), powerUps: [], + timeLeft: this.timeLeft, roundDuration: this.roundDuration, + mvpId: this.mvpId, gameMode: this.gameMode, + }); + logger.info({ level: this.level, difficulty: this.difficulty, gameMode: this.gameMode, roundId: this.roundId }, "Round started"); + } + + tickPowerUps() { + if (this.status !== "playing") return; + const now = Date.now(); + for (const pu of this.powerUps) { + if (!pu.collected && now > pu.expiresAt) { + pu.collected = true; + this.broadcast({ type: "powerUpExpired", powerUpId: pu.id }); + } + } + this.powerUps = this.powerUps.filter(pu => !pu.collected); + if (this.players.size > 0 && now >= this.nextPowerUpAt && this.powerUps.length < this.maxActivePowerUps) { + const pu = makePowerUp(); + this.powerUps.push(pu); + this.broadcast({ type: "powerUpSpawned", powerUp: serializePowerUp(pu) }); + this.nextPowerUpAt = now + this.powerUpSpawnIntervalSec * 1000; + } + } + + tick(dt: number) { + if (this.status === "playing") { + this.timeLeft -= dt; + if (this.timeLeft <= 0) { this.timeLeft = 0; this.endRound("lost"); } + this.tickPowerUps(); + } else { + this.endHold -= dt; + if (this.endHold <= 0) this.startNewRound(); + } + } + + adminEndRound(result: "won" | "lost") { if (this.status !== "playing") return; this.endRound(result); } + + adminSpawnTrash(count: number) { + const safeCount = Math.max(1, Math.min(50, Math.floor(count))); + const newItems = generateTrash(this.level, safeCount); + this.trash.push(...newItems); + this.trashCount = this.trash.length; + for (const player of this.players.values()) { + send(player.socket, { + type: "init", selfId: player.id, level: this.level, difficulty: this.difficulty, gameMode: this.gameMode, + code: this.code, isPublic: this.isPublic, roundId: this.roundId, + timeLeft: Math.ceil(this.timeLeft), roundDuration: this.roundDuration, + winThreshold: this.winThreshold, status: this.status, + players: Array.from(this.players.values()).map(serializePlayer), + trash: this.trash.filter(t => !t.collected).map(serializeTrash), + powerUps: this.powerUps.filter(p => !p.collected).map(serializePowerUp), + mvpId: this.mvpId, + }); + } + } + + adminSpawnPowerUp(kind: PowerUpKind) { + if (this.status !== "playing") return; + const pu = makePowerUp(kind); + this.powerUps.push(pu); + this.broadcast({ type: "powerUpSpawned", powerUp: serializePowerUp(pu) }); + } + + adminKick(playerId: string): boolean { + const p = this.players.get(playerId); if (!p) return false; + send(p.socket, { type: "kicked", reason: "Removed by an owner." }); + try { p.socket.close(); } catch { /* ignore */ } + return true; + } + + adminSetTimer(seconds: number) { + if (this.status !== "playing") return; + this.timeLeft = Math.max(5, Math.min(600, Math.floor(seconds))); + } + + broadcastPositions() { + if (this.players.size === 0) return; + const players = Array.from(this.players.values()).map(p => ({ + id: p.id, x: +p.x.toFixed(2), z: +p.z.toFixed(2), rot: +p.rot.toFixed(2), + })); + this.broadcast({ type: "positions", players }); + } +} + +class RoomManager { + rooms = new Map(); + positionTimer: NodeJS.Timeout | null = null; + tickTimer: NodeJS.Timeout | null = null; + lastTick = Date.now(); + + ensurePublic(level: Level, gameMode: GameMode): Room { + const code = publicCode(level, gameMode); + let room = this.rooms.get(code); + if (!room) { + room = new Room(level, code, true, "normal", gameMode); + this.rooms.set(code, room); + logger.info({ code, level, gameMode }, "Created public room"); + } + return room; + } + + joinByCode(code: string): Room | null { + return this.rooms.get(code.toUpperCase()) ?? null; + } + + createPrivate(level: Level, difficulty: Difficulty, gameMode: GameMode): Room { + let code: string; + do { code = generateCode(); } while (this.rooms.has(code) || RESERVED.has(code)); + const room = new Room(level, code, false, difficulty, gameMode); + this.rooms.set(code, room); + logger.info({ code, level, difficulty, gameMode }, "Created private room"); + return room; + } + + disposeIfEmpty(room: Room): void { + if (room.isPublic) return; + if (room.players.size > 0) return; + this.rooms.delete(room.code); + logger.info({ code: room.code }, "Destroyed empty private room"); + } + + start() { + if (this.tickTimer) return; + this.lastTick = Date.now(); + this.tickTimer = setInterval(() => { + const now = Date.now(); const dt = (now - this.lastTick) / 1000; this.lastTick = now; + for (const room of this.rooms.values()) room.tick(dt); + }, 1000); + this.positionTimer = setInterval(() => { + for (const room of this.rooms.values()) room.broadcastPositions(); + }, Math.round(1000 / POSITION_BROADCAST_HZ)); + } +} + +export const roomManager = new RoomManager(); +let nextPlayerId = 1; +export function makePlayerId(): string { return `p${nextPlayerId++}`; } diff --git a/artifacts/api-server/src/multiplayer/wsHandler.ts b/artifacts/api-server/src/multiplayer/wsHandler.ts new file mode 100644 index 0000000000000000000000000000000000000000..410d0e6eaf10864bdc62459db001ab179164a8ef --- /dev/null +++ b/artifacts/api-server/src/multiplayer/wsHandler.ts @@ -0,0 +1,142 @@ +/** + * WebSocket handler that wires raw `ws` connections to the room manager. + */ + +import { WebSocketServer, type WebSocket } from "ws"; +import type { Server as HttpServer, IncomingMessage } from "http"; +import { logger } from "../lib/logger.js"; +import { + makePlayerId, + OWNER_PASSWORD, + roomManager, + VALID_DIFFICULTIES, + VALID_LEVELS, + VALID_GAME_MODES, + type ClientToServer, + type Difficulty, + type EmoteKind, + type GameMode, + type Level, + type PowerUpKind, +} from "./rooms.js"; + +const VALID_EMOTES: EmoteKind[] = ["wave", "thumbsup", "recycle", "smile", "cheer"]; +function isEmote(x: string): x is EmoteKind { return (VALID_EMOTES as string[]).includes(x); } +function isLevel(x: string): x is Level { return (VALID_LEVELS as string[]).includes(x); } +function isDifficulty(x: string): x is Difficulty { return (VALID_DIFFICULTIES as string[]).includes(x); } +function isGameMode(x: string): x is GameMode { return (VALID_GAME_MODES as string[]).includes(x); } + +const VALID_POWERUPS: PowerUpKind[] = ["magnet", "speed", "bonus"]; +function isPowerUpKind(x: string): x is PowerUpKind { return (VALID_POWERUPS as string[]).includes(x); } + +export function attachMultiplayer(server: HttpServer) { + const wss = new WebSocketServer({ noServer: true }); + roomManager.start(); + + server.on("upgrade", (request: IncomingMessage, socket, head) => { + const url = request.url ?? ""; + if (!url.startsWith("/api/ws")) { socket.destroy(); return; } + wss.handleUpgrade(request, socket, head, (ws) => { wss.emit("connection", ws, request); }); + }); + + wss.on("connection", (ws: WebSocket, request: IncomingMessage) => { + const url = new URL(request.url ?? "/", "http://localhost"); + const levelParam = url.searchParams.get("level") ?? "park"; + const nameParam = (url.searchParams.get("name") ?? "Player").slice(0, 20); + const codeParam = url.searchParams.get("code"); + const diffParam = url.searchParams.get("difficulty") ?? "normal"; + const modeParam = url.searchParams.get("mode") ?? "speedrun"; + const level: Level = isLevel(levelParam) ? levelParam : "park"; + const difficulty: Difficulty = isDifficulty(diffParam) ? diffParam : "normal"; + const gameMode: GameMode = isGameMode(modeParam) ? modeParam : "speedrun"; + + let room; + if (codeParam) { + const upper = codeParam.toUpperCase(); + if (upper === "NEW") { + room = roomManager.createPrivate(level, difficulty, gameMode); + } else { + const existing = roomManager.joinByCode(upper); + if (!existing) { + ws.send(JSON.stringify({ type: "error", message: `No room with code "${upper}". Check the code and try again.` })); + ws.close(); return; + } + room = existing; + } + } else { + room = roomManager.ensurePublic(level, gameMode); + } + + const playerId = makePlayerId(); + const color = room.pickColor(); + const player = { + id: playerId, + name: nameParam || "Player", + color, + x: (Math.random() - 0.5) * 4, + z: (Math.random() - 0.5) * 4, + rot: 0, + score: 0, + combo: 0, + lastCollectAt: 0, + lastEmoteAt: 0, + socket: ws, + alive: true, + }; + room.addPlayer(player); + + ws.on("message", (raw) => { + let msg: ClientToServer; + try { msg = JSON.parse(raw.toString()); } catch { return; } + switch (msg.type) { + case "move": + if (typeof msg.x === "number" && typeof msg.z === "number" && typeof msg.rot === "number" + && Number.isFinite(msg.x) && Number.isFinite(msg.z) && Number.isFinite(msg.rot)) { + room.handleMove(playerId, msg.x, msg.z, msg.rot); + } + break; + case "collect": + if (typeof msg.trashId === "string") room.handleCollect(playerId, msg.trashId); + break; + case "collectPowerUp": + if (typeof msg.powerUpId === "string") room.handleCollectPowerUp(playerId, msg.powerUpId); + break; + case "emote": + if (typeof msg.kind === "string" && isEmote(msg.kind)) room.handleEmote(playerId, msg.kind); + break; + case "ping": + ws.send(JSON.stringify({ type: "pong", t: msg.t })); + break; + case "join": break; + case "admin.identify": + ws.send(JSON.stringify(msg.password === OWNER_PASSWORD + ? { type: "adminAck", ok: true, message: "Owner mode unlocked." } + : { type: "adminAck", ok: false, message: "Wrong owner password." } + )); + break; + case "admin.endRound": + if (msg.password === OWNER_PASSWORD) room.adminEndRound(msg.result === "won" ? "won" : "lost"); + break; + case "admin.spawnTrash": + if (msg.password === OWNER_PASSWORD && typeof msg.count === "number") room.adminSpawnTrash(msg.count); + break; + case "admin.spawnPowerUp": + if (msg.password === OWNER_PASSWORD && typeof msg.kind === "string" && isPowerUpKind(msg.kind)) + room.adminSpawnPowerUp(msg.kind); + break; + case "admin.kick": + if (msg.password === OWNER_PASSWORD && typeof msg.playerId === "string" && msg.playerId !== playerId) + room.adminKick(msg.playerId); + break; + case "admin.setTimer": + if (msg.password === OWNER_PASSWORD && typeof msg.seconds === "number") room.adminSetTimer(msg.seconds); + break; + } + }); + + ws.on("close", () => { room.removePlayer(playerId); roomManager.disposeIfEmpty(room); }); + ws.on("error", (err: Error) => { logger.warn({ err, playerId }, "WebSocket error"); }); + }); + + logger.info("Multiplayer WebSocket server attached at /api/ws"); +} diff --git a/artifacts/api-server/src/routes/health.ts b/artifacts/api-server/src/routes/health.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0a144626055cbc728d5d813d63b389ae1e82bee --- /dev/null +++ b/artifacts/api-server/src/routes/health.ts @@ -0,0 +1,11 @@ +import { Router, type IRouter } from "express"; +import { HealthCheckResponse } from "@workspace/api-zod"; + +const router: IRouter = Router(); + +router.get("/healthz", (_req, res) => { + const data = HealthCheckResponse.parse({ status: "ok" }); + res.json(data); +}); + +export default router; diff --git a/artifacts/api-server/src/routes/index.ts b/artifacts/api-server/src/routes/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a1f77abda69515f1657b86f551c97570d05d6a3 --- /dev/null +++ b/artifacts/api-server/src/routes/index.ts @@ -0,0 +1,8 @@ +import { Router, type IRouter } from "express"; +import healthRouter from "./health"; + +const router: IRouter = Router(); + +router.use(healthRouter); + +export default router; diff --git a/artifacts/api-server/tsconfig.json b/artifacts/api-server/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..b60e718d970f7497ab0d119899c3b6b9cc881b32 --- /dev/null +++ b/artifacts/api-server/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "types": ["node"] + }, + "include": ["src"], + "references": [ + { + "path": "../../lib/db" + }, + { + "path": "../../lib/api-zod" + } + ] +} diff --git a/artifacts/eco-cleanup-game/.replit-artifact/artifact.toml b/artifacts/eco-cleanup-game/.replit-artifact/artifact.toml new file mode 100644 index 0000000000000000000000000000000000000000..734c3db58077491334d5a291545ccdcf211476fd --- /dev/null +++ b/artifacts/eco-cleanup-game/.replit-artifact/artifact.toml @@ -0,0 +1,31 @@ +kind = "web" +previewPath = "/" +title = "EcoClean 3D Game" +version = "1.0.0" +id = "artifacts/eco-cleanup-game" +router = "path" + +[[integratedSkills]] +name = "react-vite" +version = "1.0.0" + +[[services]] +name = "web" +paths = [ "/" ] +localPort = 18257 + +[services.development] +run = "pnpm --filter @workspace/eco-cleanup-game run dev" + +[services.production] +build = [ "pnpm", "--filter", "@workspace/eco-cleanup-game", "run", "build" ] +publicDir = "artifacts/eco-cleanup-game/dist/public" +serve = "static" + +[[services.production.rewrites]] +from = "/*" +to = "/index.html" + +[services.env] +PORT = "18257" +BASE_PATH = "/" diff --git a/artifacts/eco-cleanup-game/components.json b/artifacts/eco-cleanup-game/components.json new file mode 100644 index 0000000000000000000000000000000000000000..3ff62cf0842657da595682900f6aa27592c67b4c --- /dev/null +++ b/artifacts/eco-cleanup-game/components.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/index.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + } +} \ No newline at end of file diff --git a/artifacts/eco-cleanup-game/index.html b/artifacts/eco-cleanup-game/index.html new file mode 100644 index 0000000000000000000000000000000000000000..3e55c1bb1749a0f75fe838e6bb203fc11c660fc1 --- /dev/null +++ b/artifacts/eco-cleanup-game/index.html @@ -0,0 +1,16 @@ + + + + + + EcoClean 3D Game + + + + + + +
+ + + diff --git a/artifacts/eco-cleanup-game/package.json b/artifacts/eco-cleanup-game/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c7b0e243374e2236bf33dde3791a559dc0a38e78 --- /dev/null +++ b/artifacts/eco-cleanup-game/package.json @@ -0,0 +1,81 @@ +{ + "name": "@workspace/eco-cleanup-game", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --config vite.config.ts --host 0.0.0.0", + "build": "vite build --config vite.config.ts", + "serve": "vite preview --config vite.config.ts --host 0.0.0.0", + "typecheck": "tsc -p tsconfig.json --noEmit" + }, + "devDependencies": { + "@hookform/resolvers": "^3.10.0", + "@radix-ui/react-accordion": "^1.2.4", + "@radix-ui/react-alert-dialog": "^1.1.7", + "@radix-ui/react-aspect-ratio": "^1.1.3", + "@radix-ui/react-avatar": "^1.1.4", + "@radix-ui/react-checkbox": "^1.1.5", + "@radix-ui/react-collapsible": "^1.1.4", + "@radix-ui/react-context-menu": "^2.2.7", + "@radix-ui/react-dialog": "^1.1.7", + "@radix-ui/react-dropdown-menu": "^2.1.7", + "@radix-ui/react-hover-card": "^1.1.7", + "@radix-ui/react-label": "^2.1.3", + "@radix-ui/react-menubar": "^1.1.7", + "@radix-ui/react-navigation-menu": "^1.2.6", + "@radix-ui/react-popover": "^1.1.7", + "@radix-ui/react-progress": "^1.1.3", + "@radix-ui/react-radio-group": "^1.2.4", + "@radix-ui/react-scroll-area": "^1.2.4", + "@radix-ui/react-select": "^2.1.7", + "@radix-ui/react-separator": "^1.1.3", + "@radix-ui/react-slider": "^1.2.4", + "@radix-ui/react-slot": "^1.2.0", + "@radix-ui/react-switch": "^1.1.4", + "@radix-ui/react-tabs": "^1.1.4", + "@radix-ui/react-toast": "^1.2.7", + "@radix-ui/react-toggle": "^1.1.3", + "@radix-ui/react-toggle-group": "^1.1.3", + "@radix-ui/react-tooltip": "^1.2.0", + "@replit/vite-plugin-cartographer": "catalog:", + "@replit/vite-plugin-dev-banner": "catalog:", + "@replit/vite-plugin-runtime-error-modal": "catalog:", + "@tailwindcss/typography": "^0.5.15", + "@tailwindcss/vite": "catalog:", + "@tanstack/react-query": "catalog:", + "@types/node": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@types/three": "^0.184.0", + "@vitejs/plugin-react": "catalog:", + "@workspace/api-client-react": "workspace:*", + "class-variance-authority": "catalog:", + "clsx": "catalog:", + "cmdk": "^1.1.1", + "date-fns": "^3.6.0", + "embla-carousel-react": "^8.6.0", + "framer-motion": "catalog:", + "input-otp": "^1.4.2", + "lucide-react": "catalog:", + "next-themes": "^0.4.6", + "react": "catalog:", + "react-day-picker": "^9.11.1", + "react-dom": "catalog:", + "react-hook-form": "^7.55.0", + "react-icons": "^5.4.0", + "react-resizable-panels": "^2.1.7", + "recharts": "^2.15.2", + "sonner": "^2.0.7", + "tailwind-merge": "catalog:", + "tailwindcss": "catalog:", + "tw-animate-css": "^1.4.0", + "vaul": "^1.1.2", + "vite": "catalog:", + "wouter": "^3.3.5", + "zod": "catalog:" + }, + "dependencies": { + "three": "^0.184.0" + } +} diff --git a/artifacts/eco-cleanup-game/public/favicon.svg b/artifacts/eco-cleanup-game/public/favicon.svg new file mode 100644 index 0000000000000000000000000000000000000000..4373d3cd2f3dad5ca6f33b5cdcccc61edaef8eb7 --- /dev/null +++ b/artifacts/eco-cleanup-game/public/favicon.svg @@ -0,0 +1,3 @@ + + + diff --git a/artifacts/eco-cleanup-game/public/opengraph.jpg b/artifacts/eco-cleanup-game/public/opengraph.jpg new file mode 100644 index 0000000000000000000000000000000000000000..89b2e3a3465fec3738376f8c820a210ec92c177d Binary files /dev/null and b/artifacts/eco-cleanup-game/public/opengraph.jpg differ diff --git a/artifacts/eco-cleanup-game/src/App.tsx b/artifacts/eco-cleanup-game/src/App.tsx new file mode 100644 index 0000000000000000000000000000000000000000..298b1f26b10465c02bf270b68cfb7e548a180720 --- /dev/null +++ b/artifacts/eco-cleanup-game/src/App.tsx @@ -0,0 +1,863 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { + DIFFICULTY_LABELS, + EMOTES, + GAME_MODE_DESCRIPTIONS, + GAME_MODE_LABELS, + LEVEL_LABELS, + POWERUP_EMOJIS, + POWERUP_LABELS, + startGame, + type AdminCommand, + type Difficulty, + type EmoteKind, + type GameHandle, + type GameMode, + type GameState, + type Level, + type MiniMapData, + type PowerUpKind, +} from "@/game"; + +const NAME_KEY = "ecoclean.playerName"; +const SETTINGS_KEY = "ecoclean.settings"; + +const TRASH_LABELS: Record = { + plastic: "a plastic bottle", + metal: "a soda can", + paper: "some paper", + organic: "some organic waste", +}; + +const DIFFICULTY_BLURBS: Record = { + easy: "180s round · 24 trash · 60% to win", + normal: "120s round · 32 trash · 80% to win", + hard: "90s round · 44 trash · 90% to win", +}; + +const MODE_COLORS: Record = { + speedrun: "bg-yellow-500", + percent100: "bg-emerald-600", + powerup: "bg-purple-600", +}; + +const POWERUP_KINDS: PowerUpKind[] = ["magnet", "speed", "bonus"]; + +const ALL_LEVELS: Level[] = ["park", "beach", "city", "nightcity", "arctic", "jungle"]; + +const DEFAULT_STATE: GameState = { + status: "menu", + level: "park", + gameMode: "speedrun", + difficulty: "normal", + roundDuration: 120, + selfId: null, selfName: "", selfScore: 0, timeLeft: 0, + totalTrash: 0, collected: 0, players: [], fact: null, lastResult: null, + soundOn: true, musicVolume: 0.5, sfxVolume: 0.7, mouseSensitivity: 1.0, + pickupNotice: null, powerUpNotice: null, combo: null, mvpId: null, floatingPoints: [], + roomCode: null, isPublicRoom: false, errorMessage: null, sprintStamina: 1, isSprinting: false, + magnetMs: 0, speedMs: 0, + miniMap: { worldHalf: 28, selfX: 0, selfZ: 0, others: [], trash: [], powerUps: [] }, + isOwner: false, ownerStatus: null, godMode: false, + stats: { trashCleaned: 0, powerUpsCollected: 0, bestCombo: 0, pointsEarned: 0 }, + isPaused: false, +}; + +interface PersistedSettings { musicVolume: number; sfxVolume: number; mouseSensitivity: number; } +function loadSettings(): PersistedSettings | null { + if (typeof window === "undefined") return null; + try { const raw = window.localStorage.getItem(SETTINGS_KEY); if (!raw) return null; return JSON.parse(raw) as PersistedSettings; } catch { return null; } +} +function saveSettings(s: PersistedSettings) { + try { window.localStorage.setItem(SETTINGS_KEY, JSON.stringify(s)); } catch { /* ignore */ } +} + +/** Enhanced Mini-map with legend */ +function MiniMap({ data, godMode }: { data: MiniMapData; godMode: boolean }) { + const SIZE = 200; const HALF = SIZE / 2; const scale = HALF / data.worldHalf; + const projX = (x: number) => HALF + (x - data.selfX) * scale; + const projZ = (z: number) => HALF + (z - data.selfZ) * scale; + return ( +
+
+ + {/* Compass cardinal marks */} + N + S + W + E + {/* World border */} + + {/* Grid lines */} + {[-14, 0, 14].map(v => ( + + + + + ))} + {/* Trash blips — yellow dots with a cross */} + {data.trash.map((t, i) => ( + + + + ))} + {/* Power-up blips */} + {data.powerUps.map((p, i) => ( + + ))} + {/* Other players */} + {data.others.map(o => ( + + ))} + {/* Self — pulsing green dot */} + + + +
+ {/* Legend */} +
+ Trash + You + {data.others.length > 0 && Team} +
+
+ ); +} + +function App() { + const mountRef = useRef(null); + const gameRef = useRef(null); + + const [name, setName] = useState(() => { + if (typeof window !== "undefined") return window.localStorage.getItem(NAME_KEY) ?? ""; + return ""; + }); + const initialJoinCode = useMemo(() => { + if (typeof window === "undefined") return ""; + const c = new URL(window.location.href).searchParams.get("code"); + return (c ?? "").toUpperCase().slice(0, 8); + }, []); + const [joinCode, setJoinCode] = useState(initialJoinCode); + const [showPrivate, setShowPrivate] = useState(false); + const [privateDifficulty, setPrivateDifficulty] = useState("normal"); + const [copied, setCopied] = useState(false); + + // Lobby flow: mode → map → play + const [lobbyMode, setLobbyMode] = useState(null); + const [lobbyStep, setLobbyStep] = useState<"mode" | "map" | null>(null); + const [privateMode, setPrivateMode] = useState("speedrun"); + + // UI panels + const [showSettings, setShowSettings] = useState(false); + const [showStats, setShowStats] = useState(false); + const [showOwnerLogin, setShowOwnerLogin] = useState(false); + const [ownerPwInput, setOwnerPwInput] = useState(""); + const [showOwnerPanel, setShowOwnerPanel] = useState(false); + const [adminTimerInput, setAdminTimerInput] = useState("60"); + + const [state, setState] = useState(DEFAULT_STATE); + + useEffect(() => { + if (!mountRef.current) return; + const handle = startGame(mountRef.current, setState); + gameRef.current = handle; + const saved = loadSettings(); + if (saved) { + handle.setMusicVolume(saved.musicVolume); + handle.setSfxVolume(saved.sfxVolume); + handle.setMouseSensitivity(saved.mouseSensitivity); + } + return () => handle.dispose(); + }, []); + + useEffect(() => { + saveSettings({ musicVolume: state.musicVolume, sfxVolume: state.sfxVolume, mouseSensitivity: state.mouseSensitivity }); + }, [state.musicVolume, state.sfxVolume, state.mouseSensitivity]); + + // ESC key — pause/unpause (only when playing) + useEffect(() => { + const handleEsc = (e: KeyboardEvent) => { + if (e.key !== "Escape") return; + if (state.status !== "playing") return; + if (showSettings || showOwnerPanel || showOwnerLogin || showStats) { + setShowSettings(false); setShowOwnerPanel(false); setShowOwnerLogin(false); setShowStats(false); + return; + } + gameRef.current?.setPaused(!state.isPaused); + }; + window.addEventListener("keydown", handleEsc); + return () => window.removeEventListener("keydown", handleEsc); + }, [state.status, state.isPaused, showSettings, showOwnerPanel, showOwnerLogin, showStats]); + + // P key — admin panel + useEffect(() => { + const handleAdminKey = (e: KeyboardEvent) => { + if (e.key !== "p" && e.key !== "P") return; + if (state.status !== "playing" && state.status !== "waiting") return; + if (state.isPaused) return; + if (state.isOwner) setShowOwnerPanel(true); else setShowOwnerLogin(true); + }; + window.addEventListener("keydown", handleAdminKey); + return () => window.removeEventListener("keydown", handleAdminKey); + }, [state.status, state.isOwner, state.isPaused]); + + const finalName = () => (name.trim() || "Player").slice(0, 18); + const persistName = (n: string) => window.localStorage.setItem(NAME_KEY, n); + + const handleJoinPublic = (level: Level) => { + const n = finalName(); persistName(n); + gameRef.current?.start({ kind: "public", level, name: n, gameMode: lobbyMode ?? "speedrun" }); + setLobbyStep(null); setLobbyMode(null); + }; + const handleCreatePrivate = (level: Level) => { + const n = finalName(); persistName(n); + gameRef.current?.start({ kind: "private", level, name: n, difficulty: privateDifficulty, gameMode: privateMode }); + }; + const handleJoinCode = () => { + const code = joinCode.trim().toUpperCase(); if (!code) return; + const n = finalName(); persistName(n); + gameRef.current?.start({ kind: "join", code, name: n }); + }; + + const handleCopyCode = async () => { + if (!state.roomCode) return; + const shareUrl = `${window.location.origin}${window.location.pathname}?code=${state.roomCode}`; + try { await navigator.clipboard.writeText(shareUrl); } catch { await navigator.clipboard.writeText(state.roomCode).catch(() => undefined); } + setCopied(true); setTimeout(() => setCopied(false), 1500); + }; + const handleSubmitOwner = () => { + const pw = ownerPwInput.trim(); if (!pw) return; + gameRef.current?.submitOwnerPassword(pw); setOwnerPwInput(""); + }; + const sendAdmin = (cmd: AdminCommand) => gameRef.current?.sendAdmin(cmd); + + const cleanedPct = state.totalTrash > 0 ? Math.round((state.collected / state.totalTrash) * 100) : 0; + const minutes = Math.floor(state.timeLeft / 60); + const seconds = state.timeLeft % 60; + const timeStr = `${minutes}:${seconds.toString().padStart(2, "0")}`; + const comboPct = state.combo + ? Math.max(0, Math.min(1, (state.combo.expiresAt - performance.now()) / state.combo.windowMs)) + : 0; + const inGame = state.status === "playing" || state.status === "waiting"; + + return ( +
+
+ + {/* Top HUD */} + {inGame && ( +
+
+
+
+
Your Score
+
{state.selfScore}
+
+
+
+
Time
+
{timeStr}
+
+
+
+
Map
+
{LEVEL_LABELS[state.level]}
+
+
+
+
Mode
+
+ {GAME_MODE_LABELS[state.gameMode]} +
+
+
+
+
Players
+
{state.players.length}
+
+ {state.roomCode && ( + <> +
+ + + )} +
+ +
+
+ + + + {state.isOwner ? ( + + ) : ( + + )} + + +
+
+
+ + {/* Progress bar */} +
+
+ + {state.gameMode === "percent100" ? "♻️ Must collect ALL trash!" : "Environment Cleaned (team)"} + + + {state.collected}/{state.collected + (state.totalTrash - state.collected)} ({cleanedPct}%) + +
+
+
+ {state.gameMode !== "speedrun" && ( +
+ )} + {state.gameMode === "speedrun" && ( +
+ )} +
+
+ + {/* Active power-up timers */} + {(state.magnetMs > 0 || state.speedMs > 0 || state.godMode) && ( +
+ {state.magnetMs > 0 &&
🧲 Magnet · {(state.magnetMs / 1000).toFixed(1)}s
} + {state.speedMs > 0 &&
⚡ Speed · {(state.speedMs / 1000).toFixed(1)}s
} + {state.godMode &&
✨ God Mode
} +
+ )} +
+ )} + + {/* Mini-map — bottom-right, always visible in-game */} + {inGame && ( +
+ +
+ )} + + {/* Sprint stamina bar */} + {state.status === "playing" && ( +
+
+
+ Sprint (Shift){Math.round(state.sprintStamina * 100)}% +
+
+
+
+
+
+ )} + + {/* Scoreboard */} + {inGame && state.players.length > 0 && ( +
+
+
Leaderboard
+
+ {state.players.slice(0, 8).map((p, idx) => ( +
+ {idx + 1}. + + + {state.mvpId === p.id && 👑} + {p.name}{p.id === state.selfId && (you)} + + {p.score} +
+ ))} +
+
+
+ )} + + {/* Educational fact */} + {state.status === "playing" && state.fact && ( +
+
+
Did you know?
+
{state.fact}
+
+
+ )} + + {/* Pickup/powerup notices */} + {state.status === "playing" && state.pickupNotice && ( +
+
+ {state.pickupNotice.byName}{" picked up "}{TRASH_LABELS[state.pickupNotice.trashType] ?? "trash"} +
+
+ )} + {state.status === "playing" && state.powerUpNotice && ( +
+
+ {state.powerUpNotice.byName}{" grabbed "} + {POWERUP_EMOJIS[state.powerUpNotice.kind]}{" "}{POWERUP_LABELS[state.powerUpNotice.kind]} + {state.powerUpNotice.bonus > 0 ? ` (+${state.powerUpNotice.bonus})` : ""} +
+
+ )} + + {/* Combo + floating points */} + {state.status === "playing" && (state.combo || state.floatingPoints.length > 0) && ( +
+ {state.combo && state.combo.combo > 1 && ( +
+
Combo
+
{state.combo.combo}× streak
+
+
+
+
+ )} +
+ {state.floatingPoints.slice(-4).map(fp => ( +
+ {fp.text} +
+ ))} +
+
+ )} + + {/* Emote bar */} + {inGame && ( +
+
+ {EMOTES.map(e => ( + + ))} +
+
+ )} + + {/* Controls helper */} + {state.status === "playing" && !state.isPaused && ( +
+
+
Controls
+
WASD / Arrows — Move
+
Shift — Sprint
+
Mouse — Look around
+
Walk over trash / power-ups
+
1–5 — Emote
+
P — Admin panel
+
ESC — Pause
+
+
+ )} + + {/* ── PAUSE MENU ────────────────────────────── */} + {state.isPaused && state.status === "playing" && ( +
+
+
⏸
+

Game Paused

+

Other players keep playing. Your progress is saved.

+
+ {GAME_MODE_LABELS[state.gameMode]} + {LEVEL_LABELS[state.level]} +
+
+ + + + +
+

Press ESC to resume

+
+
+ )} + + {/* Round-end overlay */} + {state.status === "waiting" && state.lastResult && ( +
+
+
{state.lastResult.result === "won" ? "🎉" : "⏰"}
+

+ {state.lastResult.result === "won" ? "Environment Cleaned!" : "Time's Up!"} +

+

The team cleaned {state.lastResult.cleanedPct}% of the area.

+
+
Final standings
+ {state.lastResult.scores.map((s, i) => ( +
+ {i + 1}. + + + {i === 0 && state.lastResult!.scores.length > 1 && 👑} + {s.name} + + {s.score} +
+ ))} +
+

Next round starting soon… hang tight!

+

EcoClean 3D — Created by Utkarsh Pandey and Nishant Amrit

+
+
+ )} + + {/* Settings overlay */} + {showSettings && ( +
setShowSettings(false)}> +
e.stopPropagation()}> +
+

⚙️ Settings

+ +
+
+ {[ + { label: "🎵 Music", value: state.musicVolume, fn: (v: number) => gameRef.current?.setMusicVolume(v), max: 1 }, + { label: "🔊 Sound effects", value: state.sfxVolume, fn: (v: number) => gameRef.current?.setSfxVolume(v), max: 1 }, + ].map(s => ( + + ))} + + +
+
+
+ )} + + {/* Stats overlay */} + {showStats && ( +
setShowStats(false)}> +
e.stopPropagation()}> +
+

📊 Stats

+ +
+
+
{state.stats.trashCleaned}
Trash cleaned
+
{state.stats.powerUpsCollected}
Power-ups
+
{state.stats.bestCombo}×
Best combo
+
{state.stats.pointsEarned}
Points
+
+
+
+ )} + + {/* Owner login */} + {showOwnerLogin && ( +
setShowOwnerLogin(false)}> +
e.stopPropagation()}> +
+

🔐 Owner Sign-in

+ +
+

Enter the owner password to unlock admin commands for this room.

+ setOwnerPwInput(e.target.value)} + onKeyDown={e => { if (e.key === "Enter") { handleSubmitOwner(); setShowOwnerLogin(false); } }} + placeholder="Owner password" autoFocus + className="w-full border-2 border-purple-200 focus:border-purple-500 focus:outline-none rounded-lg px-3 py-2 text-purple-900 mb-3" /> + {state.ownerStatus && !state.ownerStatus.ok && ( +
{state.ownerStatus.message}
+ )} + +
+
+ )} + + {/* Owner panel */} + {showOwnerPanel && state.isOwner && ( +
setShowOwnerPanel(false)}> +
e.stopPropagation()}> +
+

👑 Owner Panel

+ +
+ {state.ownerStatus?.ok &&
{state.ownerStatus.message}
} +
+
Round
+
+ + +
+
+ setAdminTimerInput(e.target.value)} + className="border-2 border-purple-200 focus:border-purple-500 focus:outline-none rounded px-2 py-1 w-24 text-purple-900" /> + +
+
+
+
Spawn
+
+ + +
+
+ {POWERUP_KINDS.map(k => ( + + ))} +
+
+ {state.players.filter(p => p.id !== state.selfId).length > 0 && ( +
+
Players
+
+ {state.players.filter(p => p.id !== state.selfId).map(p => ( +
+ + {p.name} + +
+ ))} +
+
+ )} +
+
Local
+ +
+

Owner commands are gated by password on the server.

+
+
+ )} + + {/* Connecting */} + {state.status === "connecting" && ( +
+
+
🌍
+

Connecting…

+

Joining the {LEVEL_LABELS[state.level]} cleanup crew.

+
+
+ )} + + {/* Disconnected */} + {state.status === "disconnected" && ( +
+
+
📡
+

Disconnected

+

Lost connection to the server. Check your internet and try again.

+ +
+
+ )} + + {/* ── MAIN MENU ─────────────────────────────── */} + {state.status === "menu" && ( +
+
+
🌍
+

EcoClean 3D

+

Multiplayer cleanup. One world. One team.

+

Pick a game mode, choose your map, and clean up together!

+ + {state.errorMessage && ( +
⚠️ {state.errorMessage}
+ )} + + {/* Player name */} +
+ + setName(e.target.value)} maxLength={18} placeholder="Enter your name" + className="w-full border-2 border-emerald-200 focus:border-emerald-500 focus:outline-none rounded-lg px-3 py-2 text-emerald-900" /> +
+ + {/* ── LOBBY FLOW: mode → map ── */} + {lobbyStep === null && ( + <> + {/* Quick join public */} +
+
Join a public room
+ +
+ + {/* Join with code */} +
+
Join with a room code
+
+ setJoinCode(e.target.value.toUpperCase().replace(/[^A-Z0-9\-]/g, "").slice(0, 10))} + onKeyDown={e => { if (e.key === "Enter") handleJoinCode(); }} + placeholder="ROOM-CODE" className="flex-1 border-2 border-sky-200 focus:border-sky-500 focus:outline-none rounded-lg px-3 py-2 text-sky-900 font-bold tracking-widest tabular-nums uppercase" /> + +
+
+ + {/* Private room */} +
+ + {showPrivate && ( + <> +

A new code will be generated. Share it with friends to join the same room.

+ +
Game Mode
+
+ {(["speedrun", "percent100", "powerup"] as const).map(m => ( + + ))} +
+

{GAME_MODE_DESCRIPTIONS[privateMode]}

+ +
Difficulty
+
+ {(["easy", "normal", "hard"] as const).map(d => ( + + ))} +
+

{DIFFICULTY_BLURBS[privateDifficulty]}

+ +
Choose Map
+
+ {ALL_LEVELS.map(lvl => ( + + ))} +
+ + )} +
+ + {/* Tips */} +
+
♻️ +10 pts per trash · combo multiplier for fast pickups
+
🧲⚡⭐ Power-ups spawn mid-round — grab them fast
+
🏃 Shift to sprint · 1–5 to emote · ESC to pause
+
👑 Top scorer wears the MVP crown
+
+ +
+ + · + +
+

Created by Utkarsh Pandey and Nishant Amrit

+ + )} + + {/* Step 1: Pick game mode */} + {lobbyStep === "mode" && ( +
+ +

Choose Game Mode

+
+ {(["speedrun", "percent100", "powerup"] as const).map(m => ( + + ))} +
+
+ )} + + {/* Step 2: Pick map */} + {lobbyStep === "map" && lobbyMode && ( +
+ +
+

Choose Map

+ {GAME_MODE_LABELS[lobbyMode]} +
+
+ {ALL_LEVELS.map(lvl => { + const desc: Record = { + park: "Lush green park with trees & flowers", + beach: "Sandy shore with palm trees & ocean", + city: "Busy urban streets & tall buildings", + nightcity: "Neon-lit cyberpunk city at night", + arctic: "Frozen tundra with ice & blizzards", + jungle: "Dense tropical rainforest with mist", + }; + return ( + + ); + })} +
+
+ )} +
+
+ )} + + {/* Unsupported */} + {state.status === "unsupported" && ( +
+
+
🌐
+

WebGL not available

+

This 3D game needs a WebGL-capable browser. Try Chrome, Firefox, Edge, or Safari.

+
+
+ )} +
+ ); +} + +export default App; diff --git a/artifacts/eco-cleanup-game/src/components/ui/accordion.tsx b/artifacts/eco-cleanup-game/src/components/ui/accordion.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e1797c93458f3751a2e0f1189ff50d77f20ae3ed --- /dev/null +++ b/artifacts/eco-cleanup-game/src/components/ui/accordion.tsx @@ -0,0 +1,55 @@ +import * as React from "react" +import * as AccordionPrimitive from "@radix-ui/react-accordion" +import { ChevronDown } from "lucide-react" + +import { cn } from "@/lib/utils" + +const Accordion = AccordionPrimitive.Root + +const AccordionItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AccordionItem.displayName = "AccordionItem" + +const AccordionTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + svg]:rotate-180", + className + )} + {...props} + > + {children} + + + +)) +AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName + +const AccordionContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + +
{children}
+
+)) +AccordionContent.displayName = AccordionPrimitive.Content.displayName + +export { Accordion, AccordionItem, AccordionTrigger, AccordionContent } diff --git a/artifacts/eco-cleanup-game/src/components/ui/alert-dialog.tsx b/artifacts/eco-cleanup-game/src/components/ui/alert-dialog.tsx new file mode 100644 index 0000000000000000000000000000000000000000..fa2b4429f4303210462ad03f9f49280ac5ae07ce --- /dev/null +++ b/artifacts/eco-cleanup-game/src/components/ui/alert-dialog.tsx @@ -0,0 +1,139 @@ +import * as React from "react" +import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog" + +import { cn } from "@/lib/utils" +import { buttonVariants } from "@/components/ui/button" + +const AlertDialog = AlertDialogPrimitive.Root + +const AlertDialogTrigger = AlertDialogPrimitive.Trigger + +const AlertDialogPortal = AlertDialogPrimitive.Portal + +const AlertDialogOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName + +const AlertDialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + + +)) +AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName + +const AlertDialogHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+) +AlertDialogHeader.displayName = "AlertDialogHeader" + +const AlertDialogFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+) +AlertDialogFooter.displayName = "AlertDialogFooter" + +const AlertDialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName + +const AlertDialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AlertDialogDescription.displayName = + AlertDialogPrimitive.Description.displayName + +const AlertDialogAction = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName + +const AlertDialogCancel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName + +export { + AlertDialog, + AlertDialogPortal, + AlertDialogOverlay, + AlertDialogTrigger, + AlertDialogContent, + AlertDialogHeader, + AlertDialogFooter, + AlertDialogTitle, + AlertDialogDescription, + AlertDialogAction, + AlertDialogCancel, +} diff --git a/artifacts/eco-cleanup-game/src/components/ui/alert.tsx b/artifacts/eco-cleanup-game/src/components/ui/alert.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5afd41d142c95c74069ebb5460117e74ead3b9df --- /dev/null +++ b/artifacts/eco-cleanup-game/src/components/ui/alert.tsx @@ -0,0 +1,59 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const alertVariants = cva( + "relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7", + { + variants: { + variant: { + default: "bg-background text-foreground", + destructive: + "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +const Alert = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes & VariantProps +>(({ className, variant, ...props }, ref) => ( +
+)) +Alert.displayName = "Alert" + +const AlertTitle = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +AlertTitle.displayName = "AlertTitle" + +const AlertDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +AlertDescription.displayName = "AlertDescription" + +export { Alert, AlertTitle, AlertDescription } diff --git a/artifacts/eco-cleanup-game/src/components/ui/aspect-ratio.tsx b/artifacts/eco-cleanup-game/src/components/ui/aspect-ratio.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c4abbf37f217c715a0eaade7f45ac78600df419f --- /dev/null +++ b/artifacts/eco-cleanup-game/src/components/ui/aspect-ratio.tsx @@ -0,0 +1,5 @@ +import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio" + +const AspectRatio = AspectRatioPrimitive.Root + +export { AspectRatio } diff --git a/artifacts/eco-cleanup-game/src/components/ui/avatar.tsx b/artifacts/eco-cleanup-game/src/components/ui/avatar.tsx new file mode 100644 index 0000000000000000000000000000000000000000..51e507ba9d08bcdbb1fb630498f1cbdf2bf50093 --- /dev/null +++ b/artifacts/eco-cleanup-game/src/components/ui/avatar.tsx @@ -0,0 +1,50 @@ +"use client" + +import * as React from "react" +import * as AvatarPrimitive from "@radix-ui/react-avatar" + +import { cn } from "@/lib/utils" + +const Avatar = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +Avatar.displayName = AvatarPrimitive.Root.displayName + +const AvatarImage = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AvatarImage.displayName = AvatarPrimitive.Image.displayName + +const AvatarFallback = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName + +export { Avatar, AvatarImage, AvatarFallback } diff --git a/artifacts/eco-cleanup-game/src/components/ui/badge.tsx b/artifacts/eco-cleanup-game/src/components/ui/badge.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3f03665878d609428688f5736ab2300297115e5f --- /dev/null +++ b/artifacts/eco-cleanup-game/src/components/ui/badge.tsx @@ -0,0 +1,43 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const badgeVariants = cva( + // @replit + // Whitespace-nowrap: Badges should never wrap. + "whitespace-nowrap inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2" + + " hover-elevate ", + { + variants: { + variant: { + default: + // @replit shadow-xs instead of shadow, no hover because we use hover-elevate + "border-transparent bg-primary text-primary-foreground shadow-xs", + secondary: + // @replit no hover because we use hover-elevate + "border-transparent bg-secondary text-secondary-foreground", + destructive: + // @replit shadow-xs instead of shadow, no hover because we use hover-elevate + "border-transparent bg-destructive text-destructive-foreground shadow-xs", + // @replit shadow-xs" - use badge outline variable + outline: "text-foreground border [border-color:var(--badge-outline)]", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +export interface BadgeProps + extends React.HTMLAttributes, + VariantProps {} + +function Badge({ className, variant, ...props }: BadgeProps) { + return ( +
+ ) +} + +export { Badge, badgeVariants } diff --git a/artifacts/eco-cleanup-game/src/components/ui/breadcrumb.tsx b/artifacts/eco-cleanup-game/src/components/ui/breadcrumb.tsx new file mode 100644 index 0000000000000000000000000000000000000000..60e6c96f72f0350d08b47e4730cab8f3975dc853 --- /dev/null +++ b/artifacts/eco-cleanup-game/src/components/ui/breadcrumb.tsx @@ -0,0 +1,115 @@ +import * as React from "react" +import { Slot } from "@radix-ui/react-slot" +import { ChevronRight, MoreHorizontal } from "lucide-react" + +import { cn } from "@/lib/utils" + +const Breadcrumb = React.forwardRef< + HTMLElement, + React.ComponentPropsWithoutRef<"nav"> & { + separator?: React.ReactNode + } +>(({ ...props }, ref) =>