[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CS22VFERTE39NRC4CCY6EG":3,"skill-same:01M7CS22VFERTE39NRC4CCY6EG":50},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":27,"commitSha":28,"skillDirectory":29,"forksCount":30,"repositoryHtmlUrl":31,"repositoryHomepageUrl":32,"ownerHtmlUrl":33,"ownerBlogUrl":6,"ownerDescription":34,"updatedAt":35,"install":36,"resources":49},"01M7CS22VFERTE39NRC4CCY6EG","game-state-machines-and-ai",null,"Use when adding character\u002Fenemy\u002Fgame-flow states or NPC behaviour - explicit transition tables instead of flag soup, hierarchical and pushdown machines, behaviour trees per engine, navmesh pathfinding, AI tick budgets, and table-driven tests.","makifbaysal\u002Ftasktrooper","makifbaysal","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F25031940?v=4","01M7CRG3ZCSYZSSEVDMW3DEYC8","Mehmet Akif Baysal","01M7CRG401FJ8YAXH5ER730XYV",122,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fgame-developer\u002Fskills\u002Fgame-state-machines-and-ai\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: game-state-machines-and-ai\ncategory: gameplay\ndescription: Use when adding character\u002Fenemy\u002Fgame-flow states or NPC behaviour - explicit transition tables instead of flag soup, hierarchical and pushdown machines, behaviour trees per engine, navmesh pathfinding, AI tick budgets, and table-driven tests.\ntech_stack: Game core\nsource: informed by Robert Nystrom's Game Programming Patterns (State chapter) and the Unity, Godot and Unreal AI\u002Fnavigation docs; own wording\n---\n# Game State Machines and AI\n\n## Overview\n\nCharacter controllers, enemies, menus and match flow are all state machines whether or not the code admits it. When they are written as a pile of booleans (`isJumping`, `isAttacking`, `isStunned`), illegal combinations become reachable and every new state touches every branch. Make the states and the legal transitions explicit, and test the table.\n\n**Core principle:** One current state, an explicit list of (state, event) → next state, and enter\u002Fexit hooks. Anything not in the table cannot happen.\n\n## Flags vs a table\n\n```ts\n\u002F\u002F ❌ flag soup: can be jumping AND stunned AND attacking; every rule checks every flag\nif (input.attack && !this.isStunned && !this.isDead && (!this.isJumping || this.canAirAttack)) { ... }\n\n\u002F\u002F ✅ explicit states and transitions\ntype State = \"idle\" | \"run\" | \"jump\" | \"attack\" | \"stunned\" | \"dead\";\ntype Event = \"move\" | \"stop\" | \"jump\" | \"land\" | \"attack\" | \"attackEnd\" | \"hit\" | \"recover\" | \"die\";\n\nconst transitions: Record\u003CState, Partial\u003CRecord\u003CEvent, State>>> = {\n  idle:    { move: \"run\", jump: \"jump\", attack: \"attack\", hit: \"stunned\", die: \"dead\" },\n  run:     { stop: \"idle\", jump: \"jump\", attack: \"attack\", hit: \"stunned\", die: \"dead\" },\n  jump:    { land: \"idle\", hit: \"stunned\", die: \"dead\" },\n  attack:  { attackEnd: \"idle\", hit: \"stunned\", die: \"dead\" },\n  stunned: { recover: \"idle\", die: \"dead\" },\n  dead:    {},\n};\n\nexport class Fsm {\n  constructor(public state: State, private hooks: Hooks) {}\n  send(e: Event): boolean {\n    const next = transitions[this.state][e];\n    if (!next) return false;\n    this.hooks.exit?.(this.state); this.state = next; this.hooks.enter?.(next);\n    return true;\n  }\n}\n```\n\nThe same shape in C# is an `enum` plus a `Dictionary\u003C(State, Event), State>` built once; in GDScript a `Dictionary` of dictionaries or one node per state (godot-gdscript-patterns); in Unreal a `UENUM` with a switch, or StateTree for larger designs.\n\n## Testing the table\n\n```ts\nit.each([\n  [\"idle\", \"jump\", \"jump\"], [\"jump\", \"attack\", \"jump\"],   \u002F\u002F no air attack in this design\n  [\"stunned\", \"move\", \"stunned\"], [\"dead\", \"recover\", \"dead\"],\n  [\"attack\", \"hit\", \"stunned\"],\n])(\"%s + %s → %s\", (from, ev, to) => {\n  const fsm = new Fsm(from as State, {});\n  fsm.send(ev as Event);\n  expect(fsm.state).toBe(to);\n});\n```\n\nCover every row that matters to the design plus the rejections (\"dead ignores everything\"). A new state lands with its rows in this test.\n\n## Bigger machines\n\n- **Hierarchical:** shared transitions (hit → stunned, die → dead) live on a parent \"alive\" state instead of being copied into every child.\n- **Pushdown (a stack):** pause and nested menus — push `paused`, pop back to exactly where play was.\n- **Concurrent:** movement and weapon as two machines rather than the product of their states.\n- **Timed states:** a state that ends after 0.4 s counts seconds from `enter`, on the simulation clock (game-loop-and-time).\n\n## Behaviour trees and their alternatives\n\nReach for a behaviour tree when an NPC has many prioritised goals with conditions (patrol, investigate, chase, flee, heal). Use the one the repository already has:\n\n| Engine | Built in \u002F common |\n|---|---|\n| Unreal | Behavior Trees + Blackboard + EQS; StateTree for state-based logic |\n| Unity | Behavior package (`com.unity.behavior`); third-party trees if already present |\n| Godot | Addons such as LimboAI or Beehave; a node-based state machine for simple NPCs |\n| Bevy | Crates such as `big-brain` (utility AI) or a hand-rolled tree |\n| Web | A small hand-rolled tree, or the repository's library |\n\nRules either way: leaf actions are small and testable alone, the tree reads a blackboard instead of reaching into scene objects, conditions are cheap, and running actions can be aborted cleanly when a higher-priority branch wins. Utility AI (score each option, pick the best) suits needs-driven NPCs; keep its curves in data (data-driven-gameplay-design).\n\n## Navigation\n\n| Engine | Navmesh and agents |\n|---|---|\n| Unity | AI Navigation package: `NavMeshSurface` (bake), `NavMeshAgent.SetDestination` |\n| Godot | `NavigationRegion2D\u002F3D` + `NavigationAgent2D\u002F3D`; query only after the navigation map has synced (wait one physics frame after load) |\n| Unreal | `NavMeshBoundsVolume`, `AAIController::MoveToLocation\u002FMoveToActor`, async path queries |\n| Web | `recast-navigation` (WASM) or grid A* for 2D |\n| Bevy | Crates such as `vleue_navigator` or `oxidized_navigation` |\n\n- Do not re-path every frame: re-path when the target moved more than a threshold or on a timer, and cap path requests per frame (time-slicing).\n- Grid A* for tile games: precompute the grid, reuse open\u002Fclosed buffers, and early-out on unreachable targets.\n- Avoidance (RVO) and path following are separate concerns from path finding.\n\n## AI budget\n\n- Perception (line-of-sight, hearing) at 5–10 Hz, staggered across agents so they do not all think on the same frame.\n- Far or off-screen agents think less often (level of detail for AI).\n- Measure the AI system's frame cost against its slice of the budget (game-performance-budget).\n- Seed any randomness in decisions from the simulation's RNG, so a bug report with a seed reproduces.\n\n## Common Mistakes\n\n- Transition logic spread across `Update` branches instead of one table.\n- State entry effects (play animation, start timer) duplicated at every place that changes the state — put them in `enter`.\n- An animation state machine (Animator, AnimationTree, Anim Blueprint) used as the gameplay authority — it presents the gameplay state, it does not own it.\n- Every agent calling the pathfinder every frame.\n\n## Red Flags\n\n- Three or more booleans describing what a character is \"doing\".\n- A new state added with no test rows.\n- An `if (state == X)` check outside the state machine that decides a transition.\n","# Game State Machines and AI\n\n## Overview\n\nCharacter controllers, enemies, menus and match flow are all state machines whether or not the code admits it. When they are written as a pile of booleans (`isJumping`, `isAttacking`, `isStunned`), illegal combinations become reachable and every new state touches every branch. Make the states and the legal transitions explicit, and test the table.\n\n**Core principle:** One current state, an explicit list of (state, event) → next state, and enter\u002Fexit hooks. Anything not in the table cannot happen.\n\n## Flags vs a table\n\n```ts\n\u002F\u002F ❌ flag soup: can be jumping AND stunned AND attacking; every rule checks every flag\nif (input.attack && !this.isStunned && !this.isDead && (!this.isJumping || this.canAirAttack)) { ... }\n\n\u002F\u002F ✅ explicit states and transitions\ntype State = \"idle\" | \"run\" | \"jump\" | \"attack\" | \"stunned\" | \"dead\";\ntype Event = \"move\" | \"stop\" | \"jump\" | \"land\" | \"attack\" | \"attackEnd\" | \"hit\" | \"recover\" | \"die\";\n\nconst transitions: Record\u003CState, Partial\u003CRecord\u003CEvent, State>>> = {\n  idle:    { move: \"run\", jump: \"jump\", attack: \"attack\", hit: \"stunned\", die: \"dead\" },\n  run:     { stop: \"idle\", jump: \"jump\", attack: \"attack\", hit: \"stunned\", die: \"dead\" },\n  jump:    { land: \"idle\", hit: \"stunned\", die: \"dead\" },\n  attack:  { attackEnd: \"idle\", hit: \"stunned\", die: \"dead\" },\n  stunned: { recover: \"idle\", die: \"dead\" },\n  dead:    {},\n};\n\nexport class Fsm {\n  constructor(public state: State, private hooks: Hooks) {}\n  send(e: Event): boolean {\n    const next = transitions[this.state][e];\n    if (!next) return false;\n    this.hooks.exit?.(this.state); this.state = next; this.hooks.enter?.(next);\n    return true;\n  }\n}\n```\n\nThe same shape in C# is an `enum` plus a `Dictionary\u003C(State, Event), State>` built once; in GDScript a `Dictionary` of dictionaries or one node per state (godot-gdscript-patterns); in Unreal a `UENUM` with a switch, or StateTree for larger designs.\n\n## Testing the table\n\n```ts\nit.each([\n  [\"idle\", \"jump\", \"jump\"], [\"jump\", \"attack\", \"jump\"],   \u002F\u002F no air attack in this design\n  [\"stunned\", \"move\", \"stunned\"], [\"dead\", \"recover\", \"dead\"],\n  [\"attack\", \"hit\", \"stunned\"],\n])(\"%s + %s → %s\", (from, ev, to) => {\n  const fsm = new Fsm(from as State, {});\n  fsm.send(ev as Event);\n  expect(fsm.state).toBe(to);\n});\n```\n\nCover every row that matters to the design plus the rejections (\"dead ignores everything\"). A new state lands with its rows in this test.\n\n## Bigger machines\n\n- **Hierarchical:** shared transitions (hit → stunned, die → dead) live on a parent \"alive\" state instead of being copied into every child.\n- **Pushdown (a stack):** pause and nested menus — push `paused`, pop back to exactly where play was.\n- **Concurrent:** movement and weapon as two machines rather than the product of their states.\n- **Timed states:** a state that ends after 0.4 s counts seconds from `enter`, on the simulation clock (game-loop-and-time).\n\n## Behaviour trees and their alternatives\n\nReach for a behaviour tree when an NPC has many prioritised goals with conditions (patrol, investigate, chase, flee, heal). Use the one the repository already has:\n\n| Engine | Built in \u002F common |\n|---|---|\n| Unreal | Behavior Trees + Blackboard + EQS; StateTree for state-based logic |\n| Unity | Behavior package (`com.unity.behavior`); third-party trees if already present |\n| Godot | Addons such as LimboAI or Beehave; a node-based state machine for simple NPCs |\n| Bevy | Crates such as `big-brain` (utility AI) or a hand-rolled tree |\n| Web | A small hand-rolled tree, or the repository's library |\n\nRules either way: leaf actions are small and testable alone, the tree reads a blackboard instead of reaching into scene objects, conditions are cheap, and running actions can be aborted cleanly when a higher-priority branch wins. Utility AI (score each option, pick the best) suits needs-driven NPCs; keep its curves in data (data-driven-gameplay-design).\n\n## Navigation\n\n| Engine | Navmesh and agents |\n|---|---|\n| Unity | AI Navigation package: `NavMeshSurface` (bake), `NavMeshAgent.SetDestination` |\n| Godot | `NavigationRegion2D\u002F3D` + `NavigationAgent2D\u002F3D`; query only after the navigation map has synced (wait one physics frame after load) |\n| Unreal | `NavMeshBoundsVolume`, `AAIController::MoveToLocation\u002FMoveToActor`, async path queries |\n| Web | `recast-navigation` (WASM) or grid A* for 2D |\n| Bevy | Crates such as `vleue_navigator` or `oxidized_navigation` |\n\n- Do not re-path every frame: re-path when the target moved more than a threshold or on a timer, and cap path requests per frame (time-slicing).\n- Grid A* for tile games: precompute the grid, reuse open\u002Fclosed buffers, and early-out on unreachable targets.\n- Avoidance (RVO) and path following are separate concerns from path finding.\n\n## AI budget\n\n- Perception (line-of-sight, hearing) at 5–10 Hz, staggered across agents so they do not all think on the same frame.\n- Far or off-screen agents think less often (level of detail for AI).\n- Measure the AI system's frame cost against its slice of the budget (game-performance-budget).\n- Seed any randomness in decisions from the simulation's RNG, so a bug report with a seed reproduces.\n\n## Common Mistakes\n\n- Transition logic spread across `Update` branches instead of one table.\n- State entry effects (play animation, start timer) duplicated at every place that changes the state — put them in `enter`.\n- An animation state machine (Animator, AnimationTree, Anim Blueprint) used as the gameplay authority — it presents the gameplay state, it does not own it.\n- Every agent calling the pathfinder every frame.\n\n## Red Flags\n\n- Three or more booleans describing what a character is \"doing\".\n- A new state added with no test rows.\n- An `if (state == X)` check outside the state machine that decides a transition.\n",{"name":5,"source":24,"category":25,"tech_stack":26,"description":7},"informed by Robert Nystrom's Game Programming Patterns (State chapter) and the Unity, Godot and Unreal AI\u002Fnavigation docs; own wording","gameplay","Game core","main","910394a0b6db9fc8c9a8f36328ec421d3ebd8b38","catalog\u002Fagents\u002Fgame-developer\u002Fskills\u002Fgame-state-machines-and-ai",18,"https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper","https:\u002F\u002Ftasktrooper.ai","https:\u002F\u002Fgithub.com\u002Fmakifbaysal","Senior Software Developer","2026-11-15 04:50:29",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add makifbaysal\u002Ftasktrooper --skill game-state-machines-and-ai",{"tool":42,"command":43},"bunx","bunx skills add makifbaysal\u002Ftasktrooper --skill game-state-machines-and-ai",{"tool":45,"command":46},"pnpm","pnpm dlx skills add makifbaysal\u002Ftasktrooper --skill game-state-machines-and-ai","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fgame-developer\u002Fskills\u002Fgame-state-machines-and-ai\u002FSKILL.md",true,[],[51,57,64,71,78,85],{"skillNo":52,"name":53,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":19},"01M7CSVEPQW6J6TD6CS2T5FPNZ","visual-craft","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fvisual-craft\u002FSKILL.md",[],[],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M7CSVAQG91ETHQ0HBNZDG5FR","ux-copy","Use when you write any words a user reads in a mockup or a hand-off - content language and voice, buttons, labels, errors, empty states, confirmations, numbers and dates, and the longest-string check","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fux-copy\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M7CSV6H0J38659NDXHJQ8396","screen-mockup-html","Use when you draw screens as the design task's HTML mockup - ONE canvas document holding every screen and every variant side by side, the sanitizer-safe recipe, phone and wide frames, the states grid, static control states, and the loopback self-check with screenshots at 375, 768 and 1440 attached to the task","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fscreen-mockup-html\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M7CSV3JFRF3BM3XK52M7YEYR","performance-awareness","How the performance score moves for your role. Use when the score context shows a declining trend, or before handing off work you have not self-checked against every criterion.","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fperformance-awareness\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M7CSTZDH00YRF5SCT7BRT9QD","design-variants","Use when a screen design needs variants - how many, variants as side-by-side rows on the one canvas, what makes two variants genuinely different, recommending one, how the human's choice is read, and narrowing to the chosen one in revision","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fdesign-variants\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7CSTV6P3SM3PAE28DB0RF77","design-system-authoring","Use when you derive, change or extend a design system - where tokens live per stack, the DTCG token tree, role-based names for both themes, base vs layer vs drift, the DESIGN.md section order, the inventory format, the contrast check and the lint every proposal returns","https:\u002F\u002Fgithub.com\u002Fmakifbaysal\u002Ftasktrooper\u002Fblob\u002Fmain\u002Fcatalog\u002Fagents\u002Fui-designer\u002Fskills\u002Fdesign-system-authoring\u002FSKILL.md",[],[]]