
zendril
Hands-on Rust: spawn entities doesn't honor the frequency (page 276)
While converting to data driven spawning the data specifies that an item (like a dungeon map) has a frequency of 1.
However, when they actually get spawned, it is potentially creating many more of them (or none of them). This appears to be because it is leveraging map_builder.spawn_monsters
which is hard coded to
const NUM_MONSTERS: usize = 50;
So that means this code is iterating over the 50 Points, rather than over the number of items in the available_entities:
spawn_points.iter().for_each(|pt| {
if let Some(entity) = rng.random_slice_entry(&available_entities) {
self.spawn_entity(pt, entity, &mut commands);
}
});
Did I miss something, or is this indeed what is happening?
First Post!

herbert
Hi!
With hindsight, I should have used the rand
crate’s weighted selection, but this seems to work. NUM_MONSTERS
is meant to limit the total number of monsters - the actual weighting happens with available_entities
.
At the top of spawn_entities
(HandsOnRust/template.rs at main · thebracket/HandsOnRust · GitHub), available_entities
is created by first filtering on level (so it only sees entities that can be on the level) and then inserting each entity a number of times equal to its frequency. So an orc with a frequency of 3 would be in available_entities
3 times.
So when random_slice_entry
comes along and picks a slice entry, it includes all of the slice entries - including the duplicates. That preserves the weighting by template type.
Hope that makes sense?
Popular Pragmatic topics









Modern front-end development for Rails, second edition - Struggling to get the first chapter to work

Other popular topics









Latest in PragProg
Latest (all)
Categories:
Popular Portals
- /elixir
- /rust
- /wasm
- /ruby
- /erlang
- /phoenix
- /keyboards
- /js
- /rails
- /python
- /security
- /go
- /swift
- /vim
- /clojure
- /java
- /haskell
- /emacs
- /svelte
- /onivim
- /typescript
- /crystal
- /c-plus-plus
- /tailwind
- /kotlin
- /gleam
- /react
- /flutter
- /elm
- /ocaml
- /vscode
- /opensuse
- /ash
- /centos
- /php
- /deepseek
- /zig
- /scala
- /html
- /debian
- /nixos
- /lisp
- /agda
- /react-native
- /sublime-text
- /textmate
- /kubuntu
- /arch-linux
- /revery
- /ubuntu
- /manjaro
- /spring
- /django
- /diversity
- /nodejs
- /lua
- /c
- /julia
- /slackware
- /neovim