Game Development / Game AI and NPC Development

Using FSM and Decision Trees

This tutorial explores Finite State Machines and decision trees. You'll learn how these can be used to control complex NPC behavior in games.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores the implementation of Artificial Intelligence (AI) in games to control NPC behavior and game mechanics.

Using FSM and Decision Trees

1. Introduction

In this tutorial, we will delve into the world of Finite State Machines (FSM) and Decision Trees, two important concepts in AI programming. They are frequently used in game development to control complex Non-Player Character (NPC) behavior.

By the end of this tutorial, you should be able to:

  • Understand what Finite State Machines and Decision Trees are
  • Implement these techniques in your programs to control NPC behavior

Prerequisites

  • Basic understanding of programming concepts
  • Familiarity with any programming language, preferably Python

2. Step-by-Step Guide

Finite State Machines (FSM)

An FSM is a model of computation used to design both computer programs and sequential logic circuits. It is conceived as an abstract machine that can be in one of a finite number of states.

Example:

Consider a simple light switch. It has two states, ON and OFF. The transition between these states is triggered by a user action (flipping the switch).

# State 1: ON
# State 2: OFF
# User action: Flip switch

Decision Trees

A Decision Tree is a flowchart-like tree structure where each internal node denotes a test on an attribute, each branch represents an outcome of the test, and each leaf node (terminal node) holds a class label.

Example:

A simple decision tree could be used to determine whether to go outside based on the weather.

# Test: Is it raining?
    # Branch 1: Yes -> Don't go outside
    # Branch 2: No -> Go outside

3. Code Examples

Example 1: FSM

In this Python example, we create an FSM to simulate a traffic light.

class TrafficLightFSM:
    def __init__(self):
        self.state = 'Red'

    def change(self):
        if self.state == 'Red':
            self.state = 'Green'
        elif self.state == 'Green':
            self.state = 'Yellow'
        elif self.state == 'Yellow':
            self.state = 'Red'

    def __str__(self):
        return self.state

traffic_light = TrafficLightFSM()

for i in range(10):
    print(str(traffic_light))
    traffic_light.change()

In this code, the traffic light changes from Red to Green, then to Yellow, and back to Red again. This process repeats 10 times.

Example 2: Decision Tree

In this Python example, we'll use the sklearn library to create a Decision Tree for classifying Iris species.

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

# Load Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# Split data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)

# Create Decision Tree classifier
clf = DecisionTreeClassifier()

# Train classifier
clf.fit(X_train, y_train)

# Predict for test set
y_pred = clf.predict(X_test)

print(y_pred)

This program trains a decision tree classifier on the Iris dataset and predicts the species for the test set.

4. Summary

We've learned about Finite State Machines and Decision Trees, two powerful tools for controlling complex behavior in programs. By implementing these concepts, you can create more advanced and realistic game NPCs.

For further learning, you could explore more complex FSMs and Decision Trees or try implementing them in different programming languages.

5. Practice Exercises

Exercise 1: Create an FSM for a DVD player that has the states: Playing, Paused, and Stopped.

Exercise 2: Create a Decision Tree for deciding what to wear based on the weather and the type of event (casual or formal).

Exercise 3: Implement an FSM for a simple game character that can be in one of three states: Idle, Walking, and Running.

Remember to practice regularly to master these concepts. Happy learning!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help