Game AI Algorithms
Basic NPC
These game loops add a small finite state machine (FSM). The NPC waits for one second, walks between x = -1 and x = 1, then turns and waits again. Its two states are idle and walk. dt is seconds passed, capped at 0.05 after a long pause.
2D:
SDL 3:
C:
Install SDL 3 and link against it.
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
enum { IDLE, WALK } state = IDLE;
static double x = -1, direction = 1, waitTime = 1;
static void update(double dt) {
if (state == IDLE) {
waitTime -= dt; // Wait for one second.
if (waitTime <= 0) state = WALK;
} else {
x += direction * dt; // Walk at one unit per second.
if (x * direction >= 1) { // Reached the far end.
x = direction; // Stop at the end.
direction = -direction; // Turn round.
waitTime = 1;
state = IDLE;
}
}
}
int main(int argc, char **argv) {
(void)argc;
(void)argv;
if (!SDL_Init(SDL_INIT_VIDEO)) {
SDL_Log("%s", SDL_GetError());
return 1;
}
SDL_Window *window;
SDL_Renderer *renderer;
if (!SDL_CreateWindowAndRenderer("NPC loop", 640, 360, 0, &window, &renderer)) {
SDL_Log("%s", SDL_GetError());
SDL_Quit();
return 1;
}
bool running = true;
Uint64 last = SDL_GetTicksNS();
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) { // Read input.
if (event.type == SDL_EVENT_QUIT) running = false;
}
if (!running) break;
Uint64 now = SDL_GetTicksNS();
double dt = (now - last) / 1000000000.0; // Seconds passed.
last = now;
if (dt > 0.05) dt = 0.05; // Limit long pauses.
update(dt);
SDL_SetRenderDrawColor(renderer, 20, 20, 20, 255);
SDL_RenderClear(renderer);
// Draw the NPC.
SDL_FRect npc = {320 + (float)x * 200 - 8, 172, 16, 16};
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &npc);
SDL_RenderPresent(renderer);
SDL_Delay(16); // Brief rest.
}
SDL_DestroyRenderer(renderer); // Tidy up.
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Nim:
Install nim-lang/sdl3 and the SDL 3 library.
import sdl3
type State = enum idle, walk
var state = idle
var x = -1.0
var direction = 1.0
var waitTime = 1.0
proc update(dt: float64) =
if state == idle:
waitTime -= dt # Wait for one second.
if waitTime <= 0: state = walk
else:
x += direction * dt # Walk at one unit per second.
if x * direction >= 1: # Reached the far end.
x = direction # Stop at the end.
direction = -direction # Turn round.
waitTime = 1
state = idle
if not init(INIT_VIDEO):
system.quit($getError())
var window: Window
var renderer: Renderer
if not createWindowAndRenderer("NPC loop", 640, 360, 0, window, renderer):
let message = $getError()
sdl3.quit()
system.quit(message)
var running = true
var last = getTicksNS()
while running:
var event: Event
while pollEvent(event): # Read input.
if event.type == EVENT_QUIT: running = false
if not running: break
let now = getTicksNS()
# Seconds passed; limit long pauses.
let dt = min(float64(now - last) / 1_000_000_000.0, 0.05)
last = now
update(dt)
discard setRenderDrawColor(renderer, 20, 20, 20, 255)
discard renderClear(renderer)
# Draw the NPC.
let npc = FRect(x: (320 + x * 200 - 8).cfloat, y: 172, w: 16, h: 16)
discard setRenderDrawColor(renderer, 255, 255, 255, 255)
discard renderFillRect(renderer, npc)
discard renderPresent(renderer)
delay(16) # Brief rest.
destroyRenderer(renderer) # Tidy up.
destroyWindow(window)
sdl3.quit()
PixiJS:
JavaScript:
Use PixiJS 8 in a browser project using a bundler, with pixi.js installed.
import { Application, Graphics } from "pixi.js";
const app = new Application();
await app.init({ width: 640, height: 360 });
document.body.appendChild(app.canvas);
const npc = new Graphics().rect(-8, -8, 16, 16).fill(0xffffff);
npc.position.set(120, 180);
app.stage.addChild(npc);
let state = "idle", x = -1, direction = 1, waitTime = 1;
function update(dt) {
if (state === "idle") {
waitTime -= dt; // Wait for one second.
if (waitTime <= 0) state = "walk";
} else {
x += direction * dt; // Walk at one unit per second.
if (x * direction >= 1) { // Reached the far end.
x = direction; // Stop at the end.
direction = -direction; // Turn round.
waitTime = 1;
state = "idle";
}
}
}
app.ticker.add((ticker) => {
const dt = Math.min(ticker.deltaMS / 1000, 0.05); // Seconds passed.
// Read input here.
update(dt);
npc.x = 320 + x * 200; // Place the NPC.
// PixiJS draws the stage for us.
});
3D:
Sokol:
Sokol calls the frame function and handles window events. The NPC position changes, but drawing its mesh is left as a comment.
C:
Use the Sokol headers and link one Sokol implementation built for your chosen graphics backend.
#define SOKOL_IMPL
#include "sokol_app.h"
#include "sokol_gfx.h"
#include "sokol_glue.h"
static void init(void) {
// Prepare the graphics.
sg_setup(&(sg_desc){ .environment = sglue_environment() });
}
enum { IDLE, WALK } state = IDLE;
static double x = -1, direction = 1, waitTime = 1;
static void update(double dt) {
if (state == IDLE) {
waitTime -= dt; // Wait for one second.
if (waitTime <= 0) state = WALK;
} else {
x += direction * dt; // Walk at one unit per second.
if (x * direction >= 1) { // Reached the far end.
x = direction; // Stop at the end.
direction = -direction; // Turn round.
waitTime = 1;
state = IDLE;
}
}
}
static void frame(void) {
// Limit long gaps between frames.
double dt = sapp_frame_duration();
if (dt > 0.05) dt = 0.05;
update(dt);
// Clear the window.
sg_begin_pass(&(sg_pass){ .swapchain = sglue_swapchain() });
// Draw the NPC at (x, 0, 0) here.
sg_end_pass();
sg_commit();
}
static void cleanup(void) {
sg_shutdown(); // Release the graphics.
}
sapp_desc sokol_main(int argc, char *argv[]) {
(void)argc;
(void)argv;
// Sokol runs the loop.
return (sapp_desc){
.init_cb = init, .frame_cb = frame, .cleanup_cb = cleanup,
.width = 640, .height = 360, .window_title = "NPC loop"
};
}
Nim:
Install the sokol-nim bindings with nimble install sokol.
import sokol/app as sapp
import sokol/gfx as sg
import sokol/glue as sglue
proc init() {.cdecl.} =
# Prepare the graphics.
sg.setup(sg.Desc(environment: sglue.environment()))
type State = enum idle, walk
var state = idle
var x = -1.0
var direction = 1.0
var waitTime = 1.0
proc update(dt: float64) =
if state == idle:
waitTime -= dt # Wait for one second.
if waitTime <= 0: state = walk
else:
x += direction * dt # Walk at one unit per second.
if x * direction >= 1: # Reached the far end.
x = direction # Stop at the end.
direction = -direction # Turn round.
waitTime = 1
state = idle
proc frame() {.cdecl.} =
# Limit long gaps between frames.
let dt = min(sapp.frameDuration(), 0.05)
update(dt)
# Clear the window.
sg.beginPass(sg.Pass(swapchain: sglue.swapchain()))
# Draw the NPC at (x, 0, 0) here.
sg.endPass()
sg.commit()
proc cleanup() {.cdecl.} =
sg.shutdown() # Release the graphics.
# Sokol runs the loop.
sapp.run(sapp.Desc(
initCb: init, frameCb: frame, cleanupCb: cleanup,
width: 640, height: 360, windowTitle: "NPC loop"
))
Three JS:
JavaScript:
Use Three.js in a browser project using a bundler, with three installed.
import * as THREE from "three";
const renderer = new THREE.WebGLRenderer();
renderer.setSize(640, 360);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, 640 / 360, 0.1, 100);
camera.position.z = 5;
const npc = new THREE.Mesh(
new THREE.BoxGeometry(0.2, 0.2, 0.2), new THREE.MeshNormalMaterial()
);
scene.add(npc);
let state = "idle", x = -1, direction = 1, waitTime = 1;
function update(dt) {
if (state === "idle") {
waitTime -= dt; // Wait for one second.
if (waitTime <= 0) state = "walk";
} else {
x += direction * dt; // Walk at one unit per second.
if (x * direction >= 1) { // Reached the far end.
x = direction; // Stop at the end.
direction = -direction; // Turn round.
waitTime = 1;
state = "idle";
}
}
}
let last = performance.now();
renderer.setAnimationLoop((now) => {
const dt = Math.min((now - last) / 1000, 0.05); // Seconds passed.
last = now;
// Read input here.
update(dt);
npc.position.x = x; // Place the NPC.
renderer.render(scene, camera); // Draw the scene.
});