Give every NPC a race and class, resolved at spawn time
NPCs can now optionally specify race and class in their TOML. When omitted, race is randomly selected from non-hidden races and class is determined by the race's default_class or picked randomly from compatible non-hidden classes. Race/class are re-rolled on each respawn for NPCs without fixed values, so killing the barkeep may bring back a different race next time. New hidden content (excluded from character creation): - Beast race: for animals (rats, etc.) with feral stats and no equipment slots - Peasant class: weak default for humanoid NPCs - Creature class: default for beasts/animals Existing races gain default_class fields (humanoids → peasant, beast → creature, dragon → random compatible). Look and examine commands now display NPC race and class. Made-with: Cursor
This commit is contained in:
@@ -29,7 +29,8 @@ impl ChargenState {
|
||||
"\r\n{}\r\n\r\n",
|
||||
ansi::bold("=== Choose Your Race ===")
|
||||
));
|
||||
for (i, race) in world.races.iter().enumerate() {
|
||||
let visible_races: Vec<_> = world.races.iter().filter(|r| !r.hidden).collect();
|
||||
for (i, race) in visible_races.iter().enumerate() {
|
||||
let mods = format_stat_mods(&race.stats);
|
||||
out.push_str(&format!(
|
||||
" {}{}.{} {} {}\r\n {}\r\n",
|
||||
@@ -82,7 +83,8 @@ impl ChargenState {
|
||||
"\r\n{}\r\n\r\n",
|
||||
ansi::bold("=== Choose Your Class ===")
|
||||
));
|
||||
for (i, class) in world.classes.iter().enumerate() {
|
||||
let visible_classes: Vec<_> = world.classes.iter().filter(|c| !c.hidden).collect();
|
||||
for (i, class) in visible_classes.iter().enumerate() {
|
||||
let guild_info = class.guild.as_ref()
|
||||
.and_then(|gid| world.guilds.get(gid))
|
||||
.map(|g| format!(" → joins {}", ansi::color(ansi::YELLOW, &g.name)))
|
||||
@@ -126,7 +128,7 @@ impl ChargenState {
|
||||
ChargenStep::AwaitingRace => {
|
||||
let race = find_by_input(
|
||||
input,
|
||||
&world.races.iter().map(|r| (r.id.clone(), r.name.clone())).collect::<Vec<_>>(),
|
||||
&world.races.iter().filter(|r| !r.hidden).map(|r| (r.id.clone(), r.name.clone())).collect::<Vec<_>>(),
|
||||
);
|
||||
match race {
|
||||
Some((id, name)) => {
|
||||
@@ -149,6 +151,7 @@ impl ChargenState {
|
||||
&world
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|c| !c.hidden)
|
||||
.map(|c| (c.id.clone(), c.name.clone()))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
|
||||
@@ -254,17 +254,23 @@ async fn cmd_look(pid: usize, target: &str, state: &SharedState) -> CommandResul
|
||||
for nid in &room.npcs {
|
||||
if let Some(npc) = st.world.get_npc(nid) {
|
||||
if npc.name.to_lowercase().contains(&low) {
|
||||
let alive = st.npc_instances.get(nid).map(|i| i.alive).unwrap_or(true);
|
||||
let inst = st.npc_instances.get(nid);
|
||||
let alive = inst.map(|i| i.alive).unwrap_or(true);
|
||||
let att = st.npc_attitude_toward(nid, &pname);
|
||||
let mut out = format!(
|
||||
"\r\n{}\r\n {}\r\n",
|
||||
ansi::bold(&npc.name),
|
||||
npc.description
|
||||
);
|
||||
if let Some(inst) = inst {
|
||||
let rname = st.world.races.iter().find(|r| r.id == inst.race_id).map(|r| r.name.as_str()).unwrap_or("???");
|
||||
let cname = st.world.classes.iter().find(|c| c.id == inst.class_id).map(|c| c.name.as_str()).unwrap_or("???");
|
||||
out.push_str(&format!(" {} {}\r\n", ansi::color(ansi::CYAN, rname), ansi::color(ansi::DIM, cname)));
|
||||
}
|
||||
if !alive {
|
||||
out.push_str(&format!(" {}\r\n", ansi::color(ansi::RED, "(dead)")));
|
||||
} else if let Some(ref c) = npc.combat {
|
||||
let hp = st.npc_instances.get(nid).map(|i| i.hp).unwrap_or(c.max_hp);
|
||||
let hp = inst.map(|i| i.hp).unwrap_or(c.max_hp);
|
||||
out.push_str(&format!(
|
||||
" HP: {}/{} | ATK: {} | DEF: {}\r\n",
|
||||
hp, c.max_hp, c.attack, c.defense
|
||||
@@ -897,14 +903,20 @@ async fn cmd_examine(pid: usize, target: &str, state: &SharedState) -> CommandRe
|
||||
for nid in &room.npcs {
|
||||
if let Some(npc) = st.world.get_npc(nid) {
|
||||
if npc.name.to_lowercase().contains(&low) {
|
||||
let alive = st.npc_instances.get(nid).map(|i| i.alive).unwrap_or(true);
|
||||
let inst = st.npc_instances.get(nid);
|
||||
let alive = inst.map(|i| i.alive).unwrap_or(true);
|
||||
let att = st.npc_attitude_toward(nid, pname);
|
||||
let mut out =
|
||||
format!("\r\n{}\r\n {}\r\n", ansi::bold(&npc.name), npc.description);
|
||||
if let Some(inst) = inst {
|
||||
let rname = st.world.races.iter().find(|r| r.id == inst.race_id).map(|r| r.name.as_str()).unwrap_or("???");
|
||||
let cname = st.world.classes.iter().find(|c| c.id == inst.class_id).map(|c| c.name.as_str()).unwrap_or("???");
|
||||
out.push_str(&format!(" {} {}\r\n", ansi::color(ansi::CYAN, rname), ansi::color(ansi::DIM, cname)));
|
||||
}
|
||||
if !alive {
|
||||
out.push_str(&format!(" {}\r\n", ansi::color(ansi::RED, "(dead)")));
|
||||
} else if let Some(ref c) = npc.combat {
|
||||
let hp = st.npc_instances.get(nid).map(|i| i.hp).unwrap_or(c.max_hp);
|
||||
let hp = inst.map(|i| i.hp).unwrap_or(c.max_hp);
|
||||
out.push_str(&format!(
|
||||
" HP: {}/{} | ATK: {} | DEF: {}\r\n",
|
||||
hp, c.max_hp, c.attack, c.defense
|
||||
|
||||
120
src/game.rs
120
src/game.rs
@@ -7,7 +7,7 @@ use russh::server::Handle;
|
||||
use russh::ChannelId;
|
||||
|
||||
use crate::db::{GameDb, SavedPlayer};
|
||||
use crate::world::{Attitude, Object, World};
|
||||
use crate::world::{Attitude, Class, Object, Race, World};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PlayerStats {
|
||||
@@ -92,6 +92,8 @@ pub struct NpcInstance {
|
||||
pub hp: i32,
|
||||
pub alive: bool,
|
||||
pub death_time: Option<Instant>,
|
||||
pub race_id: String,
|
||||
pub class_id: String,
|
||||
}
|
||||
|
||||
pub struct PlayerConnection {
|
||||
@@ -141,31 +143,83 @@ pub struct GameState {
|
||||
|
||||
pub type SharedState = Arc<Mutex<GameState>>;
|
||||
|
||||
impl GameState {
|
||||
pub fn new(world: World, db: Arc<dyn GameDb>) -> Self {
|
||||
let mut npc_instances = HashMap::new();
|
||||
for npc in world.npcs.values() {
|
||||
if let Some(ref combat) = npc.combat {
|
||||
npc_instances.insert(
|
||||
npc.id.clone(),
|
||||
NpcInstance {
|
||||
hp: combat.max_hp,
|
||||
alive: true,
|
||||
death_time: None,
|
||||
},
|
||||
);
|
||||
pub fn resolve_npc_race_class(
|
||||
fixed_race: &Option<String>,
|
||||
fixed_class: &Option<String>,
|
||||
world: &World,
|
||||
rng: &mut XorShift64,
|
||||
) -> (String, String) {
|
||||
let race_id = match fixed_race {
|
||||
Some(rid) if world.races.iter().any(|r| r.id == *rid) => rid.clone(),
|
||||
_ => {
|
||||
// Pick a random non-hidden race
|
||||
let candidates: Vec<&Race> = world.races.iter().filter(|r| !r.hidden).collect();
|
||||
if candidates.is_empty() {
|
||||
world.races.first().map(|r| r.id.clone()).unwrap_or_default()
|
||||
} else {
|
||||
let idx = rng.next_range(0, candidates.len() as i32) as usize;
|
||||
candidates[idx].id.clone()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let class_id = match fixed_class {
|
||||
Some(cid) if world.classes.iter().any(|c| c.id == *cid) => cid.clone(),
|
||||
_ => {
|
||||
let race = world.races.iter().find(|r| r.id == race_id);
|
||||
// Try race default_class first
|
||||
if let Some(ref dc) = race.and_then(|r| r.default_class.clone()) {
|
||||
if world.classes.iter().any(|c| c.id == *dc) {
|
||||
return (race_id, dc.clone());
|
||||
}
|
||||
}
|
||||
// No default → pick random non-hidden class compatible with race
|
||||
let restricted = race
|
||||
.map(|r| &r.guild_compatibility.restricted)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let candidates: Vec<&Class> = world.classes.iter()
|
||||
.filter(|c| !c.hidden)
|
||||
.filter(|c| {
|
||||
c.guild.as_ref().map(|gid| !restricted.contains(gid)).unwrap_or(true)
|
||||
})
|
||||
.collect();
|
||||
if candidates.is_empty() {
|
||||
world.classes.first().map(|c| c.id.clone()).unwrap_or_default()
|
||||
} else {
|
||||
let idx = rng.next_range(0, candidates.len() as i32) as usize;
|
||||
candidates[idx].id.clone()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
(race_id, class_id)
|
||||
}
|
||||
|
||||
impl GameState {
|
||||
pub fn new(world: World, db: Arc<dyn GameDb>) -> Self {
|
||||
let seed = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos() as u64;
|
||||
let mut rng = XorShift64::new(seed);
|
||||
let mut npc_instances = HashMap::new();
|
||||
for npc in world.npcs.values() {
|
||||
let (race_id, class_id) = resolve_npc_race_class(
|
||||
&npc.fixed_race, &npc.fixed_class, &world, &mut rng,
|
||||
);
|
||||
let hp = npc.combat.as_ref().map(|c| c.max_hp).unwrap_or(20);
|
||||
npc_instances.insert(
|
||||
npc.id.clone(),
|
||||
NpcInstance { hp, alive: true, death_time: None, race_id, class_id },
|
||||
);
|
||||
}
|
||||
GameState {
|
||||
world,
|
||||
db,
|
||||
players: HashMap::new(),
|
||||
npc_instances,
|
||||
rng: XorShift64::new(seed),
|
||||
rng,
|
||||
tick_count: 0,
|
||||
}
|
||||
}
|
||||
@@ -398,11 +452,14 @@ impl GameState {
|
||||
|
||||
pub fn check_respawns(&mut self) {
|
||||
let now = Instant::now();
|
||||
for (npc_id, instance) in self.npc_instances.iter_mut() {
|
||||
if instance.alive {
|
||||
continue;
|
||||
}
|
||||
let npc = match self.world.npcs.get(npc_id) {
|
||||
let npc_ids: Vec<String> = self.npc_instances.keys().cloned().collect();
|
||||
for npc_id in npc_ids {
|
||||
let instance = match self.npc_instances.get(&npc_id) {
|
||||
Some(i) => i,
|
||||
None => continue,
|
||||
};
|
||||
if instance.alive { continue; }
|
||||
let npc = match self.world.npcs.get(&npc_id) {
|
||||
Some(n) => n,
|
||||
None => continue,
|
||||
};
|
||||
@@ -410,13 +467,22 @@ impl GameState {
|
||||
Some(s) => s,
|
||||
None => continue,
|
||||
};
|
||||
if let Some(death_time) = instance.death_time {
|
||||
if now.duration_since(death_time).as_secs() >= respawn_secs {
|
||||
if let Some(ref combat) = npc.combat {
|
||||
instance.hp = combat.max_hp;
|
||||
instance.alive = true;
|
||||
instance.death_time = None;
|
||||
}
|
||||
let should_respawn = instance.death_time
|
||||
.map(|dt| now.duration_since(dt).as_secs() >= respawn_secs)
|
||||
.unwrap_or(false);
|
||||
if should_respawn {
|
||||
let hp = npc.combat.as_ref().map(|c| c.max_hp).unwrap_or(20);
|
||||
let fixed_race = npc.fixed_race.clone();
|
||||
let fixed_class = npc.fixed_class.clone();
|
||||
let (race_id, class_id) = resolve_npc_race_class(
|
||||
&fixed_race, &fixed_class, &self.world, &mut self.rng,
|
||||
);
|
||||
if let Some(inst) = self.npc_instances.get_mut(&npc_id) {
|
||||
inst.hp = hp;
|
||||
inst.alive = true;
|
||||
inst.death_time = None;
|
||||
inst.race_id = race_id;
|
||||
inst.class_id = class_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
30
src/world.rs
30
src/world.rs
@@ -104,6 +104,10 @@ pub struct NpcFile {
|
||||
#[serde(default)]
|
||||
pub faction: Option<String>,
|
||||
#[serde(default)]
|
||||
pub race: Option<String>,
|
||||
#[serde(default)]
|
||||
pub class: Option<String>,
|
||||
#[serde(default)]
|
||||
pub respawn_secs: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub dialogue: Option<NpcDialogue>,
|
||||
@@ -244,6 +248,10 @@ pub struct RaceFile {
|
||||
#[serde(default)]
|
||||
pub metarace: Option<String>,
|
||||
#[serde(default)]
|
||||
pub hidden: bool,
|
||||
#[serde(default)]
|
||||
pub default_class: Option<String>,
|
||||
#[serde(default)]
|
||||
pub stats: StatModifiers,
|
||||
#[serde(default)]
|
||||
pub body: BodyFile,
|
||||
@@ -290,6 +298,8 @@ pub struct ClassFile {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub hidden: bool,
|
||||
#[serde(default)]
|
||||
pub base_stats: ClassBaseStats,
|
||||
#[serde(default)]
|
||||
pub growth: ClassGrowth,
|
||||
@@ -395,6 +405,8 @@ pub struct Npc {
|
||||
pub room: String,
|
||||
pub base_attitude: Attitude,
|
||||
pub faction: Option<String>,
|
||||
pub fixed_race: Option<String>,
|
||||
pub fixed_class: Option<String>,
|
||||
pub respawn_secs: Option<u64>,
|
||||
pub greeting: Option<String>,
|
||||
pub combat: Option<NpcCombatStats>,
|
||||
@@ -437,6 +449,8 @@ pub struct Race {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub metarace: Option<String>,
|
||||
pub hidden: bool,
|
||||
pub default_class: Option<String>,
|
||||
pub stats: StatModifiers,
|
||||
pub size: String,
|
||||
pub weight: i32,
|
||||
@@ -462,6 +476,7 @@ pub struct Class {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub hidden: bool,
|
||||
pub base_stats: ClassBaseStats,
|
||||
pub growth: ClassGrowth,
|
||||
pub guild: Option<String>,
|
||||
@@ -535,6 +550,8 @@ impl World {
|
||||
races.push(Race {
|
||||
id, name: rf.name, description: rf.description,
|
||||
metarace: rf.metarace,
|
||||
hidden: rf.hidden,
|
||||
default_class: rf.default_class,
|
||||
stats: rf.stats,
|
||||
size: rf.body.size,
|
||||
weight: rf.body.weight,
|
||||
@@ -560,7 +577,7 @@ impl World {
|
||||
let mut classes = Vec::new();
|
||||
load_entities_from_dir(&world_dir.join("classes"), "class", &mut |id, content| {
|
||||
let cf: ClassFile = toml::from_str(content).map_err(|e| format!("Bad class {id}: {e}"))?;
|
||||
classes.push(Class { id, name: cf.name, description: cf.description, base_stats: cf.base_stats, growth: cf.growth, guild: cf.guild });
|
||||
classes.push(Class { id, name: cf.name, description: cf.description, hidden: cf.hidden, base_stats: cf.base_stats, growth: cf.growth, guild: cf.guild });
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -623,7 +640,12 @@ impl World {
|
||||
let combat = Some(nf.combat.map(|c| NpcCombatStats { max_hp: c.max_hp, attack: c.attack, defense: c.defense, xp_reward: c.xp_reward })
|
||||
.unwrap_or(NpcCombatStats { max_hp: 20, attack: 4, defense: 2, xp_reward: 5 }));
|
||||
let greeting = nf.dialogue.and_then(|d| d.greeting);
|
||||
npcs.insert(id.clone(), Npc { id: id.clone(), name: nf.name, description: nf.description, room: nf.room, base_attitude: nf.base_attitude, faction: nf.faction, respawn_secs: nf.respawn_secs, greeting, combat });
|
||||
npcs.insert(id.clone(), Npc {
|
||||
id: id.clone(), name: nf.name, description: nf.description, room: nf.room,
|
||||
base_attitude: nf.base_attitude, faction: nf.faction,
|
||||
fixed_race: nf.race, fixed_class: nf.class,
|
||||
respawn_secs: nf.respawn_secs, greeting, combat,
|
||||
});
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -644,8 +666,8 @@ impl World {
|
||||
|
||||
if !rooms.contains_key(&manifest.spawn_room) { return Err(format!("Spawn room '{}' not found", manifest.spawn_room)); }
|
||||
for room in rooms.values() { for (dir, target) in &room.exits { if !rooms.contains_key(target) { return Err(format!("Room '{}' exit '{dir}' -> unknown '{target}'", room.id)); } } }
|
||||
if races.is_empty() { return Err("No races defined".into()); }
|
||||
if classes.is_empty() { return Err("No classes defined".into()); }
|
||||
if races.iter().filter(|r| !r.hidden).count() == 0 { return Err("No playable (non-hidden) races defined".into()); }
|
||||
if classes.iter().filter(|c| !c.hidden).count() == 0 { return Err("No playable (non-hidden) classes defined".into()); }
|
||||
|
||||
log::info!("World '{}': {} rooms, {} npcs, {} objects, {} races, {} classes, {} guilds, {} spells",
|
||||
manifest.name, rooms.len(), npcs.len(), objects.len(), races.len(), classes.len(), guilds.len(), spells.len());
|
||||
|
||||
Reference in New Issue
Block a user