Перейти к основному содержимому

ИИ в играх

Разработчику

Слово ИИ в играх объединяет ботов с 1990-х и нейросети 2020-х. Здесь — карта технологий без хайпа: классический game AI, процедурная генерация, ML в продакшене, LLM и этика. Общая база ML — раздел 6; дискурс — 9.10/132. Связанное: гейм-дизайн, оптимизация, доступность, Unity, Unreal.


Два разных смысла ИИ

Игровой ИИ (game AI) — правила, графы и скрипты поведения NPC:

  • pathfinding и NavMesh;
  • finite state machines;
  • behavior trees и GOAP;
  • utility scoring.

ML и нейросети — обучение на данных:

  • античит и anomaly detection;
  • matchmaking и churn prediction;
  • боты, имитирующие стиль игрока;
  • эксперименты с LLM-диалогами и diffusion-артом.

Игроку поведение кажется умным из дизайна и телеграфа, GPT для этого не обязателен.


Словарь game AI

  • FSM — finite state machine, конечный автомат состояний.
  • Behavior tree (BT) — дерево задач с selector/sequence/decorator.
  • GOAP — Goal-Oriented Action Planning, планировщик действий по целям.
  • Utility AI — выбор действия по числовой полезности.
  • NavMesh — навигационная сетка проходимых областей.
  • A* — алгоритм поиска пути на графе.
  • Steering behaviors — seek, flee, flock для движения.
  • Blackboard — общая память AI между системами.
  • Telegraph — визуальная подсказка перед атакой босса.
  • Perception — sight/hearing cones, line of sight.
  • ELO / TrueSkill — рейтинг для matchmaking.
  • RL — reinforcement learning для обучения агентов.
  • PCG — procedural content generation.

История — хронология

ПериодВехи
1950–60Minimax (шахматы), ELIZA — не игры, но база
1970–80Space Invaders patterns, Pac-Man ghost FSM
1990Doom finite states, Quake monsters, RTS pathfinding
1998–2004Half-Life scripting, F.E.A.R. GOAP (Jeff Orkin)
2005–10Behavior trees в AAA (Halo 2), crowds
2010–15Utility AI (Killing Floor 2), NavMesh стандарт в Unity/UE
2016–20DeepMind AlphaGo; ML anticheat в online shooters
2020–26LLM NPC эксперименты, generative assets, AI-assisted tools

Ключевой урок истории: простые FSM + хороший дизайн побеждали сложные системы без fun.


FSM — конечные автоматы

Структура

  • States: Idle, Patrol, Chase, Attack, Flee.
  • Transitions: условия (distance < 10, health < 0.2).
  • Entry/exit actions: play animation, enable collider.

Плюсы и минусы

  • Плюсы: простота, debug, предсказуемость для дизайнера.
  • Минусы: combinatorial explosion при росте states; spaghetti transitions.

Когда использовать

  • Boss phases с 3–5 чёткими режимами.
  • Simple enemies (turret, animal).
  • UI flow и game mode switching.

Пример (псевдокод)

state Patrol:
if sees_player: goto Chase
state Chase:
if lost_player: goto Patrol
if in_range: goto Attack
state Attack:
if health_low: goto Flee

Behavior Trees — деревья поведения

Узлы

  • Selector (?) — первый успешный child; OR.
  • Sequence (→) — все children success; AND.
  • Decorator — invert, repeat, cooldown, fail on condition.
  • Leaf — action (move, shoot) или condition (can see player).

Execution model

  • Tick каждый frame или fixed interval с Running status.
  • Interrupt: higher priority branch (heard gunshot) aborts patrol.

AAA-паттерн

  • Subtrees: Combat, Investigate, Social reusable.
  • Blackboard keys: TargetActor, LastKnownPosition, AmmoCount.

Unity пример (псевдокод C#)

// Упрощённый tick
public enum NodeState { Success, Failure, Running }

public abstract class BTNode {
public abstract NodeState Tick(Blackboard bb);
}

public class Sequence : BTNode {
public List<BTNode> children;
public override NodeState Tick(Blackboard bb) {
foreach (var c in children) {
var s = c.Tick(bb);
if (s != NodeState.Success) return s;
}
return NodeState.Success;
}
}

public class MoveToTarget : BTNode {
public override NodeState Tick(Blackboard bb) {
if (bb.Target == null) return NodeState.Failure;
agent.SetDestination(bb.Target.position);
return agent.remainingDistance < 1f ? NodeState.Success : NodeState.Running;
}
}

Unreal: Behavior Tree Editor + Blackboard + Environment Query System (EQS).


GOAP — планирование действий

Концепция (F.E.A.R.)

  • Goals: KillPlayer, TakeCover, Reload — с priority.
  • Actions: atomic с preconditions и effects.
  • Planner строит цепочку actions минимальной cost.

Action example

Action Reload:
Preconditions: has_magazine, in_cover
Effects: ammo_full
Cost: 2.0

Когда использовать

  • Emergent tactics без ручного BT на каждый сценарий.
  • Sandbox NPC с inventory и world state.

Сложность

  • Planner A* по action space; нужен cap на depth.
  • Debug сложнее BT; документируйте actions.

Utility AI — полезность действий

Scoring

Каждое action получает score 0–1:

score_attack = curve(distance) * curve(ammo) * curve(visibility)
score_flee = curve(low_health) * curve(outnumbered)
pick max score if above threshold

Curves

  • Linear, logistic, custom AnimationCurve в Unity.
  • Killing Floor 2 — классический utility reference.

Комбинация с BT

  • Utility выбирает branch; BT исполняет детали.

Pipeline

  1. Bake NavMesh из geometry уровня (walkable slope, step height).
  2. NavMesh Agent — radius, height, avoidance.
  3. Off-mesh links — прыжки, лadders, doors.
  4. Dynamic obstacles — carve holes или local avoidance (RVO).

A* и оптимизация

  • Hierarchical pathfinding для open world.
  • Partial paths при moving target.
  • Async path query на worker thread (Unity DOTS/ECS patterns).

Godot 4

@onready var agent: NavigationAgent3D = $NavigationAgent3D

func _physics_process(delta):
if target:
agent.target_position = target.global_position
if not agent.is_navigation_finished():
var next = agent.get_next_path_position()
velocity = (next - global_position).normalized() * speed
move_and_slide()

Common bugs

  • Agent stuck on edge — adjust bake agent radius.
  • Enemies stack — separation steering + priority.
  • Floating — align Y to ground raycast.

См. Unity, Unreal, оптимизация.


Процедурная генерация

Не всегда ML; часто классические алгоритмы.

Шум и ландшафт

  • Perlin / Simplex noise — heightmap Minecraft-style.
  • Octaves, persistence, lacunarity для detail.
  • Erosion simulation post-process для realism.

Wave Function Collapse (WFC)

  • Tile constraints: соседние edges match.
  • Уровни Zelda-like dungeons, 2D maps.
  • Over-constrained → restart with backtrack.

Graph-based dungeons

  • Rooms as nodes, doors as edges.
  • Minimum spanning tree + extra loops для variety.
  • Roguelike: place rooms, connect corridors, spawn entities by rules.

L-systems и flora

  • Trees, rivers as recursive grammar.

Loot tables

  • Weighted random — design-controlled proc gen.
  • Seeded RNG для reproducible speedruns.

Budget и QA

  • Validation pass: reachable exit, difficulty bounds.
  • Playtest на 100 seeds.

ML в продакшене

ЗадачаПодходГде выполняется
АнтичитAnomaly input timing, stat outliersServer
MatchmakingELO, TrueSkill, skill bucketsServer
Churn predictionGradient boosting on telemetryBackend
Bot playersImitation learning, RL on replaysServer / offline train
Dynamic difficultyMoving average deaths, time-to-completeClient or server
Toxic chatText classifierServer
Personalization offersRecommendationBackend

Античит

  • Speed hack: position delta vs server simulation.
  • Aimbot: inhuman snap velocity distribution.
  • ML flags review queue, не instant ban без human.

Matchmaking

  • Skill rating convergence ~20–40 matches.
  • Smurf detection — separate models controversial.

Ограничения клиента

  • Тяжёлые модели на сервере; на клиенте — FPS и батарея (оптимизация).
  • On-device ML (Core ML, NNAPI) для niche: gesture, photo mode filters.

LLM для NPC — риски и практика

Обещания маркетинга

  • Бесконечные диалоги — demos 2023–2025 (Convai, Inworld, Ubisoft NEO).

Риски

  • Hallucination — NPC говорит о квестах, которых нет.
  • Toxicity — игрок провоцирует; нужен filter pipeline.
  • Canon break — lore violation breaks immersion.
  • Latency — 500 ms+ unacceptable in action games.
  • Cost — API per token at scale.
  • Privacy — voice/chat logged; GDPR.

Mitigation

  • RAG на approved lore documents only.
  • Structured output (JSON intent) → hand-authored lines when possible.
  • Fallback lines when API down.
  • Human review for shipped vertical slices.

Где уместно

  • Hub games, social sims, tabletop adapters.
  • Не core loop fast combat NPC barking.

Generative art и этика

Use cases

  • Concept art iteration, texture upscaling, placeholder assets.
  • Voice synth with actor consent contract.

Споры

  • Training data copyright (Stable Diffusion lawsuits ongoing).
  • Asset store policies on AI disclosure.
  • Displacement junior artists — кризис индустрии.

Studio policy template

  • Disclose AI in credits where required.
  • No ship unreviewed AI assets in hero content without art director sign-off.
  • Prefer licensed or in-house fine-tuned models for style consistency.

Карьера в индустрии

Роли

  • Gameplay programmer — BT, FSM, combat AI; most common entry.
  • AI programmer — nav, crowds, GOAP at AAA.
  • ML engineer — matchmaking, anticheat, analytics; rarely dedicated NPC GPT roles.
  • Technical designer — tuning utility curves, boss phases.

Навыки gameplay AI

  • C++/C#, data structures, debugging.
  • Unreal BT/Blackboard or Unity AI plugins.
  • Playtest iteration with designers.

Навыки ML

  • Python, PyTorch, SQL, telemetry pipelines.
  • Not substitute for game design sense.

Портфолио

  • Small project: stealth game with patrol/chase FSM + NavMesh.
  • Postmortem: what broke in playtest and how you fixed telegraph timing.

Ресурсы для обучения

Книги и курсы

  • Programming Game AI by Example — Buckland (FSM, steering, BT intro).
  • Artificial Intelligence for Games — Millington & Funge.
  • GDC Vault: Halo AI, F.E.A.R. GOAP, DOOM 2016 AI.

Онлайн

  • Game AI Pro — free articles.
  • Unity Learn: NavMesh, ML-Agents (RL experiments).
  • Unreal Documentation: Behavior Trees, EQS, Mass AI (crowds).

ML


Примеры Unity и Godot

Unity — простой enemy FSM

public enum State { Patrol, Chase, Attack }

public class EnemyAI : MonoBehaviour {
public State state = State.Patrol;
public Transform player;
public float sightRange = 15f;

void Update() {
switch (state) {
case State.Patrol:
Patrol();
if (CanSeePlayer()) state = State.Chase;
break;
case State.Chase:
Chase();
if (DistanceToPlayer() < 2f) state = State.Attack;
else if (!CanSeePlayer()) state = State.Patrol;
break;
case State.Attack:
Attack();
break;
}
}
}

Godot — BT-like with states

enum State { PATROL, CHASE, ATTACK }
var state = State.PATROL

func _process(delta):
match state:
State.PATROL:
_patrol()
if _can_see_player():
state = State.CHASE
State.CHASE:
_chase()
if _distance_to_player() < 2.0:
state = State.ATTACK
State.ATTACK:
_attack()

Perception и combat AI

Sense models

  • Sight: cone angle, radius, peripheral falloff; line trace to target bone.
  • Hearing: event stimuli radius (footstep loudness RTPC from audio); stimulus age decay.
  • Damage: last known direction indicator for flanking AI.

Telegraph design

  • Wind-up animation 0.3–0.8 sec before damage frame; color VFX consistent across enemies.
  • Designer doc: every unfair hit needs preceding readable cue.

Group tactics

  • Squad leader assigns flanking slots; avoid all agents same cover point via EQS scoring.

Steering behaviors (кратко)

  • Seek / Flee — velocity toward/away target.
  • Arrive — decelerate near goal.
  • Separation — push apart neighbors; prevents stacking in doorways.
  • Flocking — crowd civilians; lower tick rate acceptable.

Combine with NavMesh path for final velocity.


Wave Function Collapse — шаги

  1. Define tile set with edge labels (N, E, S, W sockets).
  2. Initialize grid superposition all tiles legal.
  3. Collapse lowest entropy cell; propagate constraints neighbors.
  4. Contradiction → backtrack or restart seed.
  5. Post-process: spawn enemies by room type rules.

Used in indie: Bad North-style layouts, 2D platform tile maps.


Dungeon generation graph algorithm

rooms = random_count(5, 12)
place rooms AABB no overlap
graph = minimum_spanning_tree(rooms)
add random extra edges for loops
for each edge: carve corridor L-shaped or straight
place keys before locks via topological sort
validate reachability start to boss

Roguelike staple; guarantees solvable with key-door ordering.


ML matchmaking pipeline

  1. Collect match outcomes, player stats, ping.
  2. Feature engineering: rolling KDA, role, party size.
  3. Train skill model offline; deploy versioned on server.
  4. A/B test queue time vs match quality metrics.
  5. Monitor smurf reports separate channel.

TrueSkill: Bayesian update; good for team games. ELO simpler for 1v1.


Unreal EQS пример (conceptual)

Query: Find cover from Player
Generator: Points in ring around self
Test: Trace hide from Player (visibility score)
Test: Distance prefer 800–1500 uu
Scoring: highest hide wins

Used in shooter AI cover selection alongside BT task Move To EQS Result.


Будущие тrends (2025–2030)

  • Authoring tools: BT/GOAP assisted by LLM for draft trees — human verify.
  • NPC memory: lightweight structured memory, not raw chat logs.
  • Procedural narrative: grammar-based + human curation beats pure LLM quests.
  • Regulation: EU AI Act transparency for certain game features.
  • Crowd simulation: GPU/MassEntity scale in UE5.
  • Player co-pilot AI: accessibility and creative mode assistants.
  • Synthetic playtesting: bots explore NavMesh for stuck geometry — QA aid.

FAQ

Нужен ли LLM для умных NPC? Нет; scripted BT + barks достаточно для 95% AAA истории.

FSM или BT? FSM для простого; BT для масштабируемого combat AI.

Что такое EQS в Unreal? Environment Query System — context-aware point picking (cover, flank).

GOAP dead? Niche но жив в sim/sandbox; BT чаще default.

NavMesh каждый frame? Bake static; dynamic obstacles selective rebuild.

ML-Agents для продакшена? Research и prototypes; shipped enemy AI редко pure RL.

Как сделать бота похожим на игрока? Record replays, imitation learning, cap skill on server.

LLM локально без API? Small models on PC growing; quality vs cloud tradeoff.

Proc gen seed в speedrun? Fixed seed category; random for casual.

WFC over-constrained? Relax constraints or backtrack; pre-validate tile set.

Дополнительные вопросы по GOAP

Сколько actions в GOAP planner? Десятки, не сотни; иначе search explosion.

Preconditions в GOAP vs BT conditions? GOAP symbolic world state; BT checks per tick on blackboard.

Planner каждый frame? Нет; replan on state change или cooldown 0.5–2 sec.

Дополнительные вопросы по процедурке

Perlin seed в multiplayer? Host seed sync; clients deterministic gen.

Biome boundaries? Blend noise layers; avoid hard seams with transition tiles.

AI replace game designers? No; tools change workflow, гейм-дизайн остаётся human-led.

Anticheat ML false positives? Human review + appeal; never autoban solely on model.

TrueSkill vs ELO? TrueSkill handles teams/uncertainty; Xbox Live classic.

Behavior tree tick rate? Every frame or 10 Hz for distant AI — LOD for brains.

Blackboard thread-safe? Main thread only unless documented locks.

Steering vs NavMesh? NavMesh path + local steering avoidance combine.

AlphaGo связь с играми? Motivated RL research; chess in games uses minimax not neural at runtime usually.

Generative quests shipping? Experiments in indie; AAA waits QA control.

Voice AI NPC? Latency and lip-sync hard; pre-baked preferred.

AI tools in Unity 6? Assistant for code; not replacement for BT editor.

Jobs AI programmer entry? C++ gameplay + one shipped BT project strong start.

Ethics board at studio? Growing for generative content policies.

Player data for ML training? Consent, anonymize, legal review.

Future of game AI hiring? Gameplay AI stable demand; hype LLM roles volatile.

Best GDC talk start? Building the AI of F.E.A.R. — Jeff Orkin.

Link utility AI and difficulty? Utility can score flee higher on Easy — designer curves.

NavMesh in multiplayer? Server authoritative path or sync waypoints.

Procedural + accessibility? Ensure color-blind safe markers in generated levels — test seeds.


См. также


Содержание