PROGRAMMING NPC BEHAVIOR IN GAMES USING ARTIFICIAL INTELLIGENCE
Abstract: the article examines the evolution of architectures for programming non-player character (NPC) behavior at the intersection of classical algorithms and machine-learning methods. The aim of the study is to analyze NPC decision-making mechanisms as a linkage among perception, internal goals, and admissible actions under genre-specific and resource constraints. The researchs relevance is driven by the industry’s need for plausible, controllable, and diverse character behavior that sustains the impression of a living game world. The scientific novelty lies in the systematization of engineering criteria (readability, reproducibility, controllability) applied to hybrid architectures that combine finite-state machines, behavior trees, goal-oriented planning, utility-based action selection, and reinforcement learning. It is demonstrated that the transition from rigid scripting and state webs to modular and learnable solutions is justified only when a controlled rule-based skeleton is preserved, constraining the strategy space and maintaining testability and dramaturgical control. The article is intended for game researchers and developers, game AI specialists, and technical designers responsible for NPC behavior design.
Keywords: NPC behavior, non-player characters, artificial intelligence, finite-state machines, behavior trees.
https://doi.org/10.24412/2712-8849-2026-295-586-601
Introduction. The behavior of non-player characters determines whether the player perceives the game world as a coherent system or merely as a backdrop populated by repetitive reactions. Even with static visuals, it is behavioral plausibility that creates a sense of presence: characters must be capable of selecting actions in context, sustaining the dramaturgy of encounters, preserving the pacing of progression, and at the same time remaining readable to the player. Consequently, behavior programming cannot be reduced to isolated techniques such as chasing or taking cover. Rather, it involves designing a decision-making mechanism that connects world perception, a character’s internal goals, and admissible actions under specific game constraints. Contemporary surveys emphasize that the key difficulty lies not in adding ever more intricate reactions, but in achieving stable, explainable, and reproducible action selection across a wide range of situations [1]. In game development, the term artificial intelligence is used in two distinct senses, and it is crucial to clarify this distinction at the outset, otherwise, further discussion risks splitting into incompatible meanings. In the first sense, the term refers to classical algorithms in which intelligence is implemented as a rule-based structure: finite-state machines, behavior trees, variants of planning, utility evaluation, and other deterministic mechanisms that afford the developer direct control over what a character can and cannot do. These methods emerged as a response to the practical challenge of scaling logic: when simple state machines grow uncontrollably, hierarchical behavior trees enable the assembly of complex tactics from reusable fragments and formalize action priorities without an explosive increase in transitions [2]. In the second sense, artificial intelligence denotes machine learning, where behavior is shaped not by explicit enumeration of rules, but through data, learning from experience, and goal optimization, that is, through configuring what the character is rewarded for and what it is allowed to explore. This introduces adaptivity and unexpected ingenuity, but also a cost in the form of computational overhead, more complex debugging, and the risk of obtaining behavior that is effective yet poorly interpretable and misaligned with game expectations. For this reason, contemporary approaches increasingly favor hybrid logic: basic behavior contours are specified by classical structures, while learnable components are used selectively, precisely where hand-crafted rules struggle to cover the diversity of situations, particularly in coordination tasks and learning in multi-agent environments [3]. Materials and Methodology. The study is grounded in a comparison of two families of approaches that are often conflated under the single label AI in industry practice: deterministic control formalisms (finite-state machines, behavior trees, planning, and utility-based methods) and learnable techniques (primarily reinforcement learning and multi-agent schemes). The material basis of the work is defined by a corpus of domain-specific publications from the reference list: the survey on NPC decision-making identifies the key engineering challenge as the search for stable, explainable, and reproducible action selection across a wide range of game situations [1], while studies on behavior trees explain why the industry is moving away from transition webs of state machines toward hierarchical composition, in which decision logic becomes observable, modular, and more scalable [2, 7]. For machine learning, the theoretical foundation is provided by research on multi-agent deep reinforcement learning, in which adaptivity and coordination are treated as outcomes of goal optimization, while simultaneously highlighting the computational cost and interpretability challenges of agent decisions, factors that are critical in the context of game performance and debugging constraints [3, 9]. Methodologically, the work is structured as a conceptual-analytical investigation of NPC architectures: the unit of analysis is the decision-making mechanism that links observations (world perception), internal goals, and admissible actions, while the comparison criteria are designer controllability, behavioral reproducibility under identical conditions, and player-facing readability as a prerequisite for a fair gameplay challenge. The comparison of deterministic approaches relies on applied evidence regarding the advantages of structuring logic through state machines for clarity of execution and production predictability [5], as well as on the results of evaluations of behavior trees and their expressiveness, which formalize the trade-off between control and variability without eroding causality [6, 7]. For learnable methods, the comparative framework is grounded in the analysis of reinforcement-learning-oriented studies, where behavior is conceptualized as a strategy discovered through reward-driven optimization and thus potentially plastic, yet prone to optimizing the wrong thing from the players and narratives standpoints. This motivates the choice of a hybrid perspective in which learnable components are treated as local amplifiers embedded within a controlled rule-based skeleton, rather than as a complete replacement for classical control [8, 9, 10]. Results and Discussion. From a practical standpoint, the lowest level of NPC control consists of scripts, events, and triggers, which define predefined reactive chains of the form: condition detected - action executed. Such logic is typically tied to specific points in the game world and to specific stimuli: entering an area, collision, a quest phase change, the emergence of a threat, or a players utterance. As a result, behavior arises not so much from the character’s internal intentions as from external signals to which the character is required to respond according to the script, consequently, such systems are often built around environmental objects and markers that hint to the character how to behave at a given location, and reaction switching occurs on events rather than through continuous deliberation. This approach is well illustrated by work on event-oriented mechanisms for secondary characters, where decision selection is moved into event entities and propagated through a message board, reducing the coupling between behavior and a specific agent and simplifying large-scale crowd reactions [4]. The main strength of scripts and triggers is their extreme determinism: the designer gains complete control over what occurs, when, and with which line of dialogue, while the programmer receives a simple debugging model, since causality is almost linear. The same determinism, however, leads to fragility: when the player disrupts the expected sequence (jumps over a barrier, distracts a character, leaves and returns), the logic either hangs between steps or produces contextually inappropriate reactions. Scalability quickly becomes problematic as well: each new exceptional case requires yet another condition, and the growing condition set starts to conflict internally, depriving the system of transparency and degrading reuse. Notably, even in applied studies comparing straightforward implementations of behavior via scattered computational logic with more structured control, the advantage is emphasized specifically in clarity and predictability of execution when transitioning to a state-machine model, including measurable performance benefits in simple prototypes [5]. A logical extension of this distributed trigger system is the finite-state machine, in which behavior is defined by a set of states and transitions between them. In this case, patrol gives way to chase, which gives way to attack, which gives way to search, which gives way to patrol. In this scheme, not only the picture of states is important, but also the discipline of designing transition conditions: perception events (seeing a target, hearing a sound), internal parameters (health, ammunition, fatigue), and temporal constraints must function as filters, otherwise, the machine begins to oscillate, jumping back and forth with minimal fluctuations in the input. Mature implementations introduce hysteresis thresholds, delays, priorities, and cool-downs on immediate re-switching, the purpose of all these techniques is the same: to preserve the readability of behavior for the player and reproducibility for the developer. Contemporary surveys of NPC decision-making explicitly highlight finite-state machines as a basic, widely applied class of methods valued for their structural clarity and ease of control, while also categorizing them as the lowest level of expressiveness compared with more modular constructions [1]. The limitations of finite-state machines become apparent when behavior ceases to be a linear sequence of phases and instead becomes a composition of motives: fight, but avoid fire. Yet cover an ally, and at any moment be ready to abort if a more important threat appears. In state-machine form, such transversal requirements lead either to a combinatorial explosion in the number of states or to the dispersion of transition logic across many locations, at which point the system loses the very properties it was introduced to provide: locality and clarity. It is therefore unsurprising that works describing the evolution of behavioral formalisms stress that with increasing complexity, state machines scale and support reuse poorly, which historically pushed the industry toward hierarchical, modular structures where switching logic is not smeared across transitions but gathered into a controllable composition. This frontier constitutes the transition to the next step, behavior trees, which preserve the predictability of rules while mitigating part of the architectural debt inherent in the state-machine approach [2]. Figure 1 illustrates the process of implementing systemic control. Fig. 1. Enhancing NPC Behavior with Systemic Control. Once finite-state machines reach the limits imposed by state and transition growth, behavior trees emerge as a natural continuation, relocating switching logic from the web of transitions into a single decision and execution hierarchy. In this model, behavior is described as a tree in which leaves correspond to concrete character actions, while internal nodes specify composition rules: what is considered more important, what is checked first, when to interrupt the current attempt, and revert to a higher-priority goal. It is precisely this centralization of logic that makes behavior extensible without avalanche-like complication, which explains why behavior trees historically arose as a response to the poor scalability of state machines and subsequently became a universal formalism for managing complexity in a controlled manner [2]. The operation of a behavior tree is usually organized as a recurring top-down tick cycle: in each cycle, nodes receive a signal to evaluate, check conditions, and either initiate an action or return a status that enables the parent node to select the next option. A small set of building blocks suffices for description: a selector node iterates alternatives until it finds one that can be executed, a sequence node requires steps to succeed in order, condition nodes check facts about the world (target visibility, cover availability, health level), action nodes trigger specific procedures (movement, shooting, item pickup). Through the statuses success, failure, and running, the tree can naturally support interruptions and returns, so that a character can start a maneuver, interrupt it due to a new threat, and then either continue or adopt another plan without manually coding transitions for every case. This mechanism aligns well with the requirement of behavioral readability: the player perceives a sequence of intentions, and the developer obtains a reproducible decision structure [6]. The modularity of behavior trees manifests in individual subtrees being conceptualized as reusable behavioral skills that can be plugged into different contexts and evolved independently. This is particularly convenient for collaborative workflows: writers and behavior specialists can assemble behavior from existing blocks without rewriting low-level logic, while programmers can constrain the set of actions and conditions such that behavior remains safe and predictable. In practice, complex scenarios are naturally expressed as compositions of subtrees: first take cover, then assess risk, if necessary pick up a medkit, and only then attack from an advantageous position, with each link replaceable by a more refined implementation without restructuring the remainder. In surveys of NPC decision-making, behavior trees are typically highlighted as a compromise between control and expressiveness: they remain rule-oriented yet are sufficiently flexible to avoid mechanical repetition of simple templates [7]. Hypothetical extensions of classical methods add plans and utility to allow more semantically rich actions while keeping the classical rules intact. Priority replacement is a context-dependent utility: all admissible actions are ranked according to some context (distance, riskiness, resources, goals, etc.), and the most appropriate action is executed. This allows for a smooth transition between visual styles instead of jumping between nodes of a hardwired branching graph. The character uses goal-directed action planning to chain together a number of actions to achieve a goal and replans actions if the situation changes. Similar to hardwired branching, using rules to specify actions, preconditions, and effects is a core component of planning. Notably, contemporary applied work predominantly considers hybrids: behavior trees provide the framework and constraints, whereas utility and planning are integrated precisely where variability and escape from repetition are required [8]. The shift toward machine learning has become inevitable not because classical methods have become obsolete, but because they exhibit systemic limits: maintenance complexity as exceptions proliferate, duplication of similar branches, repetitive tactics, and weak adaptation to unforeseen player styles. Machine learning excels where the space of situations and actions is too large for manual rule specification or where continuous decisions and fine-grained adaptation are essential, for example, in learnable tactics, group coordination, tuning aggressiveness and accuracy to the player, and discovering unexpected yet effective combinations of actions through reinforcement learning [9]. In industrial logic, however, a controlled skeleton is typically preserved: high-level goals, constraints, narrative limitations, and critical switches remain in behavior trees and planning, while models are delegated local choices and parameterization within clearly delineated boundaries. In this way, adaptivity is achieved without sacrificing reproducibility and controllability [10]. Evolution of AI behavior control is shown in Figure 2. Fig. 2. Evolution of AI Behavior Control. Reinforcement learning shifts NPC control from rule enumeration to strategy search, treating the character as an agent acting in an environment and receiving evaluations of the consequences of its actions. The developer can instead specify an actor space, an observation space for the agent, and a reward function that encodes the desired strategy. The agent explores this action space repeatedly, mapping reward values to the actions it takes to build a probability distribution over them. The agent is then guided to take actions more frequently that scored a positive reward. The result is greater flexibility, where instead of jumping between predetermined modes, an agent can react to small, fine-grain changes in circumstances that may be difficult to pre-program. Applied tasks for reinforcement learning include strong performance in continuous decision-making/micro-tactics, including shot distance and timing, movement and firing timing, cover behind corners and walls, repositioning during danger, flanking, evading, and teamwork with other players. In such tasks, behavior quality is defined not by a single decision but by a sequence of small actions, each affecting subsequent possibilities. Learning thus enables the agent to develop stable habits perceived as combat experience: it begins to economize movement, avoid dangerous trajectories, and choose positions that simultaneously confer advantage and maintain safety. Without constraints, however, this may yield behavior that is formally effective yet appears strange in a game sense, so learning is typically combined with explicit prohibitions to prevent the agent from exceeding the character’s role and genre expectations. Hierarchical reinforcement learning addresses the problem of multi-level control when behavior must integrate both strategic decisions and precise execution. The upper level selects abstract intentions such as take cover, suppress with fire, flank, retreat, while lower levels learn to implement these intentions through concrete movements and actions. This decomposition reduces learning complexity and makes behavior more controllable, because it is easier for designers to manage the set of high-level goals, leaving the model to master their execution in the specific geometry of the level. In addition, hierarchy improves transferability: the same high-level logic can apply across different maps and scenarios if the low-level control adapts execution to local conditions. The risks of reinforcement learning arise from the fact that an agent optimizes reward rather than human intuitions about proper behavior. Programmatic loopholes can also occur, in which the agent exploits the mechanics to achieve high rewards in ways that are nonsensical from the players perspective, breaking immersion in the environment. Even if there are no loopholes, the agent can engage in inscrutable emergent play, where it plays well in ways difficult to explain. Debugging is difficult, as errors may not be related to the specific decisions made, but rather to decisions made previously, the data used for training, or even the process of action selection itself. Consequently, real-world projects require reproducibility, decision logging, constrained action spaces, and filters that discard unacceptable behavioral trajectories before these reach the game. Generative models add a new layer of vivification for NPCs, primarily through dialogue and semantically grounded reactions to context. Conversational dialogue systems using large-language models can produce a variety of outputs and convey on-brand personality through character traits and goals. To do this, characters should be restricted to certain properties, including an admissible domain of world knowledge, topic constraints, a certain speech style, and prohibitions on conflicting lore and false information. However, mere generation is not enough for quests and objectives. Generative layers have to fill templates in a structured way, and these templates must be validated to filter out implementations that would not work or create unbalanced situations. This means that generative methods are applied on top of classical control methods, increasing the search space while still allowing control over the game experience. Figure 3 shows the reinforcement learning process for NPCs. Fig. 3. Reinforcement Learning Cycle for NPCs. In contrast to single-agent settings, in large-scale simulations, there are many agents. Here, behavioral value is defined in terms of the plausibility of a whole collective rather than a single agent. In agent-based modeling, many crowds are generated with local rules of perception and movement. Agents also have local goals, limits, and responses to one another. Overall, global effects are emergent. In such systems, navigation is only one aspect, social signals are equally significant: following the flow, avoiding collisions, forming queues, gravitating toward safe zones, and propagating alarms. When properly tuned, these mechanisms yield a self-organization effect in which the crowd appears natural without manual direction of every step. Machine learning in large-scale systems is usually not used to train each agent to live, but rather to optimize parameters and reactions that are difficult to calibrate by hand. This may involve tuning sensitivity to danger, the speed of flow reconfiguration, the propensity to maintain distance, the likelihood of imitating neighbors, or route choice under limited information. The learnable component acts as a calibrator: it selects coefficients and thresholds so that the global pattern conforms to expected scenarios while remaining robust to random perturbations, for example, unexpected player actions or changes in scene geometry. In this way, developers obtain a controllable social physics, in which rules remain simple and suitable for real-time execution, while learning helps bring dynamics closer to plausibility. Mass phenomena can be seen as tests of whether local rules and systems can produce realistic global dynamics and patterns. Exiting a building, agents must move toward the exits, self-organize in corridors, and respond appropriately to bottlenecks without creating chaos or artificial symmetries. On a meta level, panic should resemble nonlinear waves, neither persisting indefinitely nor composed of rational agents, instead, the irrationality of individuals should be compensated for by the regularities of the crowd. Urban flows test long-term stability: people do not merely move toward goals but conform to environmental rhythms, form persistent routes, avoid obstacles, and preserve the illusion of normalcy when the player interferes with movement. The practical value of artificial intelligence in game production manifests even more strongly in tasks where the aim is not smarter enemies but a more reliable development process. Automated agents can be used to traverse levels, searching the state space for rare bugs, logic deadlocks, broken quests, and unusual mechanic combinations that may be hard to find manually. Dynamic difficulty adjustment can monitor player behaviors and adapt enemy attribute values to maintain a consistent difficulty level, without creating spikes or appearing overly punishing, and should be subtle and interpretable within the in-game context. Other aspects of living worlds, like the passage of time, the routines and habits of its inhabitants, their memory of the players interactions, and their personal goals, all help make each characters interactions with players feel like an episode in their life. These examples simultaneously clarify why replacing all behavior components with neural networks is not viable. Gameplay requires readability: players must detect patterns and learn from them, and overly unpredictable behavior destroys the perception of a fair challenge. Computational cost constrains both training and inference: even after training, a models runtime execution competes with graphics, physics, and networking for resources, and in crowds, this cost is multiplied by the number of agents. Designer control also changes: instead of directly specifying behavior, designers must act indirectly via goals and constraints, complicating authorial control over pacing, dramaturgy, and character roles. Finally, consistency and reproducibility are critical for debugging: behavior must repeat under identical conditions, otherwise bug fixing degenerates into guesswork. Accordingly, in mature systems, learnable components are almost always embedded within frameworks that constrain, log, and validate their decisions. Conclusion. NPC behavior in a game system functions not as a decorative layer but as a mechanism linking world perception, the agent’s internal goals, and admissible actions under genre and computational constraints. In this context, it is essential to differentiate between two meanings of game AI: on the one hand, deterministic rule structures that ensure direct control and reproducibility (finite-state machines, behavior trees, planning, utility-based methods), on the other hand, learnable techniques in which adaptivity emerges from goal and experience optimization but is paid for by increased interpretive and debugging complexity. Thus, the central problem is formulated not as the accumulation of reactions but as achieving stable, explainable, and repeatable action selection across a broad spectrum of situations while preserving readability for the player and controllability for the developer. The examined evolution of classical approaches demonstrates a systematic transition from event- and script-based chains to a more architectural perspective on decision-making. Triggers and scripts provide maximal determinism but exhibit fragility when players deviate from expected sequences and quickly lose transparency as conditions scale. Finite-state machines introduce discipline through states and transitions, yet as cross-cutting requirements grow, they can lead to architectural sprawl and a combinatorial explosion of complexity. Behavior trees alleviate part of this debt by concentrating decision logic in a hierarchy and making behavior modular, extensible, and suitable for reuse, further enhancing expressiveness is achieved by incorporating utility-based methods and planning to escape rigid priorities without abandoning a controlled rule-based skeleton. Machine learning, particularly reinforcement learning and its hierarchical variants, introduces a different regime of behavior construction: not enumerating when to do what, but searching for strategies within specified spaces of observations, actions, and rewards, which is especially salient in continuous decisions, micro-tactics, and coordination. However, the identified risks, optimizing reward rather than intuitive plausibility, the emergence of formally effective yet unreadable and genre-incongruent tactics, increased computational cost, and impaired reproducibility, lead to a practical conclusion in favor of hybridization. In mature production logic, learnable components are most effective not as replacements for classical control but as local amplifiers within frameworks where high-level goals, constraints, dramaturgical switches, and consistency control remain rule-driven, while model decisions are constrained, logged, and validated for acceptability, thereby preserving a balance among adaptivity, readability, and engineering reliability.
Полная версия статьи PDF
Номер журнала «Вестник науки» № 2 (95) том 3
Ссылка для цитирования:
PROGRAMMING NPC BEHAVIOR IN GAMES USING ARTIFICIAL INTELLIGENCE // Журнал «Вестник науки» от 15 февраля 2026 г. № 2 (95) том 3. С. 586 - 601. 2026 г. ISSN 2712-8849 // Электронный ресурс: https://www.вестник-науки.рф/article/28975 (дата обращения: 29.11.2026 г.)
Альтернативная ссылка латинскими символами: vestnik-nauki.com/article/28975
Нашли грубую ошибку (плагиат, фальсифицированные данные или иные нарушения научно-издательской этики) ?
- напишите письмо в редакцию журнала: zhurnal@vestnik-nauki.com
