feat: 实现游戏核心功能与前端界面

- 添加游戏核心系统:战斗、任务、日志、随机数生成等
- 实现前端主界面、HUD、底部导航和各类卡片组件
- 添加用户认证系统与游戏存档持久化
- 配置项目基础架构与开发环境
- 补充文档说明与Docker部署支持
This commit is contained in:
2026-04-28 22:16:58 +08:00
parent 2e1b58bada
commit e783e6e533
124 changed files with 9759 additions and 1 deletions
Binary file not shown.
+36
View File
@@ -0,0 +1,36 @@
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS save_slots (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
slot_key TEXT NOT NULL,
label TEXT NOT NULL,
state_json TEXT NOT NULL,
revision INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE(user_id, slot_key),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_save_slots_user_id ON save_slots(user_id);
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@tinywaste/api",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "tsx watch src/server.ts",
"build": "tsup src/server.ts scripts/migrate.ts --format esm --sourcemap --clean --out-dir dist",
"start": "node dist/src/server.js",
"db:migrate:prod": "node dist/scripts/migrate.js",
"lint": "eslint src scripts --ext .ts",
"test": "vitest run",
"db:migrate": "tsx scripts/migrate.ts"
},
"dependencies": {
"@fastify/cookie": "^11.0.2",
"@fastify/cors": "^11.1.0",
"@fastify/static": "^9.1.3",
"@tinywaste/content": "workspace:*",
"@tinywaste/game-core": "workspace:*",
"bcryptjs": "^3.0.3",
"better-sqlite3": "^12.4.1",
"dotenv": "^17.2.3",
"drizzle-orm": "^0.44.7",
"fastify": "^5.6.1",
"zod": "^4.1.12"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.13"
}
}
+54
View File
@@ -0,0 +1,54 @@
import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import Database from 'better-sqlite3';
import { config as loadDotenv } from 'dotenv';
loadDotenv({
path: [resolve(process.cwd(), '.env'), resolve(process.cwd(), '../../.env')],
});
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
throw new Error('DATABASE_URL is required.');
}
const dbPath = resolve(process.cwd(), databaseUrl);
mkdirSync(dirname(dbPath), { recursive: true });
const db = new Database(dbPath);
db.pragma('foreign_keys = ON');
db.exec(`
CREATE TABLE IF NOT EXISTS _migrations (
name TEXT PRIMARY KEY,
applied_at INTEGER NOT NULL
);
`);
const applied = new Set(
db
.prepare('SELECT name FROM _migrations')
.all()
.map((row) => String((row as { name: string }).name)),
);
const migrationsDir = resolve(process.cwd(), 'migrations');
const files = readdirSync(migrationsDir)
.filter((file) => file.endsWith('.sql'))
.sort();
for (const file of files) {
if (applied.has(file)) continue;
const sql = readFileSync(join(migrationsDir, file), 'utf8');
db.exec('BEGIN');
try {
db.exec(sql);
db.prepare('INSERT INTO _migrations (name, applied_at) VALUES (?, ?)').run(file, Date.now());
db.exec('COMMIT');
console.log(`Applied migration ${file}`);
} catch (error) {
db.exec('ROLLBACK');
throw error;
}
}
db.close();
@@ -0,0 +1,51 @@
import { and, eq, lt, or } from 'drizzle-orm';
import type { db as database } from '../../shared/database/client';
import { saveSlotsTable, sessionsTable, usersTable } from '../../shared/database/schema';
type DbClient = typeof database;
export class AuthRepository {
constructor(private readonly db: DbClient) {}
findUserByIdentifier(identifier: string) {
return this.db.query.usersTable.findFirst({
where: or(eq(usersTable.email, identifier), eq(usersTable.username, identifier)),
});
}
findUserById(userId: string) {
return this.db.query.usersTable.findFirst({
where: eq(usersTable.id, userId),
});
}
createUser(user: typeof usersTable.$inferInsert) {
this.db.insert(usersTable).values(user).run();
return user;
}
createSession(session: typeof sessionsTable.$inferInsert) {
this.db.insert(sessionsTable).values(session).run();
return session;
}
findSessionByTokenHash(tokenHash: string) {
return this.db.query.sessionsTable.findFirst({
where: eq(sessionsTable.tokenHash, tokenHash),
});
}
deleteSessionByTokenHash(tokenHash: string) {
this.db.delete(sessionsTable).where(eq(sessionsTable.tokenHash, tokenHash)).run();
}
deleteExpiredSessions(now: number) {
this.db.delete(sessionsTable).where(lt(sessionsTable.expiresAt, now)).run();
}
getMainSaveSlot(userId: string) {
return this.db.query.saveSlotsTable.findFirst({
where: and(eq(saveSlotsTable.userId, userId), eq(saveSlotsTable.slotKey, 'main')),
});
}
}
+28
View File
@@ -0,0 +1,28 @@
import type { FastifyInstance } from 'fastify';
import { loginSchema, registerSchema } from './auth.schemas';
import { AuthService } from './auth.service';
export const registerAuthRoutes = (app: FastifyInstance, authService: AuthService) => {
app.get('/api/auth/me', async (request) => {
const user = await authService.getUserFromRequest(request);
return { user };
});
app.post('/api/auth/register', async (request, reply) => {
const input = registerSchema.parse(request.body);
const user = await authService.register(input, reply);
return { user };
});
app.post('/api/auth/login', async (request, reply) => {
const input = loginSchema.parse(request.body);
const user = await authService.login(input, reply);
return { user };
});
app.post('/api/auth/logout', async (request, reply) => {
await authService.logout(request, reply);
return { ok: true };
});
};
@@ -0,0 +1,16 @@
import { z } from 'zod';
export const registerSchema = z.object({
email: z.string().email(),
username: z.string().trim().min(3).max(24),
password: z.string().min(8).max(128),
});
export const loginSchema = z.object({
identifier: z.string().trim().min(3),
password: z.string().min(8).max(128),
});
export type RegisterInput = z.infer<typeof registerSchema>;
export type LoginInput = z.infer<typeof loginSchema>;
+132
View File
@@ -0,0 +1,132 @@
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import bcrypt from 'bcryptjs';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { AppError } from '../../shared/errors';
import { env } from '../../shared/env';
import { AuthRepository } from './auth.repository';
import type { LoginInput, RegisterInput } from './auth.schemas';
const SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 14;
export interface AuthUser {
id: string;
email: string;
username: string;
}
const normalizeIdentifier = (value: string) => value.trim().toLowerCase();
const hashSessionToken = (token: string) => createHash('sha256').update(token).digest('hex');
export class AuthService {
constructor(private readonly repository: AuthRepository) {}
private sanitizeUser(user: { id: string; email: string; username: string }): AuthUser {
return {
id: user.id,
email: user.email,
username: user.username,
};
}
private issueSession(reply: FastifyReply, userId: string) {
this.repository.deleteExpiredSessions(Date.now());
const rawToken = randomBytes(32).toString('hex');
const tokenHash = hashSessionToken(rawToken);
const now = Date.now();
const session = {
id: randomUUID(),
userId,
tokenHash,
expiresAt: now + SESSION_TTL_MS,
createdAt: now,
};
this.repository.createSession(session);
reply.setCookie(env.sessionCookieName, rawToken, {
httpOnly: true,
sameSite: 'lax',
path: '/',
maxAge: SESSION_TTL_MS / 1000,
secure: false,
});
}
async register(input: RegisterInput, reply: FastifyReply) {
const email = normalizeIdentifier(input.email);
const username = input.username.trim();
const existing = await this.repository.findUserByIdentifier(email);
if (existing) {
throw new AppError(409, 'AUTH_EXISTS', '该邮箱或用户名已经被使用。');
}
const byUsername = await this.repository.findUserByIdentifier(username);
if (byUsername) {
throw new AppError(409, 'AUTH_EXISTS', '该邮箱或用户名已经被使用。');
}
const user = {
id: randomUUID(),
email,
username,
passwordHash: await bcrypt.hash(input.password, 10),
createdAt: Date.now(),
updatedAt: Date.now(),
};
this.repository.createUser(user);
this.issueSession(reply, user.id);
return this.sanitizeUser(user);
}
async login(input: LoginInput, reply: FastifyReply) {
const identifier = input.identifier.includes('@')
? normalizeIdentifier(input.identifier)
: input.identifier.trim();
const user = await this.repository.findUserByIdentifier(identifier);
if (!user) {
throw new AppError(401, 'AUTH_INVALID', '账号或密码不正确。');
}
const ok = await bcrypt.compare(input.password, user.passwordHash);
if (!ok) {
throw new AppError(401, 'AUTH_INVALID', '账号或密码不正确。');
}
this.issueSession(reply, user.id);
return this.sanitizeUser(user);
}
async getUserFromRequest(request: FastifyRequest) {
const rawToken = request.cookies[env.sessionCookieName];
if (!rawToken) return null;
const session = await this.repository.findSessionByTokenHash(hashSessionToken(rawToken));
if (!session) return null;
if (session.expiresAt < Date.now()) {
this.repository.deleteSessionByTokenHash(session.tokenHash);
return null;
}
const user = await this.repository.findUserById(session.userId);
return user ? this.sanitizeUser(user) : null;
}
async requireUser(request: FastifyRequest) {
const user = await this.getUserFromRequest(request);
if (!user) {
throw new AppError(401, 'AUTH_REQUIRED', '请先登录。');
}
return user;
}
async logout(request: FastifyRequest, reply: FastifyReply) {
const rawToken = request.cookies[env.sessionCookieName];
if (rawToken) {
this.repository.deleteSessionByTokenHash(hashSessionToken(rawToken));
}
reply.clearCookie(env.sessionCookieName, { path: '/' });
}
}
@@ -0,0 +1,48 @@
import { and, eq } from 'drizzle-orm';
import type { db as database } from '../../shared/database/client';
import { saveSlotsTable } from '../../shared/database/schema';
type DbClient = typeof database;
export class GameRepository {
constructor(private readonly db: DbClient) {}
getMainSlot(userId: string) {
return this.db.query.saveSlotsTable.findFirst({
where: and(eq(saveSlotsTable.userId, userId), eq(saveSlotsTable.slotKey, 'main')),
});
}
async upsertMainSlot(userId: string, stateJson: string, label: string) {
const existing = await this.getMainSlot(userId);
const now = Date.now();
if (existing) {
this.db
.update(saveSlotsTable)
.set({
stateJson,
label,
revision: existing.revision + 1,
updatedAt: now,
})
.where(eq(saveSlotsTable.id, existing.id))
.run();
return await this.getMainSlot(userId);
}
const created = {
id: crypto.randomUUID(),
userId,
slotKey: 'main',
label,
stateJson,
revision: 1,
createdAt: now,
updatedAt: now,
};
this.db.insert(saveSlotsTable).values(created).run();
return await this.getMainSlot(userId);
}
}
+27
View File
@@ -0,0 +1,27 @@
import type { FastifyInstance } from 'fastify';
import { AuthService } from '../auth/auth.service';
import { createGameSchema, gameActionSchema } from './game.schemas';
import { GameService } from './game.service';
export const registerGameRoutes = (
app: FastifyInstance,
authService: AuthService,
gameService: GameService,
) => {
app.get('/api/game/state', async (request) => {
const user = await authService.requireUser(request);
return await gameService.getState(user.id);
});
app.post('/api/game/new', async (request) => {
const user = await authService.requireUser(request);
const input = createGameSchema.parse(request.body);
return { view: await gameService.createGame(user.id, input) };
});
app.post('/api/game/action', async (request) => {
const user = await authService.requireUser(request);
const action = gameActionSchema.parse(request.body);
return { view: await gameService.applyAction(user.id, action) };
});
};
@@ -0,0 +1,25 @@
import { z } from 'zod';
export const createGameSchema = z.object({
playerName: z.string().trim().min(2).max(24),
});
export const gameActionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('travel'), toPlaceId: z.string().min(1) }),
z.object({ type: z.literal('perform-action'), actionId: z.string().min(1) }),
z.object({ type: z.literal('select-event-option'), optionId: z.string().min(1) }),
z.object({
type: z.literal('combat'),
move: z.enum(['attack', 'defend', 'advance', 'retreat', 'escape']),
}),
z.object({ type: z.literal('craft'), recipeId: z.string().min(1) }),
z.object({ type: z.literal('use-item'), itemId: z.string().min(1) }),
z.object({ type: z.literal('equip-item'), itemId: z.string().min(1) }),
z.object({ type: z.literal('unequip-item'), slot: z.enum(['weapon', 'body', 'tool']) }),
z.object({ type: z.literal('trade'), offerId: z.string().min(1) }),
z.object({ type: z.literal('rest'), minutes: z.number().int().min(10).max(240) }),
]);
export type CreateGameInput = z.infer<typeof createGameSchema>;
export type GameActionInput = z.infer<typeof gameActionSchema>;
@@ -0,0 +1,49 @@
import {
applyGameAction,
buildGameView,
createNewGameState,
type GameState,
} from '@tinywaste/game-core';
import { gameContent } from '@tinywaste/content';
import { AppError } from '../../shared/errors';
import { GameRepository } from './game.repository';
import type { CreateGameInput, GameActionInput } from './game.schemas';
export class GameService {
constructor(private readonly repository: GameRepository) {}
async getState(userId: string) {
const slot = await this.repository.getMainSlot(userId);
if (!slot) {
return { hasSave: false as const, view: null };
}
const state = JSON.parse(slot.stateJson) as GameState;
return {
hasSave: true as const,
view: buildGameView(state, gameContent),
};
}
async createGame(userId: string, input: CreateGameInput) {
const state = createNewGameState(gameContent, input.playerName.trim());
await this.repository.upsertMainSlot(
userId,
JSON.stringify(state),
`${input.playerName.trim()} 的进度`,
);
return buildGameView(state, gameContent);
}
async applyAction(userId: string, action: GameActionInput) {
const slot = await this.repository.getMainSlot(userId);
if (!slot) {
throw new AppError(404, 'GAME_NOT_FOUND', '还没有创建游戏进度。');
}
const state = JSON.parse(slot.stateJson) as GameState;
const result = applyGameAction(state, gameContent, action);
await this.repository.upsertMainSlot(userId, JSON.stringify(result.state), slot.label);
return buildGameView(result.state, gameContent);
}
}
+120
View File
@@ -0,0 +1,120 @@
import { existsSync } from 'node:fs';
import Fastify from 'fastify';
import cookie from '@fastify/cookie';
import cors from '@fastify/cors';
import fastifyStatic from '@fastify/static';
import { ZodError } from 'zod';
import { db } from './shared/database/client';
import { env } from './shared/env';
import { formatZodError, isAppError } from './shared/errors';
import { AuthRepository } from './features/auth/auth.repository';
import { AuthService } from './features/auth/auth.service';
import { registerAuthRoutes } from './features/auth/auth.routes';
import { GameRepository } from './features/game/game.repository';
import { GameService } from './features/game/game.service';
import { registerGameRoutes } from './features/game/game.routes';
const app = Fastify({ logger: true });
await app.register(cookie, {
secret: env.sessionSecret,
});
await app.register(cors, {
origin: env.webOrigin,
credentials: true,
});
const authRepository = new AuthRepository(db);
const authService = new AuthService(authRepository);
const gameRepository = new GameRepository(db);
const gameService = new GameService(gameRepository);
app.get('/api/health', async () => ({
ok: true,
service: 'tinywaste-api',
}));
registerAuthRoutes(app, authService);
registerGameRoutes(app, authService, gameService);
const webDistAvailable = existsSync(env.webDistPath);
if (webDistAvailable) {
await app.register(fastifyStatic, {
root: env.webDistPath,
prefix: '/',
maxAge: '30d',
immutable: true,
});
app.get('/', async (_request, reply) =>
reply.sendFile('index.html', {
maxAge: 0,
immutable: false,
}),
);
app.setNotFoundHandler((request, reply) => {
const acceptsHtml = request.headers.accept?.includes('text/html');
if (request.method === 'GET' && acceptsHtml && !request.url.startsWith('/api/')) {
return reply.sendFile('index.html', {
maxAge: 0,
immutable: false,
});
}
return reply.status(404).send({
error: {
code: 'NOT_FOUND',
message: '请求的资源不存在。',
},
});
});
}
app.setErrorHandler((error, _request, reply) => {
if (isAppError(error)) {
reply.status(error.statusCode).send({
error: {
code: error.code,
message: error.message,
},
});
return;
}
if (error instanceof ZodError) {
reply.status(400).send({
error: {
code: 'VALIDATION_ERROR',
message: formatZodError(error),
},
});
return;
}
app.log.error(error);
reply.status(500).send({
error: {
code: 'INTERNAL_ERROR',
message: '服务器内部错误,请稍后再试。',
},
});
});
const start = async () => {
try {
await app.listen({ port: env.port, host: '0.0.0.0' });
app.log.info(`API running on http://localhost:${env.port}`);
if (webDistAvailable) {
app.log.info(`Web bundle served from ${env.webDistPath}`);
}
} catch (error) {
app.log.error(error);
process.exit(1);
}
};
await start();
+11
View File
@@ -0,0 +1,11 @@
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { env } from '../env';
import * as schema from './schema';
const sqlite = new Database(env.databasePath);
sqlite.pragma('foreign_keys = ON');
export const db = drizzle(sqlite, { schema });
export { sqlite, schema };
+53
View File
@@ -0,0 +1,53 @@
import { integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core';
export const usersTable = sqliteTable(
'users',
{
id: text('id').primaryKey(),
email: text('email').notNull(),
username: text('username').notNull(),
passwordHash: text('password_hash').notNull(),
createdAt: integer('created_at', { mode: 'number' }).notNull(),
updatedAt: integer('updated_at', { mode: 'number' }).notNull(),
},
(table) => ({
usersEmailUnique: uniqueIndex('users_email_unique').on(table.email),
usersUsernameUnique: uniqueIndex('users_username_unique').on(table.username),
}),
);
export const sessionsTable = sqliteTable(
'sessions',
{
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => usersTable.id, { onDelete: 'cascade' }),
tokenHash: text('token_hash').notNull(),
expiresAt: integer('expires_at', { mode: 'number' }).notNull(),
createdAt: integer('created_at', { mode: 'number' }).notNull(),
},
(table) => ({
sessionsTokenHashUnique: uniqueIndex('sessions_token_hash_unique').on(table.tokenHash),
}),
);
export const saveSlotsTable = sqliteTable(
'save_slots',
{
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => usersTable.id, { onDelete: 'cascade' }),
slotKey: text('slot_key').notNull(),
label: text('label').notNull(),
stateJson: text('state_json').notNull(),
revision: integer('revision', { mode: 'number' }).notNull(),
createdAt: integer('created_at', { mode: 'number' }).notNull(),
updatedAt: integer('updated_at', { mode: 'number' }).notNull(),
},
(table) => ({
saveSlotsUserSlotUnique: uniqueIndex('save_slots_user_slot_unique').on(table.userId, table.slotKey),
}),
);
+35
View File
@@ -0,0 +1,35 @@
import { mkdirSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { config as loadDotenv } from 'dotenv';
import { z } from 'zod';
loadDotenv({
path: [resolve(process.cwd(), '.env'), resolve(process.cwd(), '../../.env')],
});
const envSchema = z.object({
API_PORT: z.coerce.number().int().positive().default(3001),
WEB_ORIGIN: z.string().url().default('http://localhost:5173'),
WEB_DIST_DIR: z.string().min(1).default('../web/dist'),
SESSION_COOKIE_NAME: z.string().min(3).default('tinywaste_session'),
SESSION_SECRET: z.string().min(16),
DATABASE_URL: z.string().min(1).default('./data/tinywaste.db'),
});
const parsed = envSchema.safeParse(process.env);
if (!parsed.success) {
throw new Error(`Invalid environment: ${parsed.error.message}`);
}
const databasePath = resolve(process.cwd(), parsed.data.DATABASE_URL);
const webDistPath = resolve(process.cwd(), parsed.data.WEB_DIST_DIR);
mkdirSync(dirname(databasePath), { recursive: true });
export const env = {
port: parsed.data.API_PORT,
webOrigin: parsed.data.WEB_ORIGIN,
webDistPath,
sessionCookieName: parsed.data.SESSION_COOKIE_NAME,
sessionSecret: parsed.data.SESSION_SECRET,
databasePath,
};
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import { loginSchema, registerSchema } from '../features/auth/auth.schemas';
import { formatZodError } from './errors';
describe('formatZodError', () => {
it('returns a friendly message for short passwords', () => {
const result = loginSchema.safeParse({
identifier: 'tester',
password: '123',
});
expect(result.success).toBe(false);
if (result.success) return;
expect(formatZodError(result.error)).toBe('密码 至少需要 8 个字符。');
});
it('returns a friendly message for invalid email input', () => {
const result = registerSchema.safeParse({
email: 'not-an-email',
username: 'tester',
password: '12345678',
});
expect(result.success).toBe(false);
if (result.success) return;
expect(formatZodError(result.error)).toBe('请输入有效的邮箱地址。');
});
});
+72
View File
@@ -0,0 +1,72 @@
import { ZodError } from 'zod';
export class AppError extends Error {
constructor(
public readonly statusCode: number,
public readonly code: string,
message: string,
) {
super(message);
this.name = 'AppError';
}
}
export const isAppError = (value: unknown): value is AppError => value instanceof AppError;
const FIELD_LABELS: Record<string, string> = {
email: '邮箱',
username: '用户名',
identifier: '邮箱或用户名',
password: '密码',
playerName: '幸存者代号',
actionId: '动作',
toPlaceId: '目标地点',
optionId: '事件选项',
recipeId: '配方',
itemId: '物品',
slot: '装备槽位',
offerId: '交易项',
minutes: '休息时长',
move: '战斗动作',
};
const resolveFieldLabel = (path: Array<string | number | symbol>) => {
if (path.length === 0) return '提交内容';
const key = String(path[path.length - 1]);
return FIELD_LABELS[key] ?? key;
};
export const formatZodError = (error: ZodError) => {
const issue = error.issues[0];
if (!issue) {
return '请求参数不合法。';
}
const fieldLabel = resolveFieldLabel(issue.path);
switch (issue.code) {
case 'invalid_type':
return `${fieldLabel} 类型不正确。`;
case 'too_small':
if (issue.origin === 'string') {
return `${fieldLabel} 至少需要 ${issue.minimum} 个字符。`;
}
return `${fieldLabel} 不能小于 ${issue.minimum}`;
case 'too_big':
if (issue.origin === 'string') {
return `${fieldLabel} 不能超过 ${issue.maximum} 个字符。`;
}
return `${fieldLabel} 不能大于 ${issue.maximum}`;
case 'invalid_format':
if (issue.format === 'email') {
return '请输入有效的邮箱地址。';
}
return `${fieldLabel} 格式不正确。`;
case 'invalid_value':
return `${fieldLabel} 的值不在允许范围内。`;
default:
return issue.message && issue.message !== 'Invalid input'
? `${fieldLabel}${issue.message}`
: `${fieldLabel} 不合法。`;
}
};
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "./src",
"types": ["node"]
},
"include": ["src", "scripts"]
}
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+73
View File
@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+22
View File
@@ -0,0 +1,22 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>scaffold</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+37
View File
@@ -0,0 +1,37 @@
{
"name": "@tinywaste/web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@tanstack/react-query": "^5.90.5",
"@tinywaste/content": "workspace:*",
"@tinywaste/game-core": "workspace:*",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"react-router-dom": "^7.9.6",
"zustand": "^5.0.8"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/node": "^24.12.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^10.2.1",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.5.0",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.2",
"vite": "^8.0.10",
"vitest": "^4.0.7"
}
}
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 444 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 395 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 389 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 373 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+1763
View File
File diff suppressed because it is too large Load Diff
+62
View File
@@ -0,0 +1,62 @@
import './App.css';
import { AuthScreen } from './features/auth/components/AuthScreen';
import { NewGameScreen } from './features/auth/components/NewGameScreen';
import { GameHud } from './features/game/components/GameHud';
import { LoadingScreen } from './features/shared/components/LoadingScreen';
import { useGameSession } from './features/session/useGameSession';
function App() {
const session = useGameSession();
if (session.isCheckingSession) {
return <LoadingScreen label="检查会话中…" />;
}
if (!session.user) {
return (
<AuthScreen
authError={session.authError}
authForm={session.authForm}
authMode={session.authMode}
busy={session.isWorking}
onChange={session.handleAuthChange}
onModeChange={session.handleAuthModeChange}
onSubmit={session.submitAuth}
/>
);
}
if (session.isSyncingGame) {
return <LoadingScreen label="同步云端进度中…" />;
}
if (!session.hasSave || !session.view) {
return (
<NewGameScreen
busy={session.createGameMutation.isPending}
gameError={session.gameError}
playerName={session.newGameName}
user={session.user}
onLogout={session.logout}
onPlayerNameChange={session.setNewGameName}
onStart={() => session.startNewGame()}
/>
);
}
return (
<GameHud
accountName={session.user.username}
gameError={session.gameError}
isRestarting={session.createGameMutation.isPending}
isWorking={session.isWorking}
logoutPending={session.logoutPending}
onLogout={session.logout}
onRestart={session.startNewGame}
onSendAction={session.sendAction}
view={session.view}
/>
);
}
export default App;
+66
View File
@@ -0,0 +1,66 @@
import type { GameAction, GameView } from '@tinywaste/game-core';
export interface AuthUser {
id: string;
email: string;
username: string;
}
interface ApiErrorResponse {
error?: {
code?: string;
message?: string;
};
}
const apiFetch = async <T>(path: string, init?: RequestInit): Promise<T> => {
const response = await fetch(path, {
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...(init?.headers ?? {}),
},
...init,
});
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as ApiErrorResponse | null;
throw new Error(payload?.error?.message ?? 'Request failed.');
}
return (await response.json()) as T;
};
export const getMe = () => apiFetch<{ user: AuthUser | null }>('/api/auth/me');
export const login = (payload: { identifier: string; password: string }) =>
apiFetch<{ user: AuthUser }>('/api/auth/login', {
method: 'POST',
body: JSON.stringify(payload),
});
export const register = (payload: { email: string; username: string; password: string }) =>
apiFetch<{ user: AuthUser }>('/api/auth/register', {
method: 'POST',
body: JSON.stringify(payload),
});
export const logout = () =>
apiFetch<{ ok: true }>('/api/auth/logout', {
method: 'POST',
});
export const getGameState = () =>
apiFetch<{ hasSave: boolean; view: GameView | null }>('/api/game/state');
export const createGame = (payload: { playerName: string }) =>
apiFetch<{ view: GameView }>('/api/game/new', {
method: 'POST',
body: JSON.stringify(payload),
});
export const applyGameAction = (payload: GameAction) =>
apiFetch<{ view: GameView }>('/api/game/action', {
method: 'POST',
body: JSON.stringify(payload),
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

@@ -0,0 +1,87 @@
import type { AuthFormState, AuthMode } from '../../session/useGameSession';
import { getPlaceHeroStyle } from '../../game/uiAssets';
export function AuthScreen({
authMode,
authForm,
authError,
busy,
onChange,
onModeChange,
onSubmit,
}: {
authMode: AuthMode;
authForm: AuthFormState;
authError: string | null;
busy: boolean;
onChange: (patch: Partial<AuthFormState>) => void;
onModeChange: (mode: AuthMode) => void;
onSubmit: () => void;
}) {
return (
<div className="auth-shell">
<section className="auth-hero" style={getPlaceHeroStyle('home')}>
<div className="auth-hero-copy">
<p className="eyebrow">Wasteland Access Node</p>
<h1></h1>
<p>
线沿
</p>
</div>
</section>
<section className="auth-panel">
<div className="tab-row">
<button className={authMode === 'login' ? 'active' : ''} onClick={() => onModeChange('login')}>
</button>
<button
className={authMode === 'register' ? 'active' : ''}
onClick={() => onModeChange('register')}
>
</button>
</div>
{authMode === 'register' ? (
<>
<label>
<input value={authForm.email} onChange={(event) => onChange({ email: event.target.value })} />
</label>
<label>
<input
value={authForm.username}
onChange={(event) => onChange({ username: event.target.value })}
/>
</label>
</>
) : (
<label>
<input
value={authForm.identifier}
onChange={(event) => onChange({ identifier: event.target.value })}
/>
</label>
)}
<label>
<input
type="password"
value={authForm.password}
onChange={(event) => onChange({ password: event.target.value })}
/>
</label>
{authError ? <p className="error-copy">{authError}</p> : null}
<button className="primary-button" onClick={onSubmit} disabled={busy}>
{busy ? '接入中…' : authMode === 'register' ? '注册身份' : '进入终端'}
</button>
</section>
</div>
);
}
@@ -0,0 +1,48 @@
import type { AuthUser } from '../../../api';
import { getPlaceHeroStyle } from '../../game/uiAssets';
export function NewGameScreen({
user,
playerName,
busy,
gameError,
onPlayerNameChange,
onStart,
onLogout,
}: {
user: AuthUser;
playerName: string;
busy: boolean;
gameError: string | null;
onPlayerNameChange: (value: string) => void;
onStart: () => void;
onLogout: () => void;
}) {
return (
<div className="new-game-shell">
<section className="new-game-card" style={getPlaceHeroStyle('vault_gate')}>
<div className="new-game-overlay" />
<div className="new-game-copy">
<p className="eyebrow">Cloud Save Channel Ready</p>
<h1>{user.username}</h1>
<p>
线
</p>
<label>
<input value={playerName} onChange={(event) => onPlayerNameChange(event.target.value)} />
</label>
{gameError ? <p className="error-copy">{gameError}</p> : null}
<div className="new-game-actions">
<button className="primary-button" onClick={onStart} disabled={busy}>
{busy ? '正在建档…' : '建立主存档'}
</button>
<button className="secondary-button" onClick={onLogout}>
</button>
</div>
</div>
</section>
</div>
);
}
@@ -0,0 +1,15 @@
export function AssetThumb({
src,
label,
className = '',
}: {
src?: string;
label: string;
className?: string;
}) {
return (
<figure className={`asset-thumb ${className}`.trim()}>
{src ? <img src={src} alt={label} loading="lazy" /> : <span>{label.slice(0, 2).toUpperCase()}</span>}
</figure>
);
}
@@ -0,0 +1,66 @@
import type { OverlayPanel } from '../types';
import type { GameView } from '@tinywaste/game-core';
import { getActiveQuestCount, getSupplyCounts } from '../hudModel';
export function BottomDock({
activePanel,
onOpenPanel,
view,
}: {
activePanel: OverlayPanel | null;
onOpenPanel: (panel: OverlayPanel) => void;
view: GameView;
}) {
const supplyCounts = getSupplyCounts(view);
const activeQuestCount = getActiveQuestCount(view);
return (
<footer className="command-dock">
<div className="operator-card">
<div className="operator-emblem">{view.player.name.slice(0, 1)}</div>
<div className="operator-copy">
<span>ACTIVE SURVIVOR</span>
<strong>{view.player.name}</strong>
</div>
</div>
<div className="dock-nav-groups">
<div className="dock-tabs">
<button className="dock-tab active">Shelter</button>
<button
className={`dock-tab ${activePanel === 'blueprints' ? 'active' : ''}`}
onClick={() => onOpenPanel('blueprints')}
>
Crafting
</button>
<button
className={`dock-tab ${activePanel === 'logs' ? 'active' : ''}`}
onClick={() => onOpenPanel('logs')}
>
Logs
</button>
<button
className={`dock-tab ${activePanel === 'inventory' ? 'active' : ''}`}
onClick={() => onOpenPanel('inventory')}
>
Inventory
</button>
<button
className={`dock-tab ${activePanel === 'missions' ? 'active' : ''}`}
onClick={() => onOpenPanel('missions')}
>
Missions
</button>
</div>
<div className="dock-metrics">
<span> {supplyCounts.water}</span>
<span> {supplyCounts.food}</span>
<span> {supplyCounts.medicine}</span>
<span> {supplyCounts.material}</span>
<span> {activeQuestCount}</span>
</div>
</div>
</footer>
);
}
@@ -0,0 +1,197 @@
import type { GameAction, GameView } from '@tinywaste/game-core';
import { getObjectiveRows } from '../hudModel';
import { getPlaceHeroStyle } from '../uiAssets';
import type { OverlayPanel } from '../types';
import { EmptyState } from './EmptyState';
import { PanelHeader } from '../../shared/components/PanelHeader';
function ObjectivePanel({ view }: { view: GameView }) {
const objectives = getObjectiveRows(view);
return (
<section className="subpanel objective-panel">
<PanelHeader title="Current Objectives" subtitle="主线与支线推进聚合显示" compact />
<div className="objective-list">
{objectives.length ? (
objectives.map((objective) => (
<article key={objective.id} className={`objective-card ${objective.done ? 'done' : ''}`}>
<div>
<strong>{objective.title}</strong>
<p>{objective.detail}</p>
</div>
<span>{objective.progress}</span>
</article>
))
) : (
<EmptyState text="当前没有活动目标,继续探索可以解锁新线索。" />
)}
</div>
</section>
);
}
function LogPanel({ view }: { view: GameView }) {
return (
<section className="subpanel log-panel">
<PanelHeader title="Live Log" subtitle="只滚动日志层,不推动页面滚动" compact />
<div className="log-list">
{view.logs.map((entry) => (
<article key={entry.id} className={`log-entry tone-${entry.tone}`}>
<span>{entry.minute}m</span>
<p>{entry.message}</p>
</article>
))}
</div>
</section>
);
}
export function CommandCenter({
gameError,
isWorking,
onOpenPanel,
onSendAction,
view,
}: {
gameError: string | null;
isWorking: boolean;
onOpenPanel: (panel: OverlayPanel) => void;
onSendAction: (action: GameAction) => void;
view: GameView;
}) {
const utilityCards = [
{
id: 'utility-rest',
name: '短休 30m',
kind: 'system',
desc: '不离开当前扇区,快速回收一段精力窗口。',
meta: ['30 分钟', '恢复向', '低风险'],
onClick: () => onSendAction({ type: 'rest', minutes: 30 }),
},
{
id: 'utility-blueprints',
name: '打开蓝图栈',
kind: 'system',
desc: '在独立系统面板中检查配方、缺口与制作链。',
meta: ['模式切换', '制作', '即时'],
onClick: () => onOpenPanel('blueprints'),
},
{
id: 'utility-logs',
name: '复盘日志',
kind: 'system',
desc: '在独立日志面板中回放最近行动、事件与消耗。',
meta: ['模式切换', '日志', '回放'],
onClick: () => onOpenPanel('logs'),
},
];
return (
<section className="panel panel-command">
<div className="viewport-stage" style={getPlaceHeroStyle(view.place.id)}>
<div className="viewport-copy">
<p className="eyebrow">Live Visual Feed</p>
<h2>{view.header.placeName}</h2>
<p>{view.header.placeDesc}</p>
</div>
<div className="viewport-flags">
<span>{view.pendingEvent ? '事件待处理' : '无待定事件'}</span>
<span>{view.combat ? `战斗回合 ${view.combat.round}` : `行动 ${view.place.actions.length}`}</span>
<span>{view.place.tradeOffers.length ? `可交易 ${view.place.tradeOffers.length}` : '无交易站'}</span>
</div>
</div>
{gameError ? <p className="error-copy command-error">{gameError}</p> : null}
<div className="command-surface">
<div className="command-tabs command-tabs-static">
<button className="active">Actions</button>
<button onClick={() => onOpenPanel('logs')}>Logs</button>
<button onClick={() => onOpenPanel('blueprints')}>Blueprints</button>
</div>
<div className="command-stage">
<section className="subpanel stage-main">
<PanelHeader title="Action Matrix" subtitle="服务端即时结算扇区行为" compact />
<div className="action-grid">
{view.place.actions.map((action) => (
<button
key={action.id}
className="action-card"
disabled={Boolean(action.disabledReason) || isWorking}
onClick={() => onSendAction({ type: 'perform-action', actionId: action.id })}
>
<div className="action-card-top">
<strong>{action.name}</strong>
<span className="action-kind">{action.kind}</span>
</div>
<p>{action.desc}</p>
<div className="action-card-meta">
<span>{action.timeCostMin} </span>
<span> -{action.energyCost}</span>
<span> {Math.round(action.risk * 100)}%</span>
</div>
{action.remainingStock !== null && action.remainingStock !== undefined ? (
<small>{action.remainingStock}</small>
) : null}
{action.disabledReason ? <em>{action.disabledReason}</em> : <small>{action.rewardHint}</small>}
</button>
))}
{utilityCards.map((card) => (
<button key={card.id} className="action-card utility" disabled={isWorking} onClick={card.onClick}>
<div className="action-card-top">
<strong>{card.name}</strong>
<span className="action-kind">{card.kind}</span>
</div>
<p>{card.desc}</p>
<div className="action-card-meta">
{card.meta.map((entry) => (
<span key={entry}>{entry}</span>
))}
</div>
<small></small>
</button>
))}
</div>
<div className="trade-block">
<PanelHeader title="Trade Terminal" subtitle="当前地点的即时物资交换" compact />
{view.place.tradeOffers.length ? (
<div className="trade-list compact">
{view.place.tradeOffers.map((offer) => (
<button
key={offer.id}
className="trade-card"
disabled={!offer.available || isWorking}
onClick={() => onSendAction({ type: 'trade', offerId: offer.id })}
>
<strong>{offer.name}</strong>
<p>{offer.desc}</p>
<small>
{offer.costs
.map((entry) => `${entry.name} x${entry.count} (持有 ${entry.owned})`)
.join(' · ')}
</small>
<small>
{offer.gives.map((entry) => `${entry.name} x${entry.count}`).join(' · ')}
</small>
{offer.disabledReason ? <em>{offer.disabledReason}</em> : null}
</button>
))}
</div>
) : (
<EmptyState text="当前扇区没有交易站点。" />
)}
</div>
</section>
<div className="command-side-column">
<ObjectivePanel view={view} />
<LogPanel view={view} />
</div>
</div>
</div>
</section>
);
}
@@ -0,0 +1,3 @@
export function EmptyState({ text }: { text: string }) {
return <div className="empty-state">{text}</div>;
}
@@ -0,0 +1,141 @@
import { useState } from 'react';
import type { GameAction, GameView } from '@tinywaste/game-core';
import { BottomDock } from './BottomDock';
import { CommandCenter } from './CommandCenter';
import { LoadoutPanel } from './LoadoutPanel';
import { RoutePanel } from './RoutePanel';
import { TopHud } from './TopHud';
import { SystemOverlay } from './SystemOverlay';
import { ModalShell } from '../../shared/components/ModalShell';
import type { OverlayPanel } from '../types';
export function GameHud({
accountName,
gameError,
isRestarting,
isWorking,
logoutPending,
onLogout,
onRestart,
onSendAction,
view,
}: {
accountName: string;
gameError: string | null;
isRestarting: boolean;
isWorking: boolean;
logoutPending: boolean;
onLogout: () => void;
onRestart: (playerName?: string) => void;
onSendAction: (action: GameAction) => void;
view: GameView;
}) {
const [activePanel, setActivePanel] = useState<OverlayPanel | null>(null);
return (
<div className="app-shell">
<TopHud accountName={accountName} logoutPending={logoutPending} onLogout={onLogout} view={view} />
<main className="game-grid">
<RoutePanel isWorking={isWorking} onSendAction={onSendAction} view={view} />
<CommandCenter
gameError={gameError}
isWorking={isWorking}
onOpenPanel={setActivePanel}
onSendAction={onSendAction}
view={view}
/>
<LoadoutPanel isWorking={isWorking} onOpenPanel={setActivePanel} onSendAction={onSendAction} view={view} />
</main>
<BottomDock activePanel={activePanel} onOpenPanel={setActivePanel} view={view} />
<SystemOverlay
isWorking={isWorking}
onClose={() => setActivePanel(null)}
onSendAction={onSendAction}
panel={activePanel}
view={view}
/>
{view.pendingEvent ? (
<ModalShell title={view.pendingEvent.title} subtitle="事件抉择">
<p className="modal-copy">{view.pendingEvent.text}</p>
<div className="modal-option-list">
{view.pendingEvent.options.map((option) => (
<button
key={option.id}
className="modal-option"
disabled={Boolean(option.disabledReason) || isWorking}
onClick={() => onSendAction({ type: 'select-event-option', optionId: option.id })}
>
<strong>{option.text}</strong>
{option.disabledReason ? <span>{option.disabledReason}</span> : null}
</button>
))}
</div>
</ModalShell>
) : null}
{view.combat ? (
<ModalShell
title={`遭遇 ${view.combat.enemyName}`}
subtitle={`回合 ${view.combat.round} · 距离 ${view.combat.distance}`}
>
<div className="combat-shell">
<div className="combat-health">
<span></span>
<strong>
{view.combat.enemyLife}/{view.combat.enemyMaxLife}
</strong>
</div>
<div className="combat-log">
{view.combat.log.map((line, index) => (
<p key={`${line.round}-${index}`}>
R{line.round} · {line.message}
</p>
))}
</div>
<div className="combat-actions">
{view.combat.availableMoves.map((entry) => (
<button
key={entry.label}
className="combat-button"
disabled={isWorking}
onClick={() =>
onSendAction({
type: 'combat',
move: entry.move as 'attack' | 'defend' | 'advance' | 'retreat' | 'escape',
})
}
>
{entry.label}
</button>
))}
</div>
</div>
</ModalShell>
) : null}
{view.gameOver || view.victory ? (
<ModalShell
title={view.victory ? '避难所大门开始转动' : '这次没能撑过去'}
subtitle={view.victory ? 'MVP 进度已打通' : view.deathReason ?? '失败'}
>
<p className="modal-copy">
{view.victory
? '你已经完成了当前在线版本的主线闭环,接下来可以继续扩内容,也可以直接重开试另一条路线。'
: '这个存档已经进入失败状态,你可以直接重开一个新的幸存者。'}
</p>
<button
className="primary-button"
disabled={isRestarting}
onClick={() => onRestart(`${view.player.name} II`)}
>
</button>
</ModalShell>
) : null}
</div>
);
}
@@ -0,0 +1,158 @@
import type { GameAction, GameView } from '@tinywaste/game-core';
import { useMemo } from 'react';
import { CHARACTER_PREVIEW_ART, getItemArt } from '../uiAssets';
import { getAttributeRows, getLoadoutEntries, getStatusEffects, getVisibleInventory } from '../hudModel';
import type { OverlayPanel } from '../types';
import { AssetThumb } from './AssetThumb';
import { PanelHeader } from '../../shared/components/PanelHeader';
export function LoadoutPanel({
isWorking,
onOpenPanel,
onSendAction,
view,
}: {
isWorking: boolean;
onOpenPanel: (panel: OverlayPanel) => void;
onSendAction: (action: GameAction) => void;
view: GameView;
}) {
const loadoutEntries = useMemo(() => getLoadoutEntries(view), [view]);
const attributeRows = useMemo(() => getAttributeRows(view), [view]);
const statusEffects = useMemo(() => getStatusEffects(view), [view]);
const quickSlots = useMemo(() => getVisibleInventory(view), [view]);
return (
<section className="panel panel-loadout">
<div className="panel-tabs">
<button className="active">Character</button>
<button onClick={() => onOpenPanel('inventory')}>Inventory</button>
<button onClick={() => onOpenPanel('missions')}>Missions</button>
</div>
<div className="loadout-scroll">
<PanelHeader
title="Character Matrix"
subtitle={`${view.player.name} · 容量 ${view.player.inventoryUsage}/${view.player.inventoryCapacity}`}
/>
<div className="loadout-matrix">
<div className="slot-column">
{loadoutEntries.left.map((entry) => (
<article key={entry.id} className={`loadout-slot ${entry.isEquipped ? 'equipped' : ''}`}>
<AssetThumb src={entry.art} label={entry.title} className="slot-thumb" />
<div className="slot-copy">
<span>{entry.label}</span>
<strong>{entry.title}</strong>
<small>{entry.subtitle}</small>
</div>
</article>
))}
</div>
<div className="character-figure">
<img src={CHARACTER_PREVIEW_ART} alt="幸存者角色立绘" />
<div className="character-figure-overlay">
<span>ACTIVE SURVIVOR</span>
<strong>{view.player.name}</strong>
</div>
</div>
<div className="slot-column">
{loadoutEntries.right.map((entry) => (
<article key={entry.id} className={`loadout-slot ${entry.isEquipped ? 'equipped' : ''}`}>
<AssetThumb src={entry.art} label={entry.title} className="slot-thumb" />
<div className="slot-copy">
<span>{entry.label}</span>
<strong>{entry.title}</strong>
<small>{entry.subtitle}</small>
</div>
</article>
))}
</div>
</div>
<div className="character-meta-grid">
<section className="subpanel attribute-panel">
<PanelHeader title="Attributes" subtitle="当前成长属性直接来自在线存档" compact />
<div className="attribute-grid">
{attributeRows.map((entry) => (
<article key={entry.label} className="attribute-card">
<span>{entry.label}</span>
<strong>{entry.value}</strong>
<small>{entry.name}</small>
</article>
))}
</div>
</section>
<section className="subpanel effects-panel">
<PanelHeader title="Status Effects" subtitle="从生存状态阈值导出的风险反馈" compact />
<div className="effects-grid">
{statusEffects.map((effect) => (
<article key={effect.id} className={`effect-card tone-${effect.tone}`}>
<strong>{effect.label}</strong>
<p>{effect.detail}</p>
</article>
))}
</div>
</section>
</div>
<section className="subpanel quick-slot-panel">
<PanelHeader title="Quick Slots" subtitle="高频补给和工具直接图像化呈现" compact />
<div className="quick-slot-grid">
{quickSlots.map((item) => (
<article key={`quick-${item.itemId}`} className="quick-slot">
<AssetThumb src={getItemArt(item.itemId, item.type)} label={item.name} />
<div className="quick-slot-copy">
<strong>{item.name}</strong>
<span>x{item.count}</span>
</div>
</article>
))}
{Array.from({ length: Math.max(0, 8 - quickSlots.length) }).map((_, index) => (
<article key={`locked-${index}`} className="quick-slot locked">
<div className="quick-slot-lock">LOCK</div>
</article>
))}
</div>
</section>
<section className="subpanel right-utility-panel">
<PanelHeader title="Field Panels" subtitle="中频系统改为游戏面板弹出" compact />
<div className="panel-link-grid">
<button className="secondary-button panel-link-button" onClick={() => onOpenPanel('inventory')}>
</button>
<button className="secondary-button panel-link-button" onClick={() => onOpenPanel('missions')}>
</button>
<button className="secondary-button panel-link-button" onClick={() => onOpenPanel('blueprints')}>
</button>
<button className="secondary-button panel-link-button" onClick={() => onOpenPanel('logs')}>
</button>
</div>
</section>
<section className="subpanel rest-panel">
<PanelHeader title="Recovery Actions" subtitle="原地休整仍保留在主 HUD 中" compact />
<div className="rest-actions">
{[30, 60, 120].map((minutes) => (
<button
key={minutes}
className="rest-button"
disabled={isWorking}
onClick={() => onSendAction({ type: 'rest', minutes })}
>
{minutes}
</button>
))}
</div>
</section>
</div>
</section>
);
}
@@ -0,0 +1,101 @@
import type { GameAction, GameView } from '@tinywaste/game-core';
import { edgeDestination, getActiveQuestCount, getCurrentPlace, getRiskDots, getRouteRiskTier } from '../hudModel';
import { getPlaceThumbStyle } from '../uiAssets';
import { PanelHeader } from '../../shared/components/PanelHeader';
export function RoutePanel({
isWorking,
onSendAction,
view,
}: {
isWorking: boolean;
onSendAction: (action: GameAction) => void;
view: GameView;
}) {
const currentPlace = getCurrentPlace(view);
const activeQuestCount = getActiveQuestCount(view);
return (
<section className="panel panel-route">
<PanelHeader title="Current Location" subtitle="路线、风险、耗时全部固定在当前视口内" />
<article className="route-summary-card">
<span className="intel-kicker">CURRENT SECTOR</span>
<h2>{currentPlace?.name ?? view.header.placeName}</h2>
<p>{view.header.placeDesc}</p>
<div className="route-summary-meta">
<div>
<small></small>
<strong>{view.header.riskLabel}</strong>
</div>
<div>
<small></small>
<strong>{view.place.services.length || 1} </strong>
</div>
<div>
<small></small>
<strong>{activeQuestCount}</strong>
</div>
</div>
<div className="intel-meta">
{(currentPlace?.tags ?? []).map((tag) => (
<span key={tag} className="hud-chip muted">
{tag}
</span>
))}
</div>
</article>
<div className="route-list">
{view.map.edges.map((edge) => {
const destination = edgeDestination(view, edge);
if (!destination) return null;
const riskTier = getRouteRiskTier(edge.risk);
const riskDots = getRiskDots(edge.risk);
return (
<button
key={`${edge.from}-${edge.to}`}
className={`route-card tone-${riskTier.tone}`}
disabled={Boolean(edge.blockedReason) || isWorking}
onClick={() => onSendAction({ type: 'travel', toPlaceId: edge.to })}
>
<div className="route-card-thumb" style={getPlaceThumbStyle(destination.id)} />
<div className="route-card-copy">
<strong>{destination.name}</strong>
<p>{destination.desc}</p>
<div className="route-card-detail">
<span>{edge.travelTimeMin} </span>
<span>{riskTier.label}</span>
</div>
<div className="risk-dots" aria-hidden="true">
{riskDots.map((active, index) => (
<span key={`${destination.id}-${index}`} className={active ? 'active' : ''} />
))}
</div>
</div>
<div className="route-card-state">
<span>{destination.visited ? '已探明' : '未知'}</span>
{edge.blockedReason ? <em>{edge.blockedReason}</em> : null}
</div>
</button>
);
})}
</div>
<section className="world-map-panel">
<PanelHeader title="World Map" subtitle="节点式世界图用于压缩表达地理推进" compact />
<div className="map-node-grid">
{view.map.places.map((place) => (
<article key={place.id} className={`map-node-card ${place.current ? 'current' : ''}`}>
<strong>{place.name}</strong>
<span>{place.visited ? '已探明' : '待深入'}</span>
<small>{place.tags.join(' · ') || 'unknown'}</small>
</article>
))}
</div>
</section>
</section>
);
}
@@ -0,0 +1,28 @@
export function StatMeter({
label,
value,
maxValue,
tone,
}: {
label: string;
value: number;
maxValue: number;
tone: 'health' | 'neutral' | 'danger';
}) {
const percentage = Math.max(0, Math.min(100, (value / maxValue) * 100));
return (
<article className={`stat-meter tone-${tone}`}>
<div>
<span>{label}</span>
<strong>
{Math.round(value)}
<small>/{Math.round(maxValue)}</small>
</strong>
</div>
<div className="meter-track">
<div className="meter-fill" style={{ width: `${percentage}%` }} />
</div>
</article>
);
}
@@ -0,0 +1,286 @@
import type { GameAction, GameView } from '@tinywaste/game-core';
import { getActiveQuestCount, getLoadoutEntries, getSupplyCounts } from '../hudModel';
import type { OverlayPanel } from '../types';
import { ModalShell } from '../../shared/components/ModalShell';
import { PanelHeader } from '../../shared/components/PanelHeader';
import { InventoryCard } from './cards/InventoryCard';
import { QuestCard } from './cards/QuestCard';
import { RecipeCard } from './cards/RecipeCard';
import { EmptyState } from './EmptyState';
function OverlayHeaderStats({ view }: { view: GameView }) {
const supplyCounts = getSupplyCounts(view);
const activeQuestCount = getActiveQuestCount(view);
return (
<div className="overlay-summary-grid">
<article className="overlay-summary-card">
<span></span>
<strong>
{view.player.inventoryUsage}/{view.player.inventoryCapacity}
</strong>
</article>
<article className="overlay-summary-card">
<span></span>
<strong>{supplyCounts.water}</strong>
</article>
<article className="overlay-summary-card">
<span></span>
<strong>{supplyCounts.food}</strong>
</article>
<article className="overlay-summary-card">
<span></span>
<strong>{supplyCounts.medicine}</strong>
</article>
<article className="overlay-summary-card">
<span></span>
<strong>{activeQuestCount}</strong>
</article>
</div>
);
}
function InventoryOverlay({
isWorking,
onSendAction,
view,
}: {
isWorking: boolean;
onSendAction: (action: GameAction) => void;
view: GameView;
}) {
const loadoutEntries = getLoadoutEntries(view);
return (
<div className="system-overlay">
<OverlayHeaderStats view={view} />
<div className="system-overlay-grid inventory-overlay-grid">
<section className="subpanel overlay-main-panel">
<PanelHeader title="Inventory Ledger" subtitle="完整物资、装备与使用入口" compact />
<div className="inventory-list overlay-list">
{view.player.inventory.map((item) => (
<InventoryCard
key={item.itemId}
busy={isWorking}
item={item}
onEquip={() => onSendAction({ type: 'equip-item', itemId: item.itemId })}
onUnequip={() => onSendAction({ type: 'unequip-item', slot: item.equipSlot! })}
onUse={() => onSendAction({ type: 'use-item', itemId: item.itemId })}
/>
))}
</div>
</section>
<div className="overlay-side-stack">
<section className="subpanel overlay-side-panel">
<PanelHeader title="Loadout Snapshot" subtitle="当前装备位快照" compact />
<div className="overlay-loadout-stack">
{[...loadoutEntries.left, ...loadoutEntries.right].map((entry) => (
<article key={entry.id} className={`overlay-loadout-row ${entry.isEquipped ? 'equipped' : ''}`}>
<div>
<span>{entry.label}</span>
<strong>{entry.title}</strong>
</div>
<small>{entry.subtitle}</small>
</article>
))}
</div>
</section>
<section className="subpanel overlay-side-panel">
<PanelHeader title="Bag Rules" subtitle="背包系统当前规则摘要" compact />
<div className="overlay-note-stack">
<article className="overlay-note-card">
<strong></strong>
<p></p>
</article>
<article className="overlay-note-card">
<strong>使</strong>
<p></p>
</article>
</div>
</section>
</div>
</div>
</div>
);
}
function MissionOverlay({ isWorking, onSendAction, view }: { isWorking: boolean; onSendAction: (action: GameAction) => void; view: GameView }) {
return (
<div className="system-overlay">
<OverlayHeaderStats view={view} />
<div className="system-overlay-grid mission-overlay-grid">
<section className="subpanel overlay-main-panel">
<PanelHeader title="Mission Threads" subtitle="主线、支线和当前推进步骤" compact />
<div className="quest-list overlay-list">
{view.quests.length ? (
view.quests.map((quest) => <QuestCard key={quest.id} quest={quest} />)
) : (
<EmptyState text="当前没有任务线,继续探索可以触发新的委托。" />
)}
</div>
</section>
<div className="overlay-side-stack">
<section className="subpanel overlay-side-panel">
<PanelHeader title="Recovery Actions" subtitle="以游戏面板方式触发休整" compact />
<div className="rest-actions">
{[30, 60, 120].map((minutes) => (
<button
key={minutes}
className="rest-button"
disabled={isWorking}
onClick={() => onSendAction({ type: 'rest', minutes })}
>
{minutes}
</button>
))}
</div>
</section>
<section className="subpanel overlay-side-panel">
<PanelHeader title="Mission Logic" subtitle="任务系统设计摘要" compact />
<div className="overlay-note-stack">
<article className="overlay-note-card">
<strong></strong>
<p> lockedactivecompleted</p>
</article>
<article className="overlay-note-card">
<strong></strong>
<p></p>
</article>
</div>
</section>
</div>
</div>
</div>
);
}
function BlueprintOverlay({
isWorking,
onSendAction,
view,
}: {
isWorking: boolean;
onSendAction: (action: GameAction) => void;
view: GameView;
}) {
const craftableCount = view.recipes.filter((recipe) => recipe.craftable).length;
return (
<div className="system-overlay">
<OverlayHeaderStats view={view} />
<div className="system-overlay-grid blueprint-overlay-grid">
<section className="subpanel overlay-main-panel">
<PanelHeader title="Blueprint Stack" subtitle="制作配方、缺口与执行入口" compact />
<div className="recipe-list overlay-list">
{view.recipes.map((recipe) => (
<RecipeCard
key={recipe.id}
busy={isWorking}
onCraft={() => onSendAction({ type: 'craft', recipeId: recipe.id })}
recipe={recipe}
/>
))}
</div>
</section>
<div className="overlay-side-stack">
<section className="subpanel overlay-side-panel">
<PanelHeader title="Crafting State" subtitle="当前蓝图执行态" compact />
<div className="overlay-note-stack">
<article className="overlay-note-card">
<strong></strong>
<p> {craftableCount} </p>
</article>
<article className="overlay-note-card">
<strong></strong>
<p> HUD </p>
</article>
</div>
</section>
</div>
</div>
</div>
);
}
function LogOverlay({ view }: { view: GameView }) {
return (
<div className="system-overlay">
<OverlayHeaderStats view={view} />
<div className="system-overlay-grid log-overlay-grid">
<section className="subpanel overlay-main-panel">
<PanelHeader title="Sector Logs" subtitle="完整行动、事件、战斗与资源变化回放" compact />
<div className="log-list expanded overlay-list">
{view.logs.map((entry) => (
<article key={entry.id} className={`log-entry tone-${entry.tone}`}>
<span>{entry.minute}m</span>
<p>{entry.message}</p>
</article>
))}
</div>
</section>
<div className="overlay-side-stack">
<section className="subpanel overlay-side-panel">
<PanelHeader title="Log Policy" subtitle="日志系统设计摘要" compact />
<div className="overlay-note-stack">
<article className="overlay-note-card">
<strong></strong>
<p> HUD </p>
</article>
<article className="overlay-note-card">
<strong></strong>
<p></p>
</article>
</div>
</section>
</div>
</div>
</div>
);
}
export function SystemOverlay({
isWorking,
onClose,
onSendAction,
panel,
view,
}: {
isWorking: boolean;
onClose: () => void;
onSendAction: (action: GameAction) => void;
panel: OverlayPanel | null;
view: GameView;
}) {
if (!panel) return null;
const metaByPanel: Record<OverlayPanel, { title: string; subtitle: string }> = {
inventory: { title: '背包系统', subtitle: 'Inventory Overlay' },
missions: { title: '任务系统', subtitle: 'Mission Overlay' },
blueprints: { title: '制作与蓝图系统', subtitle: 'Blueprint Overlay' },
logs: { title: '日志系统', subtitle: 'Log Overlay' },
};
return (
<ModalShell
title={metaByPanel[panel].title}
subtitle={metaByPanel[panel].subtitle}
size="wide"
onClose={onClose}
>
{panel === 'inventory' ? <InventoryOverlay isWorking={isWorking} onSendAction={onSendAction} view={view} /> : null}
{panel === 'missions' ? <MissionOverlay isWorking={isWorking} onSendAction={onSendAction} view={view} /> : null}
{panel === 'blueprints' ? <BlueprintOverlay isWorking={isWorking} onSendAction={onSendAction} view={view} /> : null}
{panel === 'logs' ? <LogOverlay view={view} /> : null}
</ModalShell>
);
}
@@ -0,0 +1,59 @@
import type { GameView } from '@tinywaste/game-core';
import { getAlertCount, getTimeLabels } from '../hudModel';
import { STAT_LABELS, STAT_ORDER } from '../uiAssets';
import { StatMeter } from './StatMeter';
export function TopHud({
accountName,
logoutPending,
onLogout,
view,
}: {
accountName: string;
logoutPending: boolean;
onLogout: () => void;
view: GameView;
}) {
const { dayLabel, clockLabel } = getTimeLabels(view.header.timeLabel);
const alertCount = getAlertCount(view);
return (
<header className="top-hud">
<div className="brand-block">
<div className="brand-mark">TW</div>
<div className="brand-copy">
<p className="eyebrow">Persistent Wasteland Interface</p>
<strong>TinyWaste Online</strong>
</div>
</div>
<div className="clock-block">
<span>{dayLabel}</span>
<strong>{clockLabel}</strong>
</div>
<section className="status-strip">
{STAT_ORDER.map((statKey) => (
<StatMeter
key={statKey}
label={STAT_LABELS[statKey] ?? statKey}
maxValue={view.player.maxStats[statKey]}
tone={statKey === 'radiation' ? 'danger' : statKey === 'life' ? 'health' : 'neutral'}
value={view.player.stats[statKey]}
/>
))}
</section>
<div className="top-actions">
<span className="hud-chip safe">{view.header.riskLabel}</span>
<span className="hud-chip"> {accountName}</span>
<span className={`hud-chip ${alertCount ? 'accent' : ''}`}>
{alertCount ? `警报 ${alertCount}` : '链路稳定'}
</span>
<button className="secondary-button" onClick={onLogout} disabled={logoutPending}>
退
</button>
</div>
</header>
);
}
@@ -0,0 +1,52 @@
import type { InventoryViewEntry } from '@tinywaste/game-core';
import { getInventoryStateLabel } from '../../hudModel';
import { getItemArt } from '../../uiAssets';
import { AssetThumb } from '../AssetThumb';
export function InventoryCard({
item,
busy,
onUse,
onEquip,
onUnequip,
}: {
item: InventoryViewEntry;
busy: boolean;
onUse: () => void;
onEquip: () => void;
onUnequip: () => void;
}) {
const art = getItemArt(item.itemId, item.type);
return (
<article className={`inventory-card ${item.equipped ? 'equipped' : ''}`}>
<AssetThumb src={art} label={item.name} />
<div className="inventory-copy">
<div className="inventory-title-row">
<strong>{item.name}</strong>
<span>x{item.count}</span>
</div>
<p>{item.desc}</p>
<small>
{item.type} · {item.volume} · {getInventoryStateLabel(item)}
</small>
</div>
<div className="inventory-actions">
{item.canUse ? (
<button className="small-button" onClick={onUse} disabled={busy}>
使
</button>
) : null}
{item.equipSlot ? (
<button
className="small-button secondary"
onClick={item.equipped ? onUnequip : onEquip}
disabled={busy}
>
{item.equipped ? '卸下' : '装备'}
</button>
) : null}
</div>
</article>
);
}
@@ -0,0 +1,23 @@
import type { QuestView } from '@tinywaste/game-core';
import { getQuestProgress } from '../../hudModel';
export function QuestCard({ quest }: { quest: QuestView }) {
return (
<article className={`quest-card state-${quest.state}`}>
<header>
<div>
<strong>{quest.title}</strong>
<small>{quest.desc}</small>
</div>
<span>{getQuestProgress(quest)}</span>
</header>
<div className="quest-steps">
{quest.steps.map((step) => (
<span key={step.text} className={step.done ? 'done' : ''}>
{step.done ? '✓' : '○'} {step.text}
</span>
))}
</div>
</article>
);
}
@@ -0,0 +1,37 @@
import type { RecipeView } from '@tinywaste/game-core';
import { getItemArt } from '../../uiAssets';
import { AssetThumb } from '../AssetThumb';
export function RecipeCard({
recipe,
busy,
onCraft,
}: {
recipe: RecipeView;
busy: boolean;
onCraft: () => void;
}) {
const primaryOutput = recipe.outputs[0];
return (
<article className={`recipe-card ${recipe.craftable ? 'craftable' : ''}`}>
<AssetThumb src={getItemArt(primaryOutput?.itemId)} label={recipe.name} />
<div className="recipe-copy">
<strong>{recipe.name}</strong>
<p>{recipe.desc}</p>
<small>
{recipe.timeCostMin} · -{recipe.energyCost}
</small>
<small>
{recipe.inputs.map((input) => `${input.name} ${input.owned}/${input.count}`).join(' · ')}
</small>
</div>
<div className="recipe-actions">
<button className="small-button" onClick={onCraft} disabled={!recipe.craftable || busy}>
</button>
{recipe.disabledReason ? <em>{recipe.disabledReason}</em> : null}
</div>
</article>
);
}
+206
View File
@@ -0,0 +1,206 @@
import type { EdgeView, GameView, InventoryViewEntry, QuestView } from '@tinywaste/game-core';
import { getEquipmentArt, getItemArt } from './uiAssets';
export interface EquipmentPreviewEntry {
id: string;
label: string;
title: string;
subtitle: string;
art?: string;
isEquipped: boolean;
}
export function edgeDestination(view: GameView, edge: EdgeView) {
return view.map.places.find((place) => place.id === edge.to);
}
export function getTimeLabels(timeLabel: string) {
const timeSegments = timeLabel.split('·').map((part) => part.trim());
return {
dayLabel: timeSegments[0] ?? 'Day 1',
clockLabel: timeSegments[1] ?? timeLabel,
};
}
export function getActiveQuestCount(view: GameView) {
return view.quests.filter((quest) => quest.state === 'active').length;
}
export function getAlertCount(view: GameView) {
return Number(Boolean(view.pendingEvent)) + Number(Boolean(view.combat));
}
export function getCurrentPlace(view: GameView) {
return view.map.places.find((place) => place.current) ?? null;
}
export function getVisibleInventory(view: GameView, limit = 6) {
return view.player.inventory.slice(0, limit);
}
export function getObjectiveRows(view: GameView) {
return view.quests
.filter((quest) => quest.state === 'active' || quest.state === 'completed')
.map((quest) => {
const doneCount = quest.steps.filter((step) => step.done).length;
const nextStep = quest.steps.find((step) => !step.done)?.text ?? quest.steps.at(-1)?.text ?? '待机';
return {
id: quest.id,
title: quest.title,
detail: nextStep,
progress: `${doneCount}/${quest.steps.length}`,
done: quest.state === 'completed',
};
});
}
export function getAttributeRows(view: GameView) {
const { attributes } = view.player;
return [
{ label: 'STR', name: '力量', value: attributes.str },
{ label: 'AGI', name: '敏捷', value: attributes.agi },
{ label: 'INT', name: '智力', value: attributes.int },
{ label: 'PER', name: '感知', value: attributes.per },
{ label: 'LCK', name: '幸运', value: attributes.luck },
];
}
export function getStatusEffects(view: GameView) {
const { stats, maxStats } = view.player;
const effects: { id: string; label: string; detail: string; tone: 'good' | 'warn' | 'danger' }[] = [];
if (stats.life / maxStats.life <= 0.55) {
effects.push({ id: 'life', label: '创伤', detail: '生命处于低位', tone: 'danger' });
}
if (stats.thirst / maxStats.thirst <= 0.5) {
effects.push({ id: 'thirst', label: '脱水', detail: '口渴已压缩行动余量', tone: 'warn' });
}
if (stats.hunger / maxStats.hunger <= 0.5) {
effects.push({ id: 'hunger', label: '饥饿', detail: '需要补充稳定热量', tone: 'warn' });
}
if (stats.energy / maxStats.energy <= 0.45) {
effects.push({ id: 'energy', label: '疲劳', detail: '精力不足,适合休整', tone: 'warn' });
}
if (stats.sanity / maxStats.sanity <= 0.45) {
effects.push({ id: 'sanity', label: '精神波动', detail: '理智偏低,事件风险提升', tone: 'danger' });
}
if (stats.radiation / maxStats.radiation >= 0.32) {
effects.push({ id: 'radiation', label: '污染累积', detail: '辐射正在侵蚀身体', tone: 'danger' });
}
if (!effects.length) {
effects.push({ id: 'stable', label: '稳定', detail: '当前幸存者状态平稳', tone: 'good' });
}
return effects.slice(0, 4);
}
export function getSupplyCounts(view: GameView) {
const counts = {
water: 0,
food: 0,
medicine: 0,
material: 0,
};
for (const item of view.player.inventory) {
if (item.type === 'water') counts.water += item.count;
if (item.type === 'food') counts.food += item.count;
if (item.type === 'medicine') counts.medicine += item.count;
if (item.type === 'material') counts.material += item.count;
}
return counts;
}
export function getKitItem(view: GameView) {
return view.player.inventory.find((item) => item.type === 'medicine' || item.type === 'water') ?? null;
}
export function getLoadoutEntries(view: GameView) {
const inventoryById = new Map(view.player.inventory.map((item) => [item.itemId, item]));
const weaponItem = view.player.equipment.weapon ? inventoryById.get(view.player.equipment.weapon) : undefined;
const bodyItem = view.player.equipment.body ? inventoryById.get(view.player.equipment.body) : undefined;
const toolItem = view.player.equipment.tool ? inventoryById.get(view.player.equipment.tool) : undefined;
const kitItem = getKitItem(view);
const left: EquipmentPreviewEntry[] = [
{
id: 'head',
label: 'Head',
title: '遮面兜帽',
subtitle: '造型预置位',
art: getEquipmentArt(undefined, 'head'),
isEquipped: false,
},
{
id: 'body',
label: 'Body',
title: bodyItem?.name ?? '未装备护甲',
subtitle: bodyItem ? '已挂载在躯干槽' : '建议保留一件抗风装备',
art: getEquipmentArt(bodyItem?.itemId, 'body'),
isEquipped: Boolean(bodyItem),
},
{
id: 'back',
label: 'Back',
title: '远行背包',
subtitle: `容量 ${view.player.inventoryUsage}/${view.player.inventoryCapacity}`,
art: getEquipmentArt(undefined, 'back'),
isEquipped: true,
},
];
const right: EquipmentPreviewEntry[] = [
{
id: 'weapon',
label: 'Weapon',
title: weaponItem?.name ?? '未装备主武器',
subtitle: weaponItem ? '武器槽在线' : '可通过蓝图制作远程装备',
art: getEquipmentArt(weaponItem?.itemId, 'weapon'),
isEquipped: Boolean(weaponItem),
},
{
id: 'tool',
label: 'Tool',
title: toolItem?.name ?? '未挂载工具',
subtitle: toolItem ? '工具槽在线' : '撬棍可作为早期万能工具',
art: getEquipmentArt(toolItem?.itemId, 'tool'),
isEquipped: Boolean(toolItem),
},
{
id: 'kit',
label: 'Kit',
title: kitItem?.name ?? '未配置急救包',
subtitle: kitItem ? `携带 ${kitItem.count} 件应急补给` : '建议随身携带水或药物',
art: kitItem ? getItemArt(kitItem.itemId, kitItem.type) : getEquipmentArt(undefined, 'kit'),
isEquipped: Boolean(kitItem),
},
];
return { left, right };
}
export function getRouteRiskTier(risk: number) {
if (risk <= 0.35) return { label: '低风险', tone: 'safe' as const };
if (risk <= 0.65) return { label: '中风险', tone: 'warn' as const };
return { label: '高风险', tone: 'danger' as const };
}
export function getRiskDots(risk: number) {
const lit = Math.max(1, Math.min(6, Math.round(risk * 6)));
return Array.from({ length: 6 }, (_, index) => index < lit);
}
export function getInventoryStateLabel(item: InventoryViewEntry) {
if (item.equipped) return '已装备';
if (item.canUse) return '可立即使用';
if (item.equipSlot) return '可挂载';
return '物资储备';
}
export function getQuestProgress(quest: QuestView) {
return `${quest.steps.filter((step) => step.done).length}/${quest.steps.length}`;
}
+1
View File
@@ -0,0 +1 @@
export type OverlayPanel = 'inventory' | 'missions' | 'blueprints' | 'logs';
+107
View File
@@ -0,0 +1,107 @@
import type { CSSProperties } from 'react';
import type { EquipSlot } from '@tinywaste/game-core';
const GENERATED_ROOT = '/generated';
const GENERATED_UI_ROOT = `${GENERATED_ROOT}/ui`;
export const PLACE_ART: Record<string, string> = {
home: `${GENERATED_ROOT}/home-camp.png`,
roadside: `${GENERATED_ROOT}/roadside.png`,
old_store: `${GENERATED_ROOT}/old-store.png`,
village_market: `${GENERATED_ROOT}/village-market.png`,
rain_farm: `${GENERATED_ROOT}/rain-farm.png`,
city_edge: `${GENERATED_ROOT}/city-edge.png`,
subway_entrance: `${GENERATED_ROOT}/subway-entrance.png`,
sewer: `${GENERATED_ROOT}/sewer.png`,
vault_gate: `${GENERATED_ROOT}/vault-gate.png`,
};
export const STAT_LABELS: Record<string, string> = {
life: '生命',
hunger: '饥饿',
thirst: '口渴',
energy: '精力',
sanity: '理智',
radiation: '辐射',
};
export const STAT_ORDER = ['life', 'hunger', 'thirst', 'energy', 'sanity', 'radiation'] as const;
const ITEM_ART: Record<string, string> = {
water_dirty: `${GENERATED_UI_ROOT}/items/water-dirty.png`,
water_purified: `${GENERATED_UI_ROOT}/items/water-purified.png`,
canned_beans: `${GENERATED_UI_ROOT}/items/canned-beans.png`,
cloth_rag: `${GENERATED_UI_ROOT}/items/cloth-rag.png`,
herb_bundle: `${GENERATED_UI_ROOT}/items/herb-bundle.png`,
mushroom_cluster: `${GENERATED_UI_ROOT}/items/mushroom-cluster.png`,
scrap_metal: `${GENERATED_UI_ROOT}/items/scrap-metal.png`,
parts_wire: `${GENERATED_UI_ROOT}/items/parts-wire.png`,
rad_pills: `${GENERATED_UI_ROOT}/items/rad-pills.png`,
shiv: `${GENERATED_UI_ROOT}/items/shiv.png`,
crowbar: `${GENERATED_UI_ROOT}/items/crowbar.png`,
leather_coat: `${GENERATED_UI_ROOT}/items/leather-coat.png`,
field_bandage: `${GENERATED_UI_ROOT}/items/cloth-rag.png`,
herbal_tea: `${GENERATED_UI_ROOT}/items/water-purified.png`,
jerky: `${GENERATED_UI_ROOT}/items/canned-beans.png`,
mushroom_stew: `${GENERATED_UI_ROOT}/items/canned-beans.png`,
};
const ITEM_TYPE_FALLBACK_ART: Record<string, string> = {
water: `${GENERATED_UI_ROOT}/items/water-purified.png`,
food: `${GENERATED_UI_ROOT}/items/canned-beans.png`,
medicine: `${GENERATED_UI_ROOT}/items/rad-pills.png`,
material: `${GENERATED_UI_ROOT}/items/scrap-metal.png`,
weapon: `${GENERATED_UI_ROOT}/items/shiv.png`,
tool: `${GENERATED_UI_ROOT}/items/crowbar.png`,
armor: `${GENERATED_UI_ROOT}/items/leather-coat.png`,
};
const SLOT_FALLBACK_ART: Record<string, string> = {
body: `${GENERATED_UI_ROOT}/equipment/body-coat.png`,
weapon: `${GENERATED_UI_ROOT}/equipment/pipe-rifle.png`,
tool: `${GENERATED_UI_ROOT}/equipment/crowbar.png`,
head: `${GENERATED_UI_ROOT}/equipment/head-wrap.png`,
back: `${GENERATED_UI_ROOT}/equipment/backpack.png`,
kit: `${GENERATED_UI_ROOT}/items/rad-pills.png`,
};
const ITEM_TO_EQUIPMENT_ART: Record<string, string> = {
pipe_rifle: `${GENERATED_UI_ROOT}/equipment/pipe-rifle.png`,
crowbar: `${GENERATED_UI_ROOT}/equipment/crowbar.png`,
shiv: `${GENERATED_UI_ROOT}/equipment/shiv.png`,
leather_coat: `${GENERATED_UI_ROOT}/equipment/body-coat.png`,
};
export function getPlaceHeroStyle(placeId: string): CSSProperties {
return {
backgroundImage: `linear-gradient(180deg, rgba(7, 7, 7, 0.12), rgba(7, 7, 7, 0.84)), linear-gradient(90deg, rgba(220, 146, 65, 0.18), rgba(10, 10, 10, 0.05) 58%), url(${PLACE_ART[placeId] ?? ''})`,
};
}
export function getPlaceThumbStyle(placeId: string): CSSProperties {
return {
backgroundImage: `linear-gradient(180deg, rgba(9, 9, 9, 0.05), rgba(9, 9, 9, 0.72)), url(${PLACE_ART[placeId] ?? ''})`,
};
}
export function getItemArt(itemId: string, itemType?: string) {
return ITEM_ART[itemId] ?? (itemType ? ITEM_TYPE_FALLBACK_ART[itemType] : undefined);
}
export function getEquipmentArt(itemId?: string, slot?: EquipSlot | 'head' | 'back' | 'kit') {
if (itemId && ITEM_TO_EQUIPMENT_ART[itemId]) {
return ITEM_TO_EQUIPMENT_ART[itemId];
}
if (itemId && ITEM_ART[itemId]) {
return ITEM_ART[itemId];
}
if (slot) {
return SLOT_FALLBACK_ART[slot];
}
return undefined;
}
export const CHARACTER_PREVIEW_ART = `${GENERATED_UI_ROOT}/character-preview.png`;
@@ -0,0 +1,175 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import type { GameAction, GameView } from '@tinywaste/game-core';
import {
applyGameAction,
createGame,
getGameState,
getMe,
login,
logout,
register,
type AuthUser,
} from '../../api';
export type AuthMode = 'login' | 'register';
export interface AuthFormState {
email: string;
username: string;
identifier: string;
password: string;
}
export function useGameSession() {
const queryClient = useQueryClient();
const [authMode, setAuthMode] = useState<AuthMode>('login');
const [authError, setAuthError] = useState<string | null>(null);
const [gameError, setGameError] = useState<string | null>(null);
const [authForm, setAuthForm] = useState<AuthFormState>({
email: '',
username: '',
identifier: '',
password: '',
});
const [newGameName, setNewGameNameState] = useState('灰烬拾荒者');
const meQuery = useQuery({
queryKey: ['me'],
queryFn: getMe,
});
const gameQuery = useQuery({
queryKey: ['game-state'],
queryFn: getGameState,
enabled: Boolean(meQuery.data?.user),
});
const authMutation = useMutation({
mutationFn: async () => {
setAuthError(null);
if (authMode === 'login') {
return login({
identifier: authForm.identifier,
password: authForm.password,
});
}
return register({
email: authForm.email,
username: authForm.username,
password: authForm.password,
});
},
onSuccess: ({ user }) => {
queryClient.setQueryData(['me'], { user });
queryClient.invalidateQueries({ queryKey: ['game-state'] });
setAuthForm((current) => ({ ...current, password: '' }));
},
onError: (error) => {
setAuthError(error instanceof Error ? error.message : '认证失败。');
},
});
const logoutMutation = useMutation({
mutationFn: logout,
onSuccess: () => {
queryClient.setQueryData(['me'], { user: null });
queryClient.setQueryData(['game-state'], { hasSave: false, view: null });
},
});
const createGameMutation = useMutation({
mutationFn: createGame,
onMutate: () => {
setGameError(null);
},
onSuccess: ({ view }) => {
setGameError(null);
queryClient.setQueryData(['game-state'], { hasSave: true, view });
},
onError: (error) => {
setGameError(error instanceof Error ? error.message : '建档失败。');
},
});
const actionMutation = useMutation({
mutationFn: applyGameAction,
onMutate: () => {
setGameError(null);
},
onSuccess: ({ view }) => {
setGameError(null);
queryClient.setQueryData(['game-state'], { hasSave: true, view });
},
onError: (error) => {
setGameError(error instanceof Error ? error.message : '行动失败。');
},
});
const isWorking =
authMutation.isPending ||
logoutMutation.isPending ||
createGameMutation.isPending ||
actionMutation.isPending;
const handleAuthChange = (patch: Partial<AuthFormState>) => {
if (authError) {
setAuthError(null);
}
setAuthForm((current) => ({ ...current, ...patch }));
};
const handleAuthModeChange = (mode: AuthMode) => {
setAuthError(null);
setAuthMode(mode);
};
const setNewGameName = (value: string) => {
if (gameError) {
setGameError(null);
}
setNewGameNameState(value);
};
const submitAuth = () => {
authMutation.mutate();
};
const startNewGame = (playerName = newGameName) => {
createGameMutation.mutate({ playerName });
};
const sendAction = (action: GameAction) => {
actionMutation.mutate(action);
};
const user: AuthUser | null = meQuery.data?.user ?? null;
const gameState = gameQuery.data ?? { hasSave: false, view: null as GameView | null };
return {
actionMutation,
authError,
authForm,
authMode,
createGameMutation,
gameError,
gameQuery,
handleAuthChange,
handleAuthModeChange,
isCheckingSession: meQuery.isLoading,
isSyncingGame: gameQuery.isLoading,
isWorking,
logoutPending: logoutMutation.isPending,
meQuery,
newGameName,
sendAction,
setNewGameName,
startNewGame,
submitAuth,
user,
view: gameState.view,
hasSave: gameState.hasSave,
logout: () => logoutMutation.mutate(),
};
}
@@ -0,0 +1,10 @@
export function LoadingScreen({ label }: { label: string }) {
return (
<div className="loading-shell">
<div className="loading-card">
<div className="loading-line" />
<p>{label}</p>
</div>
</div>
);
}
@@ -0,0 +1,34 @@
import type { ReactNode } from 'react';
export function ModalShell({
title,
subtitle,
children,
onClose,
size = 'default',
}: {
title: string;
subtitle: string;
children: ReactNode;
onClose?: () => void;
size?: 'default' | 'wide';
}) {
return (
<div className="modal-shell">
<div className={`modal-card modal-card-${size}`}>
<header className="modal-header">
<div className="modal-header-copy">
<span>{subtitle}</span>
<h3>{title}</h3>
</div>
{onClose ? (
<button className="modal-close" onClick={onClose} aria-label="关闭面板">
Close
</button>
) : null}
</header>
{children}
</div>
</div>
);
}
@@ -0,0 +1,18 @@
export function PanelHeader({
title,
subtitle,
compact = false,
}: {
title: string;
subtitle: string;
compact?: boolean;
}) {
return (
<header className={`panel-header ${compact ? 'compact' : ''}`}>
<div>
<h2>{title}</h2>
<p>{subtitle}</p>
</div>
</header>
);
}
+26
View File
@@ -0,0 +1,26 @@
@import url('https://fonts.googleapis.com/css2?family=Chakra+Petch:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap');
html,
body,
#root {
height: 100%;
}
html {
font-family: 'Chakra Petch', sans-serif;
}
body {
min-width: 320px;
}
code,
pre,
button,
input {
font-family: inherit;
}
#root {
min-height: 100vh;
}
+22
View File
@@ -0,0 +1,22 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';
import './index.css';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: 1,
},
},
});
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>,
);
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+12
View File
@@ -0,0 +1,12 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': 'http://localhost:3001',
},
},
})