Off Topic > Off Topic
Programming Megathread
<< < (108/241) > >>
Waru:
i got it like this

Foxscotch:
are you only doing it once?
McJob:

--- Code: ---/********************** AI SYSTEM - PARENT CLASS - v0.01 **********************/
 
//Made By: Ben "McJobless" Steenson
//Date: 2016-03-15T12:50:00+11:00
 
//This parent class for the AI System holds the basic functionality that all AI systems will utilise.
//Most of the things inside this parent class should be overriden (including the Data struct using the "new" keyword to hide the default).
//Anything that is core to this system and cannot be overriden is marked as private; everything else is protected (as only derived classes should need access).
 
//AI FRAME UPDATE PHASES:
//1) Initialisation: Methods are assigned to delegates, default behaviour lists are filled and the default state of the AI unit is all filled in the Awake() method.
//2) StateController() is run, and any state-specific behaviour (such as assigning timers) can be run.
//3) At any pointer, using the CurrentState accessor will run StateSwitcher(), which handles transitions between states.
//4) Once States are dealt with, TaskController() runs and will attempt to fill an empty taskStack or run the top task in the stack and then read it if required by the task conditions.
 
//Changes to make:
//0) Need a way to disable AI thinking; would be great if AI outside of rendering distance are automatically disabled.
//1) AI system has no clean way to handle task INTERRUPTIONS (especially for things like gravity-defying rotations).
//2) Need to verify data accessibility (such as adding accessors for the data containers) and also make certain parts easier to extend.
//3) Integrate the Seeker task-generation system in whatever form that may come.
//4) Node-Based Pathfinding.
//5) Make a simple demo of an AI-driven unit following an object which moves randomly around the world.
 
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class ParentAI : MonoBehaviour
{
    /* VARIABLE DEFINITIONS */
 
    //Data-Type Definitions
    protected enum AIStates { IDLE, MOVEMENT };                                                             //All states that an AI can exist in; I'd like to make this extendible so no edits need to be made to this file by a user.
    protected delegate bool Task();                                                                         //An AI-specific function that can return true if it needs to be replaced on the stack.
    protected struct AIData                                                                                 //A struct which holds AI-specific data (such as health and speed). Will likely be replaced with another form down the track.
    {                                                                                                       //The struct is designed to be overriden/hidden with the "new" keyword in derived classes.
        public float sightDistance;
        public AIData(float sD) { sightDistance = sD; }
    }
 
    //Data Containers - THESE SHOULD HAVE ACCESSORS TO PREVENT UNAUTHORISED ACCESS!!!
    protected Dictionary<AIStates, List<Task>> defaultTasks = new Dictionary<AIStates, List<Task>>();        //Defines which tasks should be returned on the stack if it's empty based on current state; allows multiple tasks to be imported at one time.
    protected Stack<Task> taskStack = new Stack<Task>();                                                    //This stack holds the tasks that the AI will attempt to complete in order from top priority (last in, first out) to lowest.
 
    //Variables: State Accessor
    private AIStates currentState = AIStates.IDLE;                                                          //Holds the current state of the AI, which can change certain behaviours and conditions.
    protected AIStates CurrentState                                                                         //Accessor is used to clear the task list (interrupts should go here) and run the transition manager (StateSwitcher()) before directly changing the state.
    {
        get { return currentState; }
        set
        {
            taskStack.Clear();
            StateSwitcher(value);
            currentState = value;
        }
    }
 
    /* METHOD DECLARATIONS */
 
    //Technically these are method definitions, but they're empty in this parent class and must be filled out in derived classes.
    protected virtual void StateController() { }
    protected virtual void StateSwitcher(AIStates toState) { }    
 
    /* METHOD DEFINITIONS */
 
    //Run once per frame; user should call this base version before/after their update code to run the task controller.
    protected virtual void Update()
    {
        StateController();
        TaskController();
    }
 
    //Handles all Task-related processing; this should never need to be modified and so it private and only handled in this base class.
    private void TaskController()
    {
        //Temporarily save the current task in case it needs to be repeated later.
        Task tempTask = null;
        if (taskStack.Count > 0) tempTask = taskStack.Peek();
 
        //If we haven't completed any relevant goals (and therefore aren't just sitting idle), run the task checks.
        if (taskStack.Count == 0) { foreach (Task item in defaultTasks[currentState]) if (item != null) taskStack.Push(item); }     //If the task stack is empty, fill the stack with the default tasks based on the current state of the AI unit (ignore any null tasks).
        else if (taskStack.Pop()()) taskStack.Push(tempTask);                                                                       //Run the top task; if it returns true it needs to be repeated, so read task to the stack.
    }
}

--- End code ---

My AI system is taking shape.

I've got a functioning child AI unit, but I won't show it until it's been cleaned up; it's using extremely messy pathfinding code which I'm not proud of yet.
$trinick:
You've got more comments than you've got code, bro.
McJob:

--- Quote from: $trinick on March 15, 2016, 07:08:52 PM ---You've got more comments than you've got code, bro.

--- End quote ---
I'm demoing this code to my college of people who want but cannot program, so I need to really intricately explain every little detail.

I think the point here is that AI is really simple once you get the logic down.
Navigation
Message Index
Next page
Previous page

Go to full version