Artificial Intelligence

Ahh… This is where I shall be slamming out my AI tutorials… I’m guessing it’ll probably get moved to MX or As or somewhere… But for now… This works.

Welcome to AI 101… I will be writing a total of 5 articles on AI. or Artificial Intelligence. AI is one the hardest things to code in a game. You have to sit down and think about how you wnat to incorporate AI in your game and how it will effect. Do you wnat the computer to be really dumb or do you wnat it to mimick as much of the human brain as you can? It’s a possibility to look into…

I will be discussing 5 possible ways to place AI in your game or program.

Random AI : I will be discussing this tonight… But this uses the random function to determine what move is next and what the computer will do next with chance.

Distance AI : This is the act of using distance forumals to determine what an enemy or object should do.

Logical AI : Checkers, Chess, and Tic-Tac-Toe are just some of the games that use logical math… It steps up about 20 notches to see what will happen in the future to determine what it’ll do next.

Pathfinding AI : This should be a subject of it’s own… it’s a small version of how you can make a character think when doing pathfinding.

Math AI : How to use Math to your advantage when doing Artificial Intelligence… TEaches you some of the basic math functions that will help your ai scripts look more advanced but be faster.

And Now… I will reply with the Random AI tutorial. Thanks for reading these… I’d appreaciate only collective criticism or friendly responses to thes tutorials :slight_smile:

gods above… thanks Playmarz. We need some good posts about this subject. I look forward to reading your thoughts on the subject. (you’re right. it will probebly be moved to MX relatively quickly… but for now it works. :stuck_out_tongue: )

I can’t wait man. These tutorials are going to be INCREDIBLY useful.

cracks knuckles…
goes and gets a huge pot of coffee
stretches a bit and yawns

I guess it’s time to do some hardcoring… hehe… :slight_smile:

:: Random AI ::

When you think of Random Ai what comes to Mind… Random Numbers and random actions? Random pieces of information… Random stuff right? Well what exactly is random and how can we use it to our advantage in Flash AI… Well…

Math.random : Creates a random number from 0 to 1 that can be changed and rounded off to equal something else.

With this little fucntion right here we can explore many different possibilities. It’s like rolling a die and wondering what face will land up. You never know til you let it go. But… What use is a number from 0 to 1?! Well let’s see…

*Math.random()10;

This multiplies the number you get from 0 to 1 by ten and basically states that you can have a possibility of 0 to 10. Well. That’s great but you still have those numbers like 2.346 Well that’s pretty weird huh? hehe… Well let’s change that to something more useful…

Math.ceil and Math.floor : Two very useful functions that will :: ceil will give you the number to the whole rounding up. 1.1 would be 2… While the floor will give you a whole number while rounding down.

So…

*Math.ceil(Math.random()10); will return a whole number between 1 and 10 and
*Math.floor(Math.random()10); will return a whole number between 0 and 9.

So… Now that we know how to use random… We can use it for building AI Scripts. YaY! =)

The first thing you have to know about random AI scripts is that they are percentage based… You will have to sit down and say… Whatall do I wnat my enemy to do… Well… let’s take a small example… let’s say… You are fighting a giant ape… And you wnat him to have special attacks… Well… let’s list all the types of options he can have…

Big Ape Butt Squash
Ape Slap
Ape Roll
Ape Defense

Allright… Well… It will randomly go through and pick one of those right? Well Kind-a… Now you have to choose out of 100%… How many times do you think you’d like this to happen over the next item… Let’s say you want the ape to have a better chance of performing the Ape Slap that the Ape Roll… But it’s defense should be down low… Well…

25% - Big Ape Butt Squash
50% - Ape Slap
15% - Ape Roll
10% - Ape Defense

100%

Now that we have that taken care of… We now know that we want the ape to 50% of the time slap, 25% of the time butt squash, 15 % of the time roll and the other 10% of the time stay on defense. Well that’s all great and everything… But how do we tie up the random number thing and the percentage thing to make some big thing?!

Let’s take a look at what we have… We have a rnadom number generator that can return any whole number from 0 to whatever we specifiy and we have a list of percentages to do things. Let’s say we… Make the random number generatorcreate a random number from 0-100 and then have that choose which action to do?!

Why 100 though? Because the basics for percentages are based around 100%.

Let’s take a look at this small algorithm.


number = create random number from 0-100;

if(number is between 0 and 50)
{
   perform the ape slap;
} else if(number is between 50 and 75)
{
   perform the ape butt squash;
} else if(number is between 75 and 90)
{
   perform the ape roll;
} 
else 
{
   perform the ape defense;
}

Seems pretty simple doesn’t it? Let’s take a look at each of these algorithmic code sections and decide what rela coding would go into each section and what the final code would look like.


number = create random number from 0-100;

This states right here that we want to have a variable that will hold a random number from 0 - 100. Well we already learned about the random fucntions so let’s put that into play here…


action = Math.ceil(Math.random()*100);

Well… That wasn’t so hard now was it? I didn’t think so… :slight_smile: So… Now the next line of code…


if(number is between 0 and 50)
{
   perform the ape slap;
}

This states here that if that random number we created so happens to be in betwene the number 0 and 50 to perform this action right here…


if(action >= 0 && action < 50)
{
   ape.performAttack("slap");
}

Or course we didn’t define a function like that but it’s something that would possibly be used in a game like this. On to the next couple of lines of code.


 else if(number is between 50 and 75)
{
   perform the ape butt squash;
} else if(number is between 75 and 90)
{
   perform the ape roll;
} 

I combined the next two sections because they look basically the same except with different numbers. The one states that if the random number we specified just so happens to be in between 50 and 75 that the butt squash be performed or if the action is in between 75 and 90 that the ape roll be performed. Else if basically says that… if the first statement IF is not true then it goes on to this one and test it out again.


} else if(action >= 50 && action < 75)
{
   ape.performAttack("buttsquash");
} else if(action >= 75 && action <90)
{
   ape.performAttack("roll");
}

Now for the last couple of lines of code… This one tops it all off.


else 
{
   perform the ape defense;
}

Basically this line of code says… Well If all of the other if and elseif statements fail then I will be performed. So if the number just so happens to be 90+ then it’ll be left to the else statement.


else
{
   ape.performDefense();
}

And that’s that for random AI coding… That wasn’t as hard as you guys thought it might be is it? I didn’t think so… What does our final pieced together code look like and how can we use it in our game… well here is the code ::


action = Math.ceil(Math.random()*100);

if(action >= 0 && action < 50)
{
   ape.performAttack("slap");
} else if(action >= 50 && action < 75)
{
   ape.performAttack("buttsquash");
} else if(action >= 75 && action <90)
{
   ape.performAttack("roll");
}
else
{
   ape.performDefense();
}

Now how would I use a piece of code like this… I would most likely suggest creating a function and placing this inside of there… You could have the actions then be equal to return (“attack1”) or something like that to whatever called it. However you wanna use this is up to you… But it’s actually a very powerful and very easy way to add a sense of AI to your game.

Thank You and I hope this tutorial has proven to be useful… Please send all comments and suggestions to [email protected]

oh neato =)

gonna go experiment a bit… :beam:

It seems I should explain myself more on how to use this code in say… Your main code… Let’s take the example I used above:


action = Math.ceil(Math.random()*100);

if(action >= 0 && action < 50)
{
   ape.performAttack("slap");
} else if(action >= 50 && action < 75)
{
   ape.performAttack("buttsquash");
} else if(action >= 75 && action <90)
{
   ape.performAttack("roll");
}
else
{
   ape.performDefense();
}

Now… We have ourselves a solid piece of code… How would we use this in a game perchance though… Well… For one thing… You wouldn’t want the character to perform an action every single frame… In a 30 fps game that would be a totla of 30 actions every second… So how would be use this in a more maneagable way… Well… First off it all depends on the game… I’ll go over one possible way… The role playing game way…

With role playing games and fight scenes… You would have a wait bar that woud have to load up before you could perform the action… Well… Let’s take this snipplet of code we have and change it into soemthing a role player would most definetly be able to use…

We would first need to create a timer varaible to hold our wait timers…

waitTimer = 180; (30 fps that would be 6 seconds)

We would then have an if statement thast checked to see if the waitTimer was down to 0… If it was it would do soemthing and if it wasn’t… It would just decrease the timer by 1 every frame until it was equal to 0. But. before we really get heavily into this… What action would it be claling upon?! Well…

We need to convert what we created above into a nice fucntion… Let’s call it…

performAction();

Now perform action will be handled by a monster and so that monster’s movieclip will need to be factored in with this… And if we have multiple player targets like most rpg’s do… We will need that as well… Soo…

MovieClip.prototype.performAction(targetPC);

That states that we will be performing an action with the MovieClip we specify on the target player character we provide. So…



MovieClip.prototype.performAction(targetPC)
{
   action = Math.ceil(Math.random()*100);

   if(action >= 0 && action < 50)
   {
      this.performAttack("slap", targetPC);
   } else if(action >= 50 && action < 75)
   {
      this.performAttack("buttsquash", targetPC);
   } else if(action >= 75 && action <90)
   {
      this.performAttack("roll", targetPC);
   }
   else
   {
      this.performDefense();
   }
}


Now we can just take the timer we were tlaking about before… Set it so that every 6 seconds the ape will perform an action depending on what the random scores show. Plus we will have it choose a random character to attack.


// This will be placed in an onLoad event handler some where.
mainTimer = 180;

// The rest is handled by the onEnterFrame handlers

_root.onEnterFrame
{
   if(mainTimer == 0)
   {
      character = Math.ceil(Math.random()*numPCS);
      ape.performAction(_root["pc"+character]);
      mainTimer = 180;
   }
   else
   {
      mainTimer--;
   }
}

And that’s all folks… That’s how you would place a small snipplet of Random Ai code in an RPG type game… or course there are alot more things you’d have to consider when doign this but for the sake of leaving that up to other tutorials and sticking with the subject I won’t talk about them here…

Take Care and Good Luck
Marz : [email protected]

great info playa !! thanks :slight_smile:

by the way … :sigh:

*Math.ceil(Math.random()10); will return a whole number between 0 and 10

Could we get these things in a proper Kirupa tutorial set? I think that a lot of people would want to read them (myself included) so putting them on the main site seems like a good idea to me. :slight_smile:

Maybe we should ask the boss man? :hat:

I’ll work with Playmarz on it. I think he just wanted to write “freeform” hence the location of the post. We’ll get them all formated once he’s got everything down.

“artificial intelligence is better than none.”

nice stuff :)…

“artificial intelligence is better than none.”
:stuck_out_tongue:

I can convert these all to the format then… But for now… I just wanted to like david stated “freeform” these…

If we ever get these on the main, we can delete these posts then :slight_smile:

:wink:

And btw KAx… I did have that down… Are you asking why it’s still 0? Because if I’m thinking… 0*10 would be 0 then… shrugs… it might make a random number in between and not on those numbers… Hmm… :-p

Math.ceil(Math.random()*10); will never return 0 :sigh:

Allright… Yeha I wasn’t too sure about that one… Okay I changed it… Thanks kax.

Gimme some creds… it was late last night I’m bound to make some mistakes :-p heh

i told you … great info =)

i really want to read the whole thing when it’s finished :wink:

Yep Playa, you wrote this around 3am…lol. I am surprised there aren’t more mistakes :crazy:

Time to spit out tutorial number 2…

:: Distance AI ::

Out of all the Ai’s you’d less suspect to be one would be this. Why would this be an AI, how to use this AI and what are some of the advantages and disadvantages of this AI system will be discussed below.

The first thing we need to know is what exactly is distance AI and how does it work? Well…

Distance AI : Is an AI system that uses locations relative to the player character (PC) and then decides on a set number of actions based on how far away the character is.

It’s typically found in most beat em up games like Double Dragon and Final Fight. It can prove to be very useful in other situations as well…

Finding Distance

The easiest and best method for finding diatance is the system of relativity.

PC._x - Enemy._x;
PC._y - Enemy._y;

That would find the distance between the PC and the enemy in both the x and y directions… Notice though… That sometimes one of these values can be negative or can be positive. We can take care of that later then.

So we have ourselvs a set of equations finally… But what use are they and how would we use this to our advantage… Well… There are two different methods we could use to change the 2 equatiosn above into something useful…

The first way is relative math.


xdistance = pc._x - enemy._x;
ydistance = pc._y - enemy._y;
distance = (xdistance + ydistance) / 2;

That would give us a well rounded number that could equal the distance… But what’s wrong with this picture… Well if you think about it, if we take the pc and the enemy… And draw a line in between them… The line probably won’t be horizontal or vertical all the time. It’ll be angled… So the number this system spits out will be a rounded off number. It’s very useful for those types of games where getting faster is better instead of getting exact…

The next system is the exact math version…


xdistance = pc._x - enemy._x;
ydistance = pc._y - enemy._y;
distance = Math.sqrt(Math.abs((xdistance*xdistance)+(ydistance*ydistance)));

Wow… That’s a bigger chunk of code… But why… And what?! Huh? hehehe… I’ll explain now…

When you have an angled line you can use the Pythagorean Theorum to figure out how long that line is exactly. By taking the two sides that we know… a(x) and b(y) and popping them in the following equation. We can figure it out then…

c2 = a2+b2;
-= or =-
c = Square Root((a * a) + (b * b));

Allright. Well that’s not so difficult looking then right? Well. Squareroot only deals wiht positive numbers so… We then have to use the Math.abs function… Also… We needthe actual square root fucntion that we will be using.

Math.abs() : Takes the number in its argument and gives you the absolute value of it…

-20 would be 20
20 would still be 20

Math.sqrt() : Takes the number in its argument line and returns th square root of that number.

25 would be 5
100 would be 10

So… Then to get the entire equations right…

distance = Math.sqrt(Math.abs((xdistancexdistance)+(ydistanceydistance)));

Now… we have two basic methods for finding out the distance from your player character to the enemy… Which is the best one to choose for your game… Well unless you are trying o find “exact” locations. I’d suggest just using the relative equation. It’ll be alot faster running and it’ll save a lot of testing hassle in the long run.

Let’s use the relative one for our example. Now… We have something that will give us the distance… Woohooo… That’s what we wanted right?.. Right! So let’s continue on.

We can use this number to tell us how far away the enemy might be and we can also use the xdistance and ydistance values to determine if he’s north, south, east or west of my character. :slight_smile:

Now say I wanted my enemy to do the following actions at these distances.

Far : Throw Rocks
Mid : Defend
Close : Punch

Easy enough. Let’s think about how we would do that… Well… If the distance was over 200 pixels. That would be pretty far… And if it was between 100 and 200 that could be classified as mid range… And then the rest would be close range… Let’s write a quick algorithm to see if we can figure this out.


xdistance = player x location - enemy x location;
ydistance = player y location - enemy y location;
distance = (xdistance + ydistance)/2;

if(distance is far ranged (200 pixels+))
{
   have enemy perform the rock throw;
} else if (distance is mid range (100 px to 200 px))
{
   have the enemy go into defensive position;
} 
else
{
   have the enemy punch your guy;
}

Now that looks fine and dandy to most people… But then… What do we wanna do if say… the player is on the right and the guy is punching or throwing rocks on the left… Well… We need to determine which way the player is in relation to the enemy.

If xdistance is a negative number. That means that the enemy’s x location was higher than the players. xdistance = 200 - 300; That means that the enemy is to the right of the character.

If xdistance is a positive number. That means that the enemy’s x location was lower than the players. xdistance = 200 - 100; That means that the enemy is to the left of the character.

If ydistance is a negative number. That means that the enemy’s y location was higher than the players. ydistance = 200 - 300; That means that the enemy is to the bottom of the character.

If ydistance is a positive number. That means that the enemy’s y location was lower than the players. ydistance = 200 - 100; That means that the enemy is to the top of the character.

Well… Now that we know how to find out where the enemy is direction wise. We can figure out which way to have the enemy throw rocks or punch. Let’s throw this in the algorithm we created above. We won’t have to check y locations because we don’t care whether the enemy throws it up or down right now. We just wanna have the enemy throw it either left or right. Your game may need to use top and bottom and for those cases please use the above diagrams to help you out.


xdistance = player x location - enemy x location;
ydistance = player y location - enemy y location;
distance = (xdistance + ydistance)/2;

if(distance is far ranged (200 pixels+))
{
   if(xdistance is positive)
   {
      have enemy perform the rock throw to the right;
   } 
   else
      have enemy perform the rock throw to the left;
   }
} else if (distance is mid range (100 px to 200 px))
{
   have the enemy go into defensive position;
} 
else
{
   if(xdistance is positive)
   {
      have enemy throw a punch to the right;
   } 
   else
      have enemy throw a punch to the left;
   }
}

Well This code surely is developing… But like my random Ai example before. This is just an algorithm to get use where we want. The Real Code :slight_smile: Let’s break this up and run by with the real code.


xdistance = player x location - enemy x location;
ydistance = player y location - enemy y location;
distance = (xdistance + ydistance)/2;

I think I can just jump over this one seeing as how we discussed this over. Place either the relative distance or exact distance equations here.


xdistance = pc._x - enemy._x;
ydistance = pc._y - enemy._y;
distance = (xdistance + ydistance) / 2;

Now onward.


if(distance is far ranged (200 pixels+))
{
   if(xdistance is positive)
   {
      have enemy perform the rock throw to the right;
   } 
   else
      have enemy perform the rock throw to the left;
   }
} 

We would writie this up as…


if(distance > 200)
{
   if(xdistance >= 0)
   {
      enemy.performAttack("rockthrow", "right");
   }
   else
   {
      enemy.performAttack("rockthrow", "left");
   }
}

Easy enough… Just a couple of simple if statements and some function calls. :slight_smile:


 else if (distance is mid range (100 px to 200 px))
{
   have the enemy go into defensive position;
} 

Now into real code.


else if(distance > 100 && distance <= 200)
{
   enemy.performDefense();
}

Now… Onto the last bit of code.


else
{
   if(xdistance is positive)
   {
      have enemy throw a punch to the right;
   } 
   else
      have enemy throw a punch to the left;
   }
}

Easy enough… This almost looks like the first one cept with an else…


else
{
   if(xdistance >= 0)
   {
      enemy.performAttack("punch", "right");
   }
   else
   {
      enemy.performAttack("punch", "left");
   }
}

And… That leads us to throwing it all together into one nice little happy family.


xdistance = pc._x - enemy._x;
ydistance = pc._y - enemy._y;
distance = (xdistance + ydistance) / 2;

if(distance > 200)
{
   if(xdistance >= 0)
   {
      enemy.performAttack("rockthrow", "right");
   }
   else
   {
      enemy.performAttack("rockthrow", "left");
   }
}else if(distance > 100 && distance <= 200)
{
   enemy.performDefense();
}
else
{
   if(xdistance >= 0)
   {
      enemy.performAttack("punch", "right");
   }
   else
   {
      enemy.performAttack("punch", "left");
   }
}

Well everyone… That’s the final piece of code… Not too bad huh? It’s funny how something so advanced can amount to around 20-40 lines of code… Funny huh? Well… Like the Random AI you can use this in many different ways. You can use this in a function or you can just plop this in your code like it is. Either way, please comment me back with as much info as possible :slight_smile:

Thanks and Good Day
Marz
[email protected]

Awesome Marz… man, when did you get motivated to actually do something constructive? lol :stuck_out_tongue: :trout:

:trout::trout:

Heck if I know… Just be glad :-p lol

*Originally posted by Jubba *
**Awesome Marz… man, when did you get motivated to actually do something constructive? lol :stuck_out_tongue: :trout: **

Marz is always productive. He helps out a lot on the forum (-:

And… niiiiice.

wow… this stuff is amazing… i would never have thought to do a lot of these things… but i am just getting into actionscript, so what do you expect?
i really wanna try out some of these things once i get better…

in other words

great job!:A+: