AI in Video Games: How to Avoid NPCs as Smart as a Rock?

AI in Video Games: How to Avoid NPCs as Smart as a Rock?

In the wonderful world of game development, we often have to juggle different artificial intelligence systems. But which one to choose without ending up bald from tearing your hair out? Today, we're going to dissect three popular approaches: Finite State Machines (FSM), Behavior Trees (BT), and Goal-Oriented Action Planning (GOAP). And of course, we’ll see why I chose GOAP for Refuge (spoiler: because I value my sanity).

1. Finite State Machines (FSM)

Concept

An FSM is like a spy with only one plan in mind. Each state defines what it does (wander, attack, hide), and it switches states based on predefined conditions. Simple? Yes. But hold on...

Advantages

  • Simple to understand and implement (like making instant noodles, but with less risk of setting the house on fire).
  • Fast execution, ideal for reactive AI.
  • Efficient for basic behaviors like "sees an enemy -> attacks."

Disadvantages

  • The moment you want more complex behavior, you end up with a tangled mess of transitions.
  • Hard to maintain: every new feature turns into a nightmare.
  • Lacks flexibility. "Planning ahead? Never heard of it."

Typical Use Cases

  • A brain-dead zombie walking straight toward you. (Useful, but not exactly impressive.)
  • NPCs with highly predictable and linear behavior.

2. Behavior Tree (BT)

Concept

A Behavior Tree is like a corporate flowchart, except the employees (nodes) actually do their job. Each node decides on an action based on conditions, and you can nest them together to create more nuanced behavior.

Advantages

  • Modular and reusable: No need to reinvent the wheel for every new action.
  • Easier to debug: You can see every decision it makes.
  • Great for complex AI that still needs structure.

Disadvantages

  • If the tree gets too deep, good luck finding your way back.
  • Not always optimal for AI that needs to dynamically react to an evolving environment.

Typical Use Cases

  • A guard who patrols, stops when hearing a noise, and draws a weapon if necessary. (A professional, in short.)
  • AI that intelligently reacts to different stimuli without long-term planning.

3. Goal-Oriented Action Planning (GOAP)

Concept

GOAP is like giving your AI an actual brain. Instead of following a pre-set script, the agent analyzes its situation, sets a goal, and plans the best way to achieve it. Kind of like a person waking up on a Monday morning and deciding whether work is really worth it.

GOAP works with several key elements:

  1. An initial state: Where is the agent? What’s its current condition? What resources are available?
  2. A goal: For example, "find food" or "repair a door."
  3. A set of possible actions: Each action has prerequisites and effects. For example, "go to the kitchen" requires an open door, and the effect is that the agent moves to the kitchen.
  4. A planner: This part finds the optimal sequence of actions to reach the goal while minimizing effort and resources.

Basically, it's like your AI is playing a real-time strategy game… about its own survival.

Advantages

  • Highly flexible: No need to hardcode everything, the AI makes decisions based on what it knows.
  • Better adaptability: No more writing thousands of if-else statements.
  • Easier to extend: Just add a new action, and the AI can use it automatically.

Disadvantages

  • More complex to implement than FSM or BT.
  • Can have higher computational costs if not optimized properly.

Typical Use Cases

  • An NPC in a survival game deciding whether to search for food, build a shelter, or run from danger.
  • Adaptive AI that prioritizes its actions based on real-time circumstances.

Why Did I Choose GOAP for Refuge?

In Refuge, survivors constantly need to adapt to their surroundings: no food? Go find some. Tired? Go to sleep. Too many zombies? Time to write a will.

With an FSM, we’d be drowning in new states for every minor adjustment. A Behavior Tree was an option, but as complexity grows, it would turn into a monster that even Frankenstein wouldn’t want to deal with.

GOAP gives our NPCs real "survival" instincts:

  • They prioritize tasks on their own.
  • They can adapt to unexpected situations without us having to predefine every possible scenario.
  • They actually seem a tiny bit smarter than zombies (which, for a survival game, is a major plus).

Conclusion

If your AI just needs to react to simple events, an FSM is fine. If you want structured but complex behavior, a Behavior Tree does the job. But if you want AI that thinks, plans, and doesn’t make you code a million special cases, then GOAP is your best bet.

For Refuge, the choice was simple: we want survivors, not brain-dead robots.


Dans le merveilleux monde du développement de jeux vidéo, on se retrouve souvent à jongler entre plusieurs systèmes d'intelligence artificielle. Mais lequel choisir sans finir chauve à force de s'arracher les cheveux ? Aujourd'hui, on va disséquer trois approches populaires : les Machines à États Finis (FSM), les Behavior Trees (BT) et le Goal-Oriented Action Planning (GOAP). Et bien sûr, on va voir pourquoi j'ai choisi GOAP pour Refuge (spoiler : parce que je tiens à ma santé mentale).

1. Machines à États Finis (Finite State Machine - FSM)

Principe

Une FSM, c'est comme un agent secret avec un seul plan en poche. Chaque état définit ce qu'il fait (se balader, attaquer, se planquer) et il change d'état selon des conditions préétablies. Simple ? Oui. Mais attendez...

Avantages

  • Simple à comprendre et à implémenter (comme une recette de pâtes, mais sans le risque de tout cramer).
  • Rapide à exécuter, idéal pour des IA réactives.
  • Efficace pour des comportements basiques comme "voit un ennemi -> attaque".

Inconvénients

  • Dès qu'on veut un comportement un peu plus avancé, on se retrouve avec une usine à gaz de transitions.
  • Difficile à maintenir : chaque nouvelle fonctionnalité est un casse-tête chinois.
  • Manque de flexibilité. "Planifier à l'avance ? Connaît pas."

Usage typique

  • Un zombie bête et méchant qui marche vers vous sans réfléchir. (Pratique, mais pas très futé.)
  • Des NPC avec des comportements très prévisibles et linéaires.

2. Behavior Tree (BT)

Principe

Un Behavior Tree, c'est une sorte d'organigramme d'entreprise, mais où les employés (les nœuds) font leur boulot correctement. Chaque nœud décide d'une action en fonction des conditions, et on peut imbriquer tout ça pour un comportement plus nuancé.

Avantages

  • Modulaire et réutilisable : Pas besoin de réinventer la roue à chaque nouvelle action.
  • Facile à déboguer : On peut voir chaque décision prise.
  • Pratique pour des IA plus complexes mais encore sous contrôle.

Inconvénients

  • Si l'arbre devient trop profond, bon courage pour s'y retrouver.
  • Pas toujours optimal pour des IA devant réagir en fonction de leur environnement dynamique.

Usage typique

  • Un garde qui patrouille, s'arrête quand il entend un bruit, et dégaine si besoin. (Bref, un mec consciencieux.)
  • Une IA qui réagit intelligemment à différents stimuli, sans avoir à planifier à long terme.

3. Goal-Oriented Action Planning (GOAP)

Principe

GOAP, c'est un peu comme donner un cerveau à votre IA. Plutôt que de suivre une liste d'actions prédéfinies, l'agent analyse sa situation, fixe un objectif et planifie lui-même les étapes pour y parvenir.

Le fonctionnement de GOAP repose sur plusieurs éléments :

  1. Un état initial : Où est l'agent ? Dans quel état est-il ? Quelles ressources sont disponibles ?
  2. Un objectif : Par exemple, "trouver de la nourriture" ou "réparer une porte".
  3. Un ensemble d'actions possibles : Chaque action a des prérequis et des effets. Par exemple, "aller à la cuisine" nécessite que la porte soit ouverte, et son effet est que l'agent se trouve dans la cuisine.
  4. Un planificateur : Il va chercher le meilleur enchaînement d'actions pour atteindre l'objectif en optimisant les ressources et le temps.

C'est un peu comme si votre IA jouait au jeu de stratégie de sa propre survie, en temps réel.

Avantages

  • Ultra flexible : Plus besoin de tout prévoir, l'IA prend des décisions basées sur ce qu'elle sait.
  • Meilleure adaptabilité : Plus besoin d'écrire mille cas particuliers.
  • Facile à étendre : On ajoute une nouvelle action et l'IA peut l'utiliser directement.

Inconvénients

  • Plus complexe à implémenter qu'une FSM ou un BT.
  • Peut avoir un coût computationnel élevé si mal optimisé.

Usage typique

  • Un NPC dans un jeu de survie qui décide s'il doit chercher à manger, construire un abri, ou fuir un danger.
  • Une IA adaptative qui doit prioriser ses actions en fonction des circonstances.

Pourquoi avoir choisi GOAP pour Refuge ?

Dans Refuge, nos survivants doivent s'adapter en permanence à leur environnement : pas de nourriture ? On va en chercher. Fatigué ? On va dormir. Trop de zombies ? On commence à rédiger notre testament.

Avec une FSM, on aurait passé notre temps à créer de nouveaux états pour chaque petit ajustement. Un Behavior Tree aurait été envisageable, mais à mesure que les besoins augmentent, il serait devenu un monstre ingérable.

GOAP nous permet de donner un réel côté "survie" à nos NPC :

  • Ils choisissent eux-mêmes ce qui est prioritaire.
  • Ils peuvent s'adapter à des imprévus sans qu'on ait à prévoir tous les cas possibles.
  • Ils donnent l'impression d'être un tantinet plus intelligents que des zombies (ce qui, pour un jeu de survie, est plutôt un atout).

Conclusion

Si votre IA doit juste réagir à des événements simples, une FSM suffit. Si vous voulez qu'elle suive des comportements plus évolués sans perdre la tête, un Behavior Tree peut faire le job. Mais si vous voulez une IA qui réfléchit et planifie (et vous évite de coder des tonnes de cas particuliers), alors GOAP est votre ami.

Pour Refuge, le choix était simple : on veut des survivants, pas des robots idiots.