Chapter 10: Game AI Fundamentals
Purpose
In this chapter, you will gain a foundational understanding of implementing artificial intelligence (AI) for game entities using C++. By the end of this lesson, you'll be equipped to create basic AI behaviors, manage AI states, implement pathfinding, and script AI decisions, enabling you to develop more dynamic and responsive game characters.
Topics Covered
- Simple AI Behaviors: Patrol, Chase, Flee
- State Machines: Managing AI States and Transitions
- Pathfinding Basics: Introduction to Algorithms like A*
- Scripting AI Decisions: Using C++ to Script AI Behavior
1. Simple AI Behaviors: Patrol, Chase, Flee
Understanding Basic AI Behaviors
AI behaviors are the actions that game entities perform in response to game events or player interactions. Three fundamental behaviors are patrol, chase, and flee.
- Patrol: The AI moves along a predefined path or between set points.
- Chase: The AI pursues the player or another target upon detection.
- Flee: The AI retreats from a threat or danger.
Implementing Patrol Behavior
Patrol behavior involves the AI moving between multiple waypoints. Here's a simple way to implement patrol behavior in C++:
class Enemy {
public:
std::vector<Vector2> patrolPoints;
int currentPointIndex;
float speed;
Enemy() : currentPointIndex(0), speed(2.0f) {}
void update(float deltaTime) {
Vector2 target = patrolPoints[currentPointIndex];
Vector2 direction = (target - position).normalize();
position += direction * speed * deltaTime;
if ((target - position).length() < 0.1f) {
currentPointIndex = (currentPointIndex + 1) % patrolPoints.size();
}
}
private:
Vector2 position;
};
Implementing Chase Behavior
Chase behavior activates when the enemy detects the player. The enemy then moves towards the player's position.
void Enemy::chasePlayer(const Vector2& playerPosition, float deltaTime) {
Vector2 direction = (playerPosition - position).normalize();
position += direction * speed * deltaTime;
}
Implementing Flee Behavior
Flee behavior is used when the enemy needs to retreat from a threat. The enemy moves away from the player's position.
void Enemy::fleeFromPlayer(const Vector2& playerPosition, float deltaTime) {
Vector2 direction = (position - playerPosition).normalize();
position += direction * speed * deltaTime;
}
2. State Machines: Managing AI States and Transitions
What is a State Machine?
A state machine is a design pattern that allows an AI to switch between different states (e.g., Patrol, Chase, Flee) based on specific conditions or events.
Implementing a Simple State Machine
First, define the possible states:
enum class AIState {
Patrolling,
Chasing,
Fleeing
};
Next, integrate the state machine into the Enemy class:
class Enemy {
public:
Enemy() : currentState(AIState::Patrolling), speed(2.0f) {}
void update(float deltaTime, const Vector2& playerPosition) {
switch (currentState) {
case AIState::Patrolling:
patrol(deltaTime);
if (detectPlayer(playerPosition)) {
currentState = AIState::Chasing;
}
break;
case AIState::Chasing:
chasePlayer(playerPosition, deltaTime);
if (isLowHealth()) {
currentState = AIState::Fleeing;
}
break;
case AIState::Fleeing:
fleeFromPlayer(playerPosition, deltaTime);
if (isSafe()) {
currentState = AIState::Patrolling;
}
break;
}
}
private:
AIState currentState;
float speed;
Vector2 position;
std::vector<Vector2> patrolPoints;
int currentPointIndex;
void patrol(float deltaTime);
void chasePlayer(const Vector2& playerPosition, float deltaTime);
void fleeFromPlayer(const Vector2& playerPosition, float deltaTime);
bool detectPlayer(const Vector2& playerPosition);
bool isLowHealth();
bool isSafe();
};
State Transitions
- Patrolling → Chasing: When the player is detected.
- Chasing → Fleeing: When the enemy's health is low.
- Fleeing → Patrolling: When the enemy is safe from threats.
3. Pathfinding Basics: Introduction to Algorithms like A*
Understanding Pathfinding
Pathfinding enables AI to navigate the game world efficiently, avoiding obstacles to reach a target. The A* (A-star) algorithm is a popular choice due to its performance and accuracy.
A Algorithm Overview*
A* calculates the shortest path between two points by considering both the actual distance and an estimated distance to the goal (heuristic).
Basic Implementation Steps
- Initialize Open and Closed Lists: Open list contains nodes to be evaluated; closed list contains nodes already evaluated.
- Start Node: Add the starting node to the open list.
- Loop:
- Select the node with the lowest f-cost from the open list.
- Move it to the closed list.
- For each neighbor:
- If it's an obstacle or in the closed list, skip.
- If not in the open list, add it and calculate its f, g, and h costs.
- If already in the open list, check if this path is better and update if necessary.
- Repeat: Until the goal is reached or the open list is empty.
Integrating A in C++*
Implementing the full A* algorithm is beyond this lesson's scope, but here's a skeleton to get you started:
struct Node {
Vector2 position;
float gCost;
float hCost;
float fCost() const { return gCost + hCost; }
Node* parent;
};
std::vector<Vector2> findPath(const Vector2& start, const Vector2& goal, const GameMap& map) {
std::vector<Node*> openList;
std::vector<Node*> closedList;
// Initialize start node
Node* startNode = new Node{ start, 0.0f, (goal - start).length(), nullptr };
openList.push_back(startNode);
while (!openList.empty()) {
// Find node with lowest fCost
auto current = openList.front();
for (auto node : openList) {
if (node->fCost() < current->fCost()) {
current = node;
}
}
// Move current to closed list
openList.erase(std::remove(openList.begin(), openList.end(), current), openList.end());
closedList.push_back(current);
// Check if goal is reached
if (current->position == goal) {
// Reconstruct path
std::vector<Vector2> path;
while (current->parent != nullptr) {
path.push_back(current->position);
current = current->parent;
}
// Cleanup
for (auto node : closedList) delete node;
for (auto node : openList) delete node;
return path;
}
// Generate neighbors
std::vector<Vector2> neighbors = map.getNeighbors(current->position);
for (auto& neighborPos : neighbors) {
// Skip if in closed list or is obstacle
if (map.isObstacle(neighborPos) ||
std::find_if(closedList.begin(), closedList.end(), [&](Node* node) { return node->position == neighborPos; }) != closedList.end()) {
continue;
}
float tentativeG = current->gCost + (neighborPos - current->position).length();
// Check if neighbor is in open list
Node* neighborNode = nullptr;
for (auto node : openList) {
if (node->position == neighborPos) {
neighborNode = node;
break;
}
}
if (neighborNode == nullptr) {
neighborNode = new Node{ neighborPos, tentativeG, (goal - neighborPos).length(), current };
openList.push_back(neighborNode);
} else if (tentativeG < neighborNode->gCost) {
neighborNode->gCost = tentativeG;
neighborNode->parent = current;
}
}
}
// No path found
for (auto node : closedList) delete node;
for (auto node : openList) delete node;
return {};
}
Note: This is a simplified version. For improved performance and functionality, consider using priority queues and more optimized data structures.
4. Scripting AI Decisions: Using C++ to Script AI Behavior
Integrating AI Logic with the Game Loop
AI decisions are typically made within the game loop, updating the AI state based on game events and conditions.
Example: Enemy Update Function
void Enemy::update(float deltaTime, const Vector2& playerPosition, const GameMap& map) {
switch (currentState) {
case AIState::Patrolling:
patrol(deltaTime);
if (detectPlayer(playerPosition)) {
currentState = AIState::Chasing;
path = findPath(position, playerPosition, map);
}
break;
case AIState::Chasing:
if (!detectPlayer(playerPosition)) {
currentState = AIState::Patrolling;
} else if (isLowHealth()) {
currentState = AIState::Fleeing;
} else {
followPath(deltaTime);
}
break;
case AIState::Fleeing:
fleeFromPlayer(playerPosition, deltaTime);
if (isSafe()) {
currentState = AIState::Patrolling;
}
break;
}
}
Handling Path Following
void Enemy::followPath(float deltaTime) {
if (path.empty()) return;
Vector2 target = path.front();
Vector2 direction = (target - position).normalize();
position += direction * speed * deltaTime;
if ((target - position).length() < 0.1f) {
path.erase(path.begin());
}
}
Detecting the Player
bool Enemy::detectPlayer(const Vector2& playerPosition) {
float detectionRadius = 10.0f;
return (playerPosition - position).length() <= detectionRadius;
}
Checking Health and Safety
bool Enemy::isLowHealth() {
return health < maxHealth * 0.3f;
}
bool Enemy::isSafe() {
float safeRadius = 15.0f;
return (playerPosition - position).length() > safeRadius;
}
Project Example: Enemy AI in Platformer
In this project, you'll create enemy characters for a platformer game that patrol their platforms and chase the player upon detection.
Step 1: Define the Enemy Class
Create an Enemy class with necessary properties and methods.
class Enemy {
public:
Enemy(const std::vector<Vector2>& patrolPoints)
: patrolPoints(patrolPoints), currentPointIndex(0), currentState(AIState::Patrolling), speed(2.0f), health(100), maxHealth(100) {}
void update(float deltaTime, const Vector2& playerPosition, const GameMap& map);
void render();
private:
AIState currentState;
std::vector<Vector2> patrolPoints;
int currentPointIndex;
float speed;
Vector2 position;
float health;
float maxHealth;
std::vector<Vector2> path;
void patrol(float deltaTime);
void chasePlayer(float deltaTime, const Vector2& playerPosition, const GameMap& map);
void fleeFromPlayer(float deltaTime, const Vector2& playerPosition);
bool detectPlayer(const Vector2& playerPosition);
bool isLowHealth();
bool isSafe(const Vector2& playerPosition);
void followPath(float deltaTime);
};
Step 2: Implement Patrol Behavior
void Enemy::patrol(float deltaTime) {
Vector2 target = patrolPoints[currentPointIndex];
Vector2 direction = (target - position).normalize();
position += direction * speed * deltaTime;
if ((target - position).length() < 0.1f) {
currentPointIndex = (currentPointIndex + 1) % patrolPoints.size();
}
}
Step 3: Implement Chase Behavior with Pathfinding
void Enemy::chasePlayer(float deltaTime, const Vector2& playerPosition, const GameMap& map) {
if (path.empty()) {
path = findPath(position, playerPosition, map);
}
followPath(deltaTime);
}
Step 4: Implement Flee Behavior
void Enemy::fleeFromPlayer(float deltaTime, const Vector2& playerPosition) {
Vector2 direction = (position - playerPosition).normalize();
position += direction * speed * deltaTime;
}
Step 5: Update Function with State Machine
void Enemy::update(float deltaTime, const Vector2& playerPosition, const GameMap& map) {
switch (currentState) {
case AIState::Patrolling:
patrol(deltaTime);
if (detectPlayer(playerPosition)) {
currentState = AIState::Chasing;
path = findPath(position, playerPosition, map);
}
break;
case AIState::Chasing:
if (!detectPlayer(playerPosition)) {
currentState = AIState::Patrolling;
} else if (isLowHealth()) {
currentState = AIState::Fleeing;
} else {
chasePlayer(deltaTime, playerPosition, map);
}
break;
case AIState::Fleeing:
fleeFromPlayer(deltaTime, playerPosition);
if (isSafe(playerPosition)) {
currentState = AIState::Patrolling;
}
break;
}
}
Step 6: Rendering the Enemy
void Enemy::render() {
// Render the enemy at its current position
drawSprite(enemySprite, position);
}
Step 7: Integrate Enemy into the Game Loop
int main() {
GameMap map = loadGameMap("level1.map");
Vector2 playerPosition;
// Initialize player and enemies
std::vector<Enemy> enemies = {
Enemy({ Vector2(5, 5), Vector2(10, 5) }),
Enemy({ Vector2(15, 10), Vector2(20, 10) })
};
while (gameRunning) {
float deltaTime = getDeltaTime();
playerPosition = getPlayerPosition();
for (auto& enemy : enemies) {
enemy.update(deltaTime, playerPosition, map);
enemy.render();
}
// Render player and other game elements
renderPlayer();
renderGameMap(map);
presentFrame();
}
return 0;
}
Step 8: Testing
- Patrol Test: Verify that enemies move between patrol points smoothly.
- Detection Test: Approach an enemy to ensure it switches to chase behavior.
- Chase Test: Move the player away to check if enemies return to patrol.
- Flee Test: Reduce an enemy's health and confirm it flees when appropriate.
Summary
In this chapter, you've learned the basics of game AI, including how to implement simple behaviors like patrol, chase, and flee. You've explored state machines to manage AI states and transitions effectively and gained an introduction to pathfinding with the A* algorithm. Additionally, you've seen how to script AI decisions using C++, culminating in a project example where you've created enemies for a platformer game that patrol platforms and chase the player upon detection.
Mastering these fundamentals will allow you to create more sophisticated and engaging AI characters, enhancing the overall gameplay experience.
Next Steps
- Advanced State Machines: Explore hierarchical state machines and behavior trees for more complex AI behaviors.
- Optimization: Learn techniques to optimize pathfinding and AI performance in larger game worlds.
- AI Perception: Implement more advanced player detection methods, such as line-of-sight and hearing.
- Collaborative AI: Develop AI systems where multiple enemies coordinate their actions.
Continue building upon these fundamentals to create rich and immersive AI-driven game worlds.