1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; // Enum for AI states enum class State { Idle, Patrol, Chase }; // AI class class AI { private: State currentState; int playerDistance; public: AI() : currentState(State::Idle), playerDistance(100) {} void update() { // Update state based on player distance if (playerDistance < 20) { currentState = State::Chase; } else if (playerDistance < 50) { currentState = State::Patrol; } else { currentState = State::Idle; } // Print the current state switch (currentState) { case State::Idle: cout << "AI is idle." << endl; break; case State::Patrol: cout << "AI is patrolling." << endl; break; case State::Chase: cout << "AI is chasing the player!" << endl; break; } } void simulatePlayerMovement() { // Simulate player distance changing playerDistance = rand() % 100; } }; int main() { srand(static_cast<unsigned>(time(0))); // Seed for random number generation AI ai; int steps = 10; for (int i = 0; i < steps; ++i) { cout << "Step " << i + 1 << ":" << endl; ai.simulatePlayerMovement(); ai.update(); cout << endl; } return 0; } |
Explanation
- Headers:
<iostream>
: For input and output operations.<cstdlib>
: Forrand()
andsrand()
Advertisement<ctime>
: Fortime()
function to seed the random number generator.
- Enum:
enum class State
: Defines the possible states for the AI (Idle, Patrol, Chase).
- AI Class:
- Attributes:
currentState
: Current state of the AI.playerDistance
: Simulated distance to the player.
Advertisement - Methods:
update()
: Updates the AI’s state based on the player’s distance and prints the current state.simulatePlayerMovement()
: Simulates changes in player distance using a random value.
- Attributes:
- Main Function:
- Initialization:
- Seeds the random number generator.
- Creates an
AI
object.
- Simulation Loop:
- Runs for a fixed number of steps (10 in this case).
- Simulates player movement by changing the distance.
- Calls
update()
to adjust the AI’s state and print the result.
- Initialization:
Notes:
- Finite State Machine: This program demonstrates a simple finite state machine where the AI’s behavior changes based on the distance to the player.
- Random Distance: The
simulatePlayerMovement()
function generates a random distance to simulate player movement.