query( 'SELECT c.*, u.username AS owner_name FROM characters c JOIN users u ON u.id = c.user_id ORDER BY u.username, c.sort_order, c.name' )->fetchAll(); } $stmt = db()->prepare( 'SELECT c.*, u.username AS owner_name FROM characters c JOIN users u ON u.id = c.user_id WHERE c.user_id = ? ORDER BY c.sort_order, c.name' ); $stmt->execute([(int) $user['id']]); return $stmt->fetchAll(); } function character_find(int $id): ?array { $stmt = db()->prepare( 'SELECT c.*, u.username AS owner_name FROM characters c JOIN users u ON u.id = c.user_id WHERE c.id = ? LIMIT 1' ); $stmt->execute([$id]); $row = $stmt->fetch(); return $row ?: null; } /** Charakter laden und Zugriff prüfen: eigener Charakter oder Admin. */ function character_require(int $id, array $user): array { $character = character_find($id); if ($character === null) { abort_page(404, 'Diesen Charakter gibt es nicht (mehr).'); } if (!auth_can_manage($user) && (int) $character['user_id'] !== (int) $user['id']) { abort_page(403, 'Dieser Charakter gehört zu einem anderen Konto.'); } return $character; } function character_status_label(string $status): string { return WS_CHARACTER_STATUS[$status] ?? $status; } function character_create(int $userId, array $data): int { // Stufe folgt aus Erfahrungspunkten + Klasse (WS_XP_TABLES); Rettungswürfe // starten dann auf dem Klassenwert dieser Stufe // (Hausregel: Klasse + Stufe bestimmen den Grundwert). $data['level'] = level_for_xp((string) ($data['class_name'] ?? 'Kämpfer'), (int) ($data['xp'] ?? 0)); $data = array_merge($data, saving_throws_for((string) ($data['class_name'] ?? 'Kämpfer'), (int) $data['level'])); $stmt = db()->prepare( 'INSERT INTO characters (user_id, name, title, gender, class_name, level, xp, hp_max, hp_current, ac, attack_bonus, attr_str, attr_dex, attr_con, attr_int, attr_wis, attr_cha, save_death, save_wand, save_paralysis, save_breath, save_spell, alignment, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' ); $stmt->execute([ $userId, $data['name'], $data['title'] ?? '', character_gender($data['gender'] ?? null), $data['class_name'] ?? 'Kämpfer', $data['level'] ?? 1, $data['xp'] ?? 0, $data['hp_max'] ?? 1, $data['hp_current'] ?? $data['hp_max'] ?? 1, character_ac_value($data['ac'] ?? null), $data['attack_bonus'] ?? 0, $data['attr_str'] ?? 10, $data['attr_dex'] ?? 10, $data['attr_con'] ?? 10, $data['attr_int'] ?? 10, $data['attr_wis'] ?? 10, $data['attr_cha'] ?? 10, $data['save_death'] ?? null, $data['save_wand'] ?? null, $data['save_paralysis'] ?? null, $data['save_breath'] ?? null, $data['save_spell'] ?? null, $data['alignment'] ?? '', utc_now(), utc_now(), ]); $id = (int) db()->lastInsertId(); character_seed_skills($id); return $id; } /** * Trägt alle Katalog-Fertigkeiten mit ihrem Startwert ein * (Fertigkeitsstufe = Attributsbonus des zugeordneten Attributs). */ /** * Gleicht den Fertigkeitenkatalog mit WS_SKILL_CATALOG ab: fehlende Einträge * anlegen, Attribut/Gruppe nachziehen, alte Einträge in „Sonstiges“ parken. */ function skills_sync_catalog(): array { $existing = []; foreach (skills_catalog() as $skill) { $existing[(string) $skill['name']] = $skill; } $insert = db()->prepare('INSERT INTO skills (name, attribute, category, sort_order) VALUES (?, ?, ?, ?)'); $update = db()->prepare('UPDATE skills SET attribute = ?, category = ?, sort_order = ? WHERE id = ?'); $order = 0; $created = 0; $updated = 0; foreach (WS_SKILL_CATALOG as $name => [$attribute, $group]) { $order += 10; if (!isset($existing[$name])) { $insert->execute([$name, $attribute, $group, $order]); $created++; continue; } $skill = $existing[$name]; if ((string) $skill['attribute'] !== $attribute || (string) $skill['category'] !== $group) { $update->execute([$attribute, $group, $order, (int) $skill['id']]); $updated++; } unset($existing[$name]); } // Nicht mehr im Bogen geführte Fertigkeiten bleiben erhalten, aber gruppiert. $park = db()->prepare("UPDATE skills SET category = 'Sonstiges' WHERE id = ? AND category <> 'Sonstiges'"); foreach ($existing as $skill) { $park->execute([(int) $skill['id']]); } return ['created' => $created, 'updated' => $updated]; } function character_seed_skills(int $characterId): int { $character = character_find($characterId); if ($character === null) { return 0; } $insert = db()->prepare( 'INSERT INTO character_skills (character_id, skill_id, name, bonus, note) VALUES (?, ?, ?, ?, \'\') ON DUPLICATE KEY UPDATE skill_id = VALUES(skill_id)' ); $count = 0; foreach (skills_catalog() as $skill) { $attribute = trim((string) ($skill['attribute'] ?? '')); $bonus = $attribute === '' ? 0 : max(0, attribute_bonus((int) ($character['attr_' . strtolower($attribute)] ?? 10))); $insert->execute([$characterId, (int) $skill['id'], (string) $skill['name'], $bonus]); $count++; } return $count; } /** * Startwerte der Fertigkeiten auf die aktuellen Attributsboni zurücksetzen. * Manuell erhöhte Werte (Bonus weicht vom Startwert ab) bleiben unberührt, * außer bei $force = true. */ function character_reset_skills(int $characterId, bool $force = false): int { $character = character_find($characterId); if ($character === null) { return 0; } $changed = 0; $update = db()->prepare('UPDATE character_skills SET bonus = ? WHERE id = ?'); foreach (character_skills($characterId) as $row) { $attribute = trim((string) ($row['attribute'] ?? '')); if ($attribute === '') { continue; } $target = max(0, attribute_bonus((int) ($character['attr_' . strtolower($attribute)] ?? 10))); if ($force || (int) $row['bonus'] === $target || (int) $row['bonus'] < 0) { $update->execute([$target, (int) $row['id']]); $changed++; } } return $changed; } /** Basisdaten aktualisieren (Name, Klasse, Werte, Rettungswürfe, Notizen). */ function character_update(int $id, array $d): void { $before = character_find($id); // Stufe aus Erfahrungspunkten und Klasse ableiten – sie ist die einzige // Quelle der Wahrheit, das Feld wird nicht mehr frei eingetragen. $d['level'] = level_for_xp((string) ($d['class_name'] ?? 'Kämpfer'), (int) ($d['xp'] ?? 0)); // Stufe oder Klasse geändert? Dann kommen die Rettungswürfe aus der Tabelle. if ($before !== null) { $levelChanged = (int) $before['level'] !== (int) $d['level']; $classChanged = (string) $before['class_name'] !== (string) ($d['class_name'] ?? ''); if ($levelChanged || $classChanged) { $d = array_merge($d, saving_throws_for((string) ($d['class_name'] ?? 'Kämpfer'), (int) $d['level'])); } } $stmt = db()->prepare( 'UPDATE characters SET name = ?, title = ?, gender = ?, class_name = ?, level = ?, xp = ?, hp_max = ?, hp_current = ?, ac = ?, attack_bonus = ?, attr_str = ?, attr_dex = ?, attr_con = ?, attr_int = ?, attr_wis = ?, attr_cha = ?, save_death = ?, save_wand = ?, save_paralysis = ?, save_breath = ?, save_spell = ?, alignment = ?, deity = ?, age = ?, height = ?, weight = ?, gold_coins = ?, appearance = ?, background = ?, notes = ?, status = ?, updated_at = ? WHERE id = ?' ); $stmt->execute([ $d['name'], $d['title'] ?? '', character_gender($d['gender'] ?? null), $d['class_name'] ?? 'Kämpfer', $d['level'] ?? 1, $d['xp'] ?? 0, $d['hp_max'] ?? 1, $d['hp_current'] ?? 1, character_ac_value($d['ac'] ?? null), $d['attack_bonus'] ?? 0, $d['attr_str'] ?? 10, $d['attr_dex'] ?? 10, $d['attr_con'] ?? 10, $d['attr_int'] ?? 10, $d['attr_wis'] ?? 10, $d['attr_cha'] ?? 10, $d['save_death'] ?? null, $d['save_wand'] ?? null, $d['save_paralysis'] ?? null, $d['save_breath'] ?? null, $d['save_spell'] ?? null, $d['alignment'] ?? '', $d['deity'] ?? '', $d['age'] ?? '', $d['height'] ?? '', $d['weight'] ?? '', $d['gold_coins'] ?? 0, $d['appearance'] ?? '', $d['background'] ?? '', $d['notes'] ?? '', $d['status'] ?? 'active', utc_now(), $id, ]); // Attributsänderungen ziehen die Startwerte der Fertigkeiten mit, // solange sie nicht manuell verändert wurden. if ($before !== null) { $attributes = ['str', 'dex', 'con', 'int', 'wis', 'cha']; $shifted = false; foreach ($attributes as $attribute) { if ((int) ($before['attr_' . $attribute] ?? 10) !== (int) ($d['attr_' . $attribute] ?? 10)) { $shifted = true; break; } } if ($shifted) { character_reset_skills($id); } } } /** Rüstungsklasse: leer/0 bedeutet „automatisch aus der Rüstung“. */ function character_ac_value(mixed $value): ?int { if ($value === null || $value === '') { return null; } $int = (int) $value; return $int > 0 ? $int : null; } /** Geschlecht auf einen gültigen Wert aus WS_GENDERS begrenzen. */ function character_gender(mixed $value): string { $gender = is_string($value) ? trim($value) : ''; return in_array($gender, WS_GENDERS, true) ? $gender : WS_DEFAULT_GENDER; } function character_delete(int $id): void { db()->prepare('DELETE FROM characters WHERE id = ?')->execute([$id]); } /** Abgeleitete Anzeigewerte (Boni, Trefferpunkte-Status, Zauberplätze-Gruppe). */ function character_derived(array $c): array { $bonuses = []; foreach (WS_ATTRIBUTES as $field => [, $label]) { $bonuses[$field] = attribute_bonus((int) ($c[$field] ?? 10)); } $hp = max(0, (int) $c['hp_current']); $hpMax = max(1, (int) $c['hp_max']); return [ 'bonuses' => $bonuses, 'hp_ratio' => min(1.0, $hp / $hpMax), 'hp_state' => $hp <= 0 ? 'unconscious' : ($hp <= $hpMax / 4 ? 'critical' : ($hp < $hpMax / 2 ? 'wounded' : 'healthy')), 'str_damage' => $bonuses['attr_str'], ]; } /* ---------------------------------------------------------- Fertigkeiten */ function skills_catalog(): array { return db()->query('SELECT * FROM skills ORDER BY sort_order, name')->fetchAll(); } function skills_catalog_add(string $name, string $attribute, string $category): void { $max = (int) db()->query('SELECT COALESCE(MAX(sort_order), 0) FROM skills')->fetchColumn(); db()->prepare('INSERT INTO skills (name, attribute, category, sort_order) VALUES (?, ?, ?, ?)') ->execute([$name, $attribute, $category, $max + 10]); } function skills_catalog_delete(int $id): void { db()->prepare('DELETE FROM skills WHERE id = ?')->execute([$id]); } function character_skills(int $characterId): array { $stmt = db()->prepare( "SELECT cs.id, cs.character_id, cs.skill_id, cs.name, cs.bonus, cs.note, COALESCE(NULLIF(cs.attribute, ''), s.attribute) AS attribute, s.category FROM character_skills cs LEFT JOIN skills s ON s.id = cs.skill_id WHERE cs.character_id = ? ORDER BY cs.name" ); $stmt->execute([$characterId]); return $stmt->fetchAll(); } function character_skill_add(int $characterId, ?int $skillId, string $name, int $bonus, string $note, string $attribute = ''): void { if ($skillId !== null && $name === '') { $stmt = db()->prepare('SELECT name FROM skills WHERE id = ?'); $stmt->execute([$skillId]); $name = (string) ($stmt->fetchColumn() ?: ''); } if ($name === '') { return; } db()->prepare( 'INSERT INTO character_skills (character_id, skill_id, name, attribute, bonus, note) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE attribute = VALUES(attribute), bonus = VALUES(bonus), note = VALUES(note), skill_id = VALUES(skill_id)' )->execute([ $characterId, $skillId, shorten($name, 80), skill_attribute_code($attribute), max(0, min(30, $bonus)), shorten($note, 255), ]); } function character_skill_delete(int $characterId, int $id): void { db()->prepare('DELETE FROM character_skills WHERE id = ? AND character_id = ?')->execute([$id, $characterId]); } /* ------------------------------------------------------- Zauber/Liturgien */ function spells_search(string $school, int $grade, string $needle = '', int $limit = 60): array { $sql = 'SELECT * FROM spells WHERE school = ?'; $args = [$school]; if ($grade > 0) { $sql .= ' AND grade = ?'; $args[] = $grade; } if ($needle !== '') { $sql .= ' AND name LIKE ?'; $args[] = '%' . $needle . '%'; } $sql .= ' ORDER BY grade, name LIMIT ' . max(1, $limit); $stmt = db()->prepare($sql); $stmt->execute($args); return $stmt->fetchAll(); } function spell_find(int $id): ?array { $stmt = db()->prepare('SELECT * FROM spells WHERE id = ? LIMIT 1'); $stmt->execute([$id]); return $stmt->fetch() ?: null; } function character_spells(int $characterId): array { $stmt = db()->prepare( 'SELECT cs.*, s.classes, s.duration, s.range_text, s.summary, s.body FROM character_spells cs LEFT JOIN spells s ON s.id = cs.spell_id WHERE cs.character_id = ? ORDER BY cs.school, cs.grade, cs.name' ); $stmt->execute([$characterId]); $rows = $stmt->fetchAll(); return ['arkan' => array_values(array_filter($rows, static fn ($r) => $r['school'] === 'arkan')), 'klerikal' => array_values(array_filter($rows, static fn ($r) => $r['school'] === 'klerikal'))]; } /** Zauber sind in Westreiche nicht vorbereitungspflichtig – prepared wird nicht mehr geführt. */ function character_spell_add(int $characterId, ?int $spellId, string $name, string $school, int $grade, string $note): void { if ($spellId !== null) { $spell = spell_find($spellId); if ($spell !== null) { $name = $name !== '' ? $name : (string) $spell['name']; $school = (string) $spell['school']; $grade = (int) $spell['grade']; } } if ($name === '') { return; } if (!in_array($school, ['arkan', 'klerikal'], true)) { $school = 'arkan'; } $grade = max(1, min(9, $grade)); db()->prepare( 'INSERT INTO character_spells (character_id, spell_id, name, school, grade, note) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE grade = VALUES(grade), note = VALUES(note)' )->execute([$characterId, $spellId, shorten($name, 120), $school, $grade, shorten($note, 255)]); } function character_spell_delete(int $characterId, int $id): void { db()->prepare('DELETE FROM character_spells WHERE id = ? AND character_id = ?')->execute([$id, $characterId]); } /* -------------------------------------------------------------- Inventar */ function character_items(int $characterId): array { $stmt = db()->prepare('SELECT * FROM character_items WHERE character_id = ? ORDER BY category, sort_order, name'); $stmt->execute([$characterId]); return $stmt->fetchAll(); } function character_item_add(int $characterId, array $d): void { $name = trim((string) ($d['name'] ?? '')); if ($name === '') { return; } $category = (string) ($d['category'] ?? 'Ausrüstung'); if (!in_array($category, WS_ITEM_CATEGORIES, true)) { $category = 'Sonstiges'; } db()->prepare( 'INSERT INTO character_items (character_id, name, qty, category, weight, value, equipped, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' )->execute([ $characterId, shorten($name, 120), max(1, (int) ($d['qty'] ?? 1)), $category, shorten((string) ($d['weight'] ?? ''), 40), shorten((string) ($d['value'] ?? ''), 40), !empty($d['equipped']) ? 1 : 0, shorten((string) ($d['note'] ?? ''), 255), ]); } /** * Ausrüstungskatalog (Selektor im Inventar). * * Reihenfolge der Filter: Art (WS_ITEM_CATEGORIES) und Verfügbarkeit als Stufe – * „Methaven“ liefert nur Dorfware, „Garana“ zusätzlich städtische Ware, „alle“ * auch das, was sonst nirgends zu kaufen ist. */ function item_catalog_sync(bool $force = false): int { require_once WS_APP . '/item_catalog_data.php'; $data = item_catalog_data(); $expected = count($data); if (!$force) { $current = (int) db()->query('SELECT COUNT(*) FROM item_catalog')->fetchColumn(); if ($current === $expected) { return 0; } } $stmt = db()->prepare( 'INSERT INTO item_catalog (name, kind, cost, weight, availability, note, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE kind = VALUES(kind), cost = VALUES(cost), weight = VALUES(weight), availability = VALUES(availability), note = VALUES(note), sort_order = VALUES(sort_order)' ); $order = 0; foreach ($data as $row) { $order += 10; $stmt->execute([ shorten((string) $row['name'], 120), (string) $row['kind'], (float) $row['cost'], shorten((string) $row['weight'], 20), (string) $row['availability'], shorten((string) $row['note'], 255), $order, ]); } return $expected; } /** * Katalog durchsuchen. * * `kinds` schränkt auf mehrere Arten zugleich ein (z. B. Rüstung + Schild). * * @param array{kind?:string,kinds?:list,availability?:string,needle?:string,limit?:int} $filter * @return list> */ function item_catalog_search(array $filter = []): array { $where = []; $args = []; $kind = (string) ($filter['kind'] ?? ''); if (in_array($kind, WS_ITEM_CATEGORIES, true)) { $where[] = 'kind = ?'; $args[] = $kind; } $kinds = item_catalog_filter_kinds($filter); if ($kinds !== []) { $where[] = 'kind IN (' . implode(', ', array_fill(0, count($kinds), '?')) . ')'; $args = array_merge($args, $kinds); } $availability = (string) ($filter['availability'] ?? ''); if ($availability === 'methaven') { $where[] = "availability = 'methaven'"; } elseif ($availability === 'garana') { $where[] = "availability IN ('methaven', 'garana')"; } $needle = trim((string) ($filter['needle'] ?? '')); if ($needle !== '') { $where[] = '(name LIKE ? OR note LIKE ?)'; $args[] = '%' . $needle . '%'; $args[] = '%' . $needle . '%'; } $limit = max(1, min(400, (int) ($filter['limit'] ?? 150))); // Gruppen in Katalogreihenfolge (WS_ITEM_CATEGORIES), innerhalb einer Gruppe alphabetisch. $kindOrder = implode(', ', array_fill(0, count(WS_ITEM_CATEGORIES), '?')); $sql = 'SELECT * FROM item_catalog' . ($where === [] ? '' : ' WHERE ' . implode(' AND ', $where)) . ' ORDER BY FIELD(kind, ' . $kindOrder . '), name, id LIMIT ' . $limit; $stmt = db()->prepare($sql); $stmt->execute(array_merge($args, WS_ITEM_CATEGORIES)); return $stmt->fetchAll(); } /** Anzahl der Treffer einer Katalogsuche (ohne Limit). */ function item_catalog_count(array $filter = []): int { $where = []; $args = []; $kind = (string) ($filter['kind'] ?? ''); if (in_array($kind, WS_ITEM_CATEGORIES, true)) { $where[] = 'kind = ?'; $args[] = $kind; } $kinds = item_catalog_filter_kinds($filter); if ($kinds !== []) { $where[] = 'kind IN (' . implode(', ', array_fill(0, count($kinds), '?')) . ')'; $args = array_merge($args, $kinds); } $availability = (string) ($filter['availability'] ?? ''); if ($availability === 'methaven') { $where[] = "availability = 'methaven'"; } elseif ($availability === 'garana') { $where[] = "availability IN ('methaven', 'garana')"; } $needle = trim((string) ($filter['needle'] ?? '')); if ($needle !== '') { $where[] = '(name LIKE ? OR note LIKE ?)'; $args[] = '%' . $needle . '%'; $args[] = '%' . $needle . '%'; } $stmt = db()->prepare( 'SELECT COUNT(*) FROM item_catalog' . ($where === [] ? '' : ' WHERE ' . implode(' AND ', $where)) ); $stmt->execute($args); return (int) $stmt->fetchColumn(); } function item_catalog_find(int $id): ?array { $stmt = db()->prepare('SELECT * FROM item_catalog WHERE id = ? LIMIT 1'); $stmt->execute([$id]); return $stmt->fetch() ?: null; } /** * Feste Artenliste eines Katalogfilters (nur gültige Kategorien, ohne Dubletten). * * @param array $filter * @return list */ function item_catalog_filter_kinds(array $filter): array { $kinds = []; foreach ((array) ($filter['kinds'] ?? []) as $kind) { $kind = (string) $kind; if (in_array($kind, WS_ITEM_CATEGORIES, true) && !in_array($kind, $kinds, true)) { $kinds[] = $kind; } } return $kinds; } /** * Waffenprofil eines Katalogeintrags (Schaden, Kategorie). * * Die OSE-Werte stehen im Katalog nur als Notiz („OSE: 1W6, Nachladen“), deshalb * wird der erste Schadenswürfel gelesen und die Kategorie aus Name und Notiz * abgeleitet. Beides lässt sich im Bogen anschließend korrigieren. * * @param array $entry * @return array{damage:string,category:string} */ function item_catalog_weapon_profile(array $entry): array { $note = (string) ($entry['note'] ?? ''); $name = (string) ($entry['name'] ?? ''); $damage = ''; if (preg_match('/(\d+)\s*W\s*(\d+)(?:\s*([+-])\s*(\d+))?/u', $note, $m) === 1) { $damage = $m[1] . 'W' . $m[2]; if (($m[3] ?? '') !== '' && ($m[4] ?? '') !== '') { $damage .= $m[3] . $m[4]; } } $ranged = preg_match('/(bogen|armbrust|schleuder|blasrohr|wurf|lasso|netz|bolas)/iu', $name) === 1 || preg_match('/fernkampf/iu', $note) === 1; return ['damage' => $damage, 'category' => $ranged ? 'Fernkampf' : 'Nahkampf']; } /** * Rüstungsbonus eines Katalogeintrags. * * Die Notizen nennen die aufsteigende RK als Zielwert („RK 12“); daraus wird der * Bonus gegenüber der ungerüsteten RK 10. Schilde tragen ihren Bonus als „+1 RK“. * Alles andere (Helm, Kleidung) zählt 0. * * @param array $entry */ function item_catalog_armor_bonus(array $entry): int { $note = (string) ($entry['note'] ?? ''); if (preg_match('/\bRK\s*(\d+)/iu', $note, $m) === 1) { return max(-5, min(15, (int) $m[1] - 10)); } if (preg_match('/\+\s*(\d+)\s*(?:RK|Rüstung)/iu', $note, $m) === 1) { return max(-5, min(15, (int) $m[1])); } return 0; } /** * Konfiguration für einen Ausrüstungs-Selektor im Charakterbogen. * * `$key` ist zugleich Präfix der Dialog-ID und der GET-Parameter * (`_kind`, `_avail`, `_q`), damit sich mehrere Selektor-Schirme * auf derselben Seite nicht gegenseitig die Filter überschreiben. * * @param list|null $kinds Feste Arten (z. B. ['Waffe']); null = freie Wahl * @return array{key:string,title:string,action:string,anchor:string,kinds:list|null,filters:array,catalog:list>,count:int,open:bool} */ function item_selector_config(string $key, string $title, string $action, string $anchor, ?array $kinds = null): array { $filters = [ 'kind' => $kinds === null ? query_string($key . '_kind') : '', 'availability' => query_string($key . '_avail'), 'needle' => query_string($key . '_q'), ]; if ($kinds !== null) { $filters['kinds'] = $kinds; } return [ 'key' => $key, 'title' => $title, 'action' => $action, 'anchor' => $anchor, 'kinds' => $kinds, 'filters' => $filters, 'catalog' => item_catalog_search($filters), 'count' => item_catalog_count($filters), 'open' => $filters['kind'] !== '' || $filters['availability'] !== '' || $filters['needle'] !== '', ]; } /** Preis eines Katalogeintrags als Text (Silbertaler, ohne Nachkommastellen wenn glatt). */ function item_cost_label(mixed $cost): string { $value = (float) $cost; if ($value <= 0) { return '–'; } $text = number_format($value, 2, ',', '.'); $text = rtrim(rtrim($text, '0'), ','); return $text . ' SM'; } /** Gewicht eines Katalogeintrags in deutscher Schreibweise. */ function item_weight_label(mixed $weight): string { $text = trim((string) $weight); return $text === '' ? '' : str_replace('.', ',', $text); } /** Katalogeintrag ins Inventar übernehmen (ein Stück, Art = Kategorie). */ function character_item_add_from_catalog(int $characterId, int $catalogId): bool { $entry = item_catalog_find($catalogId); if ($entry === null) { return false; } character_item_add($characterId, [ 'name' => (string) $entry['name'], 'qty' => 1, 'category' => (string) $entry['kind'], 'weight' => (string) $entry['weight'], 'value' => item_cost_label($entry['cost']), 'equipped' => 0, 'note' => (string) $entry['note'], ]); return true; } /** * Waffe aus dem Ausrüstungskatalog in die Bewaffnung übernehmen. */ function character_weapon_add_from_catalog(int $characterId, int $catalogId): bool { $entry = item_catalog_find($catalogId); if ($entry === null || (string) $entry['kind'] !== 'Waffe') { return false; } $profile = item_catalog_weapon_profile($entry); db()->prepare( 'INSERT INTO character_weapons (character_id, weapon_id, name, damage, attack_bonus, category, note, equipped) VALUES (?, NULL, ?, ?, 0, ?, ?, 0)' )->execute([ $characterId, shorten((string) $entry['name'], 80), shorten($profile['damage'], 20), $profile['category'], shorten((string) $entry['note'], 255), ]); return true; } /** * Rüstung oder Schild aus dem Ausrüstungskatalog übernehmen. */ function character_armor_add_from_catalog(int $characterId, int $catalogId): bool { $entry = item_catalog_find($catalogId); $kind = (string) ($entry['kind'] ?? ''); if ($entry === null || !in_array($kind, ['Rüstung', 'Schild'], true)) { return false; } character_armor_add($characterId, 0, [ 'name' => (string) $entry['name'], 'ac_bonus' => item_catalog_armor_bonus($entry), 'kind' => $kind, 'note' => (string) $entry['note'], ]); return true; } function character_item_delete(int $characterId, int $id): void { db()->prepare('DELETE FROM character_items WHERE id = ? AND character_id = ?')->execute([$id, $characterId]); } function character_item_toggle(int $characterId, int $id): void { db()->prepare('UPDATE character_items SET equipped = 1 - equipped WHERE id = ? AND character_id = ?') ->execute([$id, $characterId]); } /* ------------------------------------------------- Waffen & Rüstungen */ function weapons_catalog(): array { return db()->query('SELECT * FROM weapons ORDER BY sort_order, name')->fetchAll(); } function armors_catalog(): array { return db()->query('SELECT * FROM armors ORDER BY sort_order, name')->fetchAll(); } function weapon_catalog_find(int $id): ?array { $stmt = db()->prepare('SELECT * FROM weapons WHERE id = ? LIMIT 1'); $stmt->execute([$id]); return $stmt->fetch() ?: null; } function armor_catalog_find(int $id): ?array { $stmt = db()->prepare('SELECT * FROM armors WHERE id = ? LIMIT 1'); $stmt->execute([$id]); return $stmt->fetch() ?: null; } function character_weapons(int $characterId): array { $stmt = db()->prepare('SELECT * FROM character_weapons WHERE character_id = ? ORDER BY sort_order, name'); $stmt->execute([$characterId]); return $stmt->fetchAll(); } function character_armors(int $characterId): array { $stmt = db()->prepare('SELECT * FROM character_armors WHERE character_id = ? ORDER BY sort_order, name'); $stmt->execute([$characterId]); return $stmt->fetchAll(); } /** Waffe hinzufügen: aus dem Katalog (Werte übernehmen) oder frei eingetragen. */ function character_weapon_add(int $characterId, int $weaponId, array $d = []): void { $name = trim((string) ($d['name'] ?? '')); $damage = trim((string) ($d['damage'] ?? '')); $bonus = (int) ($d['attack_bonus'] ?? 0); $category = (string) ($d['category'] ?? 'Nahkampf'); if ($weaponId > 0 && ($weapon = weapon_catalog_find($weaponId)) !== null) { $name = $name !== '' ? $name : (string) $weapon['name']; $damage = $damage !== '' ? $damage : (string) $weapon['damage']; $category = $category !== '' ? $category : (string) $weapon['category']; $bonus = $bonus !== 0 ? $bonus : (int) $weapon['attack_bonus']; } if ($name === '') { return; } if (!in_array($category, ['Nahkampf', 'Fernkampf'], true)) { $category = 'Nahkampf'; } db()->prepare( 'INSERT INTO character_weapons (character_id, weapon_id, name, damage, attack_bonus, category, note, equipped) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' )->execute([ $characterId, $weaponId > 0 ? $weaponId : null, shorten($name, 80), shorten($damage === '' ? '1W6' : $damage, 20), max(-10, min(10, $bonus)), $category, shorten((string) ($d['note'] ?? ''), 255), !empty($d['equipped']) ? 1 : 0, ]); } function character_weapon_update(int $characterId, int $id, array $d): void { $name = trim((string) ($d['name'] ?? '')); if ($name === '') { return; } $category = (string) ($d['category'] ?? 'Nahkampf'); if (!in_array($category, ['Nahkampf', 'Fernkampf'], true)) { $category = 'Nahkampf'; } db()->prepare( 'UPDATE character_weapons SET name = ?, damage = ?, attack_bonus = ?, category = ?, note = ?, equipped = ? WHERE id = ? AND character_id = ?' )->execute([ shorten($name, 80), shorten((string) ($d['damage'] ?? ''), 20), max(-10, min(10, (int) ($d['attack_bonus'] ?? 0))), $category, shorten((string) ($d['note'] ?? ''), 255), !empty($d['equipped']) ? 1 : 0, $id, $characterId, ]); } function character_weapon_delete(int $characterId, int $id): void { db()->prepare('DELETE FROM character_weapons WHERE id = ? AND character_id = ?')->execute([$id, $characterId]); } function character_weapon_toggle(int $characterId, int $id): void { db()->prepare('UPDATE character_weapons SET equipped = 1 - equipped WHERE id = ? AND character_id = ?') ->execute([$id, $characterId]); } function character_armor_add(int $characterId, int $armorId, array $d = []): void { $name = trim((string) ($d['name'] ?? '')); $bonus = isset($d['ac_bonus']) && $d['ac_bonus'] !== '' ? (int) $d['ac_bonus'] : null; $kind = (string) ($d['kind'] ?? 'Rüstung'); if ($armorId > 0 && ($armor = armor_catalog_find($armorId)) !== null) { $name = $name !== '' ? $name : (string) $armor['name']; $bonus = $bonus !== null ? $bonus : (int) $armor['ac_bonus']; $kind = $kind !== '' ? $kind : (string) $armor['kind']; } if ($name === '') { return; } if (!in_array($kind, ['Rüstung', 'Schild'], true)) { $kind = 'Rüstung'; } db()->prepare( 'INSERT INTO character_armors (character_id, armor_id, name, ac_bonus, kind, note, equipped) VALUES (?, ?, ?, ?, ?, ?, ?)' )->execute([ $characterId, $armorId > 0 ? $armorId : null, shorten($name, 80), max(-5, min(15, $bonus ?? 0)), $kind, shorten((string) ($d['note'] ?? ''), 255), !empty($d['equipped']) ? 1 : 0, ]); } function character_armor_update(int $characterId, int $id, array $d): void { $name = trim((string) ($d['name'] ?? '')); if ($name === '') { return; } $kind = (string) ($d['kind'] ?? 'Rüstung'); if (!in_array($kind, ['Rüstung', 'Schild'], true)) { $kind = 'Rüstung'; } db()->prepare( 'UPDATE character_armors SET name = ?, ac_bonus = ?, kind = ?, note = ?, equipped = ? WHERE id = ? AND character_id = ?' )->execute([ shorten($name, 80), max(-5, min(15, (int) ($d['ac_bonus'] ?? 0))), $kind, shorten((string) ($d['note'] ?? ''), 255), !empty($d['equipped']) ? 1 : 0, $id, $characterId, ]); } function character_armor_delete(int $characterId, int $id): void { db()->prepare('DELETE FROM character_armors WHERE id = ? AND character_id = ?')->execute([$id, $characterId]); } function character_armor_toggle(int $characterId, int $id): void { db()->prepare('UPDATE character_armors SET equipped = 1 - equipped WHERE id = ? AND character_id = ?') ->execute([$id, $characterId]); } function character_skill_update(int $characterId, int $id, int $bonus, string $note, ?string $attribute = null): void { db()->prepare('UPDATE character_skills SET attribute = COALESCE(?, attribute), bonus = ?, note = ? WHERE id = ? AND character_id = ?') ->execute([ $attribute === null ? null : skill_attribute_code($attribute), max(0, min(30, $bonus)), shorten($note, 255), $id, $characterId, ]); } /** * Fertigkeiten nach Gruppen des Charakterbogens sortieren. * * @param list $skills * @return array> */ function skills_grouped(array $skills): array { $groups = []; foreach (WS_SKILL_GROUPS as $group) { $groups[$group] = []; } foreach ($skills as $skill) { $group = trim((string) ($skill['category'] ?? '')); if ($group === '') { $group = 'Sonstiges'; } $groups[$group][] = $skill; } // Feste Reihenfolge des Charakterbogens, unbekannte Gruppen danach. $ordered = []; $sequence = WS_SKILL_GROUPS; $sequence[] = 'Sonstiges'; foreach ($sequence as $group) { if (empty($groups[$group])) { continue; } $rows = $groups[$group]; usort($rows, static fn ($a, $b) => strcasecmp((string) $a['name'], (string) $b['name'])); $ordered[$group] = $rows; unset($groups[$group]); } foreach ($groups as $group => $rows) { if ($rows === []) { continue; } usort($rows, static fn ($a, $b) => strcasecmp((string) $a['name'], (string) $b['name'])); $ordered[$group] = $rows; } return $ordered; } /** Attributsbonus (MOD) einer Fertigkeit für einen Charakter. */ function skill_attribute_modifier(array $character, array $skill): ?int { $attribute = strtolower(trim((string) ($skill['attribute'] ?? ''))); if ($attribute === '') { return null; } return attribute_bonus((int) ($character['attr_' . $attribute] ?? 10)); }