{"id":855,"date":"2013-04-19T16:30:20","date_gmt":"2013-04-19T20:30:20","guid":{"rendered":"http:\/\/shiningrocksoftware.com\/?p=855"},"modified":"2013-04-19T16:30:20","modified_gmt":"2013-04-19T20:30:20","slug":"tech-stuff-2-ai","status":"publish","type":"post","link":"https:\/\/shiningrocksoftware.com\/2013-04-19-tech-stuff-2-ai\/","title":{"rendered":"Tech Stuff #2: AI"},"content":{"rendered":"

When I started this game, I knew AI was going to be a hard thing for me. I'm used to writing graphics code and low level system where the code execution paths are nearly the same every frame. For all the games I worked on in the past, I never looked into how the NPCs made decisions.<\/p>\n

I wanted the people in the game to do all manner of tasks. They'd live in houses, walk to their jobs, do the work, cut down a tree, go eat lunch, collect firewood, and go get a new shirt from the market. I had no idea how to make this happen or where to start. I tinkered with getting the AI to do simple things, and then built on that.<\/p>\n

I broke down all the things an AI could do into simple core tasks, which I call 'Actions'. These are tasks such as moving to a location, picking up an object, storing or retrieving something out of inventory, creating new objects, or playing animations.<\/p>\n

The AI then maintains a queue of actions to complete. Lets say I want to get an AI to collect food from storage and bring it to their home. The code would look something like this:<\/p>\n

\r\n\/\/ head to the storage facility or market\r\nai.AddAction(MoveTo(storageLocation, Animation_Walk));\r\n\r\n\/\/ get something out of inventory and display it.\r\nai.AddAction(PlayAnimation(Animation_BendDown));\r\nai.AddAction(RetrieveFromStorage(storageLocation, foodType));\r\nai.AddAction(PlayAnimation(Animation_StandUp));\r\n\r\n\/\/ go home\r\nai.AddAction(MoveTo(homeLocation, Animation_Walk));\r\n\r\n\/\/ drop inventory\r\nai.AddAction(PlayAnimation(Animation_BendDown));\r\nai.AddAction(DepositInventory(homeLocation));\r\nai.AddAction(PlayAnimation(Animation_StandUp));\r\n<\/pre>\n

Each item in the queue is executed until it finishes - MoveTo completes when the AI gets to the target. PlayAnimation completes once the animation finishes. Other actions like DepositInventory execute immediately and the next action is run.<\/p>\n

I call these chains of execution 'Behaviors'. The game has a lot of different behaviors, from how to hunt animals, to how to work at a building and use one resource to make another resource. Adding new behaviors and actions is easy. I could make two people walk toward each other, play an animation and play audio that shows they're talking to each other, then go about their business with just a few lines of code. (But I'd have to make the animation and audio first....)<\/p>\n

This came out as a very nice system and is very extensible. But then there is the hard part. How does the AI choose which behavior it should be using at any given time? <\/p>\n

Each AI has a set of needs that may or many not be urgent. They might need to stock their home with food or firewood. They might be sick and need a doctor. They might be cold and need to go home and warm up, or hungry and need to eat. They might have low health and decide to visit an herbalist. They AI might be a child and depend on parents for keeping the home stocked. <\/p>\n

In the best case all needs are met and the AI should just do some work so the town can prosper - if they have a specific profession and workplace this is easy - but if there is no work available they need to help around town with general labor. <\/p>\n

These things don't sound like nice programming tasks. This is where I ask myself if I've made too complex of a simulation....<\/p>\n

But to deal with it I turned to something I do know. State machines. There are different states of working versus attaining needs, and there are different versions of each of those for when an AI is a child, student or adult. Each time the action queue is empty, it signals the AI to make a new choice or change states based on needs.<\/p>\n

The needs are prioritized based on severity - freezing to death is more important to take care of compared to getting a new tool. Deciding what job to work on is handled simply by ranking jobs based on urgency and distance from the AI. <\/p>\n

Each state is simple. Here's what the normal and attain needs states looks like:<\/p>\n

\r\nvoid State_AdultWorking()\r\n{\r\n  \/\/ check to see if the ai is doing something\r\n  if (IsBusy())\r\n    return;\r\n\r\n  \/\/ do more work, idle, or change state\r\n  if (AreNeedsMet())\r\n  {\r\n    if (!GetNewTask())\r\n      ChangeState(AdultIdle);\r\n  }\r\n  else\r\n    ChangeState(AdultAttainNeeds);\r\n}\r\n\r\nvoid State_AdultAttainNeeds()\r\n{\r\n  if (IsBusy())\r\n    return;\r\n\r\n  if (AreNeedsMet())\r\n    ChangeState(AdultWorking);\r\n  else if (IsFreezing() && CanAttainWarmth())\r\n    ChangeState(State_AttainWarmth);\r\n  else if (IsSick() && CanAttainDoctor())\r\n    ChangeState(State_AttainDoctor));\r\n  else if (IsHungry() && CanAttainFood())\r\n    ChangeState(State_AttainFood);\r\n  else if (IsUnhealthy() && CanAttainHealth())\r\n    ChangeState(State_AttainHealth);\r\n  else if (!HasClothing() && CanAttainClothing())\r\n    ChangeState(State_AttainClothing);\r\n  else if (!HasTools() && CanAttainTools())\r\n    ChangeState(State_AttainTools);\r\n  .... \/\/ lots more needs omitted.\r\n  else\r\n    GetNewTask(); \/\/ couldn't attain any needs! try doing work instead, will retry later\r\n}\r\n<\/pre>\n

I implemented all this and then decided this wasn't really AI - it's a conglomeration of state machines, fifos, priority queues, and a few conditionals. But magically when hundreds of AI's are running the state machine and executing behaviors, it looks awesome and the town is alive with activity. <\/p>\n

This system could easily be extended to give the AI's more personality. I could have different states for lazy workers that idle more often than not, or people that won't work when their health is low or if they have to walk too far. But for now everyone is a well behaved, hard-working citizen.<\/p>\n","protected":false},"excerpt":{"rendered":"

When I started this game, I knew AI was going to be a hard thing for me. I'm used to writing graphics code and low level system where the code execution paths are nearly the same every frame. For all the games I worked on in the past, I never looked into how the NPCs […]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[],"_links":{"self":[{"href":"https:\/\/shiningrocksoftware.com\/wp-json\/wp\/v2\/posts\/855"}],"collection":[{"href":"https:\/\/shiningrocksoftware.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/shiningrocksoftware.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/shiningrocksoftware.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/shiningrocksoftware.com\/wp-json\/wp\/v2\/comments?post=855"}],"version-history":[{"count":0,"href":"https:\/\/shiningrocksoftware.com\/wp-json\/wp\/v2\/posts\/855\/revisions"}],"wp:attachment":[{"href":"https:\/\/shiningrocksoftware.com\/wp-json\/wp\/v2\/media?parent=855"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/shiningrocksoftware.com\/wp-json\/wp\/v2\/categories?post=855"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/shiningrocksoftware.com\/wp-json\/wp\/v2\/tags?post=855"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}