If you’ve watched any science fiction or fantasy movies in the last few decades, you’ve probably seen the following scenario play out enough times that the next paragraph shouldn’t count as a spoiler.

An endless horde overwhelms our heroes. Defeat looks inevitable. But wait! There’s a central “hive queen” pulling the puppet strings, and if the good guys can just disable that boss, the evil army will collapse.

For up-to-date “Game of Thrones” viewers, this might sound familiar. Similar story lines play out with the “brain bugs” in “Starship Troopers” or the “Mind Flayer” in “Stranger Things.” For writers, it’s an easy way to flip the bleakest moment of a story into a happy one.

“My guess is they do this because they need to figure out a way for the heroes to save the day,” said Simon Garnier, the head of the Swarm Lab at the New Jersey Institute of Technology.