Game Programming All in One 2 nd Edition phần 9 docx

74 305 0
Game Programming All in One 2 nd Edition phần 9 docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

563 Introduction to Artificial Intelligence chapter 18 P robably the thing I dislike most about some games is how the computer cheats. I’m playing my strategy game and I have to spend 10 minutes finding their units while they automatically know where mine are, which type they are, their energies, and so on. It’s not the fact that they cheat to make the game harder, it’s the fact that they cheat because the artificial intelligence is very weak. The computer adversary should know just about the same information as the player. If you look at a unit, you don’t see their health, their weapons, and their bullets. You just see a unit and, depending on your units, you respond to it. That’s what the computer should do; that’s what artificial intelligence is all about. In this chapter I will first give you a quick overview of several types of artificial intelli- gence, and then you will see how you can apply one or two to games. In this chapter, I’m going to go against the norm for this book and explain the concepts with little snippets of code instead of complete programs. The reason I’m doing this is because the implemen- tation of each field of artificial intelligence is very specific, and where is the fun in watching a graph give you the percentage of the decisions if you can’t actually see the bad guy hiding and cornering you? Complete examples would basically require a complete game! For this reason, I will go over several concrete artificial intelligence examples, giving only the theory and some basic code for the implementation, and it will be up to you to choose the best implementation for what you want to do. Here is a breakdown of the major topics in this chapter: ■ Understanding the various fields of artificial intelligence ■ Using deterministic algorithms ■ Recognizing finite state machines ■ Identifying fuzzy logic ■ Understanding a simple method for memory ■ Using artificial intelligence in games The Fields of Artificial Intelligence There are many fields of artificial intelligence; some are more game-oriented and others are more academic. Although it is possible to use almost any of them in games, there are a few that stand out, and they will be introduced and explained in this section. Expert Systems Expert systems solve problems that are usually solved by specialized humans. For example, if you go to a doctor, he will analyze you (either by asking you a set of questions or doing some analysis himself), and according to his knowledge, he will give you a diagnosis. An expert system could be the doctor if it had a broad enough knowledge base. It would ask you a set of questions, and depending on your answers, it would consult its knowledge base and give you a diagnosis. The system checks each of your answers with the possible answers in its knowledge base, and depending on your answer, it asks you other questions until it can easily give you a diagnosis. For a sample knowledge tree, take a look at Figure 18.1. As you can see, a few questions would be asked, and according to the answers, the system would follow the appropriate tree branch until it reached a leaf. A very simple expert system for a doc- tor could be something like the fol- lowing code. Note that this is all just pseudo-code, based on a fictional scripting language, and it will not compile in a compiler, such as Dev-C++ or Visual C++. This is not intended to be a functional example, just a glimpse at what an expert system’s scripting language might look like. Answer = AskQuestion (“Do you have a fever?”); if (Answer == YES) Answer = AskQuestion (“Is it a high fever (more than 105.8 F)?”); Chapter 18 ■ Introduction to Artificial Intelligence564 Figure 18.1 An expert system’s knowledge tree if (Answer == YES) Solution = “Go to a hospital now!”; end if Is Sick? NO YES Has a fever? NO YES Has problems breathing? NO YES High fever? NO YES Send home . . . Lung Infection Do more analysis . . . else Answer = AskQuestion (“Do you feel tired?”); if (Answer == YES) Solution = “You probably have a virus, rest a few days!”; else Solution = “Knowledge base insufficient. Further diagnosis needed.”; end if else Answer = AskQuestion (“Do you have problems breathing?”); if (Answer == YES) Solution = “Probably a lung infection, need to do exams.” else Solution = “Knowledge base insufficient. Further diagnosis needed.”; end if end if As you can see, the system follows a set of questions, and depending on the answers, either asks more questions or gives a solution. note For the rest of this chapter, you can assume that the strings work exactly like other variables, and you can use operators such as = and == to the same effect as in normal types of variables. Fuzzy Logic Fuzzy logic expands on the concept of an expert system. While an expert system can give values of either true (1) or false (0) for the solution, a fuzzy logic system can give values in between. For example, to know whether a person is tall, an expert system would do the following (again, this is fictional script): The Fields of Artificial Intelligence 565 Answer = AskQuestion (“Is the person’s height more than 5’ 7”?”); if (Answer == YES) Solution = “The person is tall.”; else Solution = “The person is not tall.”; end if A fuzzy set would appear like so: Answer = AskQuestion (“What is the person’s height?”); if (Answer >= 5’ 7”) Solution = “The person is tall.”; end if if ((Answer < 5’ 7”) && (Answer < 5’ 3”)) Solution = “The person is almost tall.”; end if if ((Answer < 5’ 3”) && (Answer < 4’ 11”)) Solution = “The person isn’t very tall.”; else Solution = “The person isn’t tall.”; end if The result would be fuzzy. Usually a fuzzy set returns values from 0 (false) to 1 (true), representing the membership of the problem. In the last example, a more realistic fuzzy system would use the graph shown in Figure 18.2 to return a result. As you can see from the graph, for heights greater than 5' 7", the function returns 1; for heights less than 4' 11", the function returns 0; and for values in between, it returns the corresponding value between 5' 7" and 4' 11". You could get this value by subtracting the height from 5' 7" (the true statement) and dividing by 20 (5' 7"–4' 11", which is the variance in the graph). In code, this would be something like the following: Chapter 18 ■ Introduction to Artificial Intelligence566 Figure 18.2 Fuzzy membership Answer = AskQuestion (“What is the person’s height?”); if (Answer >= 5’ 7”) Solution = 1 end if if (Answer <= 4’ 11”) Solution = 0 else Solution = (Answer - 5’ 7”) / (5’ 7” - 4’ 11”) end if You might be wondering why you don’t simply use the equation only and discard the if clauses. The problem with doing so is that if the answer is more than 5' 7" or less than 4' 11", it will give values outside the 0 to 1 range, thus making the result invalid. Fuzzy logic is extremely useful when you need reasoning in your game. Genetic Algorithms Using genetic algorithms is a method of computing solutions that relies on the concepts of real genetic concepts (such as evolution and hereditary logic). You might have had a biology class in high school that explained heredity, but in case you didn’t, the field of biology studies the evolution of subjects when they reproduce. (Okay, maybe there is a lit- tle more to it than that, but you are only interested in this much.) As you know, everyone has a blood type, with the possible types being A, B, AB, and O, and each of these types can be either positive or negative. When two people have a child, their types of blood will influence the type of blood the child has. All that you are is writ- ten in your DNA. Although the DNA is nothing more than a collection of bridges between four elements, it holds all the information about you, such as blood type, eye color, skin type, and so on. The little “creatures” that hold this information are called genes. What you might not know is that although you have only one type of blood, you have two genes specifying which blood type you have. How can that be? If you have two genes describing two types of blood, how can you have only one type of blood? Predominance! Certain genes’ information is stronger (or more influential) than that of others, thus dictating the type of blood you have. What if the two genes’ information is equally strong? You get a hybrid of the two. For the blood type example, both type A and type B are equally strong, which makes the subject have a blood type AB. Figure 18.3 shows all the possible combinations of the blood types. From this table, you can see that both the A and B types are predominant, and the O type isn’t. You can also see that posi- tive is the predominant type. So, how does this apply to the computer? There are various implementations that range from solving mathematical equations to fully generating artificial creatures for scientific The Fields of Artificial Intelligence 567 research. Implementing a simple genetics algorithm in the computer isn’t difficult. The necessary steps are described here: 1. Pick up a population and set up initial information values. 2. Order each of the information values to a flat bit vector. 3. Calculate the fitness of each member of the population. 4. Keep only the two with the highest fitness. 5. Mate the two to form a child. And thus you will have a child that is the product of the two best subjects in the population. Of course, to make a nice simulator you wouldn’t use only two of the subjects—you would group various subjects in groups of two and mate them to form various chil- dren, or offspring. Now I’ll explain each of the steps. You first need to use the initial population (all the sub- jects, including creatures, structures, or mathematical variables) and set them up with their initial values. (These initial values can be universally known infor- mation, previous experiences of the subject, or com- pletely random values.) Then you need to order the information to a bit vector, as shown in Figure 18.4. Although some researchers say that an implementation of a genetic algorithm must be done with bit vectors, others say that the bit vectors can be replaced by a function or equation that will analyze each gene of the progenitors and generate the best one out of the two. To be consis- tent with the DNA discussion earlier, I will use bit vectors (see Figure 18.4). You now have to calculate the fitness of each subject. The fitness value indicates whether you have a good subject (for a creature, this could be whether the creature was strong, smart, or fast, for example) or a bad subject. Calculating the fitness is completely depen- dent on the application, so you need to find some equation that will work for what you want to do. After you calculate the fitness, get the two subjects with the highest fitness and mate them. You can do this by randomly selecting which gene comes from which progenitor or by intelligently selecting the best genes of each to form an even more perfect child. If you Chapter 18 ■ Introduction to Artificial Intelligence568 Figure 18.3 Gene blood type table Figure 18.4 Bit vectors (or binary encoding) of information—the virtual DNA want to bring mutation to the game, you can switch a bit here and there after you get the final offspring. That’s it—you have your artificial offspring ready to use. This entire process is shown in Figure 18.5. A good use of this technology in games is to simulate artificial environments. Instead of keeping the same elements of the environment over and over, you could make elements (such as small programs) evolve to stronger, smarter, and faster elements (or objects) that can interact with the environment and you. Neural Networks Neural networks attempt to solve problems by imitating the workings of a brain. Researchers started trying to mimic animal learning by using a collection of idealized neu- rons and applying stimuli to them to change their behavior. Neural networks have evolved much in the past few years, mostly due to the discovery of various new learning algo- rithms, which made it possible to implement the idea of neural networks with success. Unfortunately, there still aren’t major discoveries in this field that make it possible to sim- ulate the human brain efficiently. The human brain is made of around 50 billion neurons (give or take a few billion). Each neu- ron can compute or process information and send this information to other neurons. Trying to simulate 50 billion neurons in a computer would be disastrous. Each neuron takes various calculations to be simulated, which would lead to around 200 billion calculations. You can forget about modeling the brain fully, but you can use a limited set of neurons (the human brain only uses around 5 to 10 percent of its capacity) to mimic basic actions of humans. The Fields of Artificial Intelligence 569 Figure 18.5 Mating and mutation of an offspring Chapter 18 ■ Introduction to Artificial Intelligence570 In 1962, Rosenblatt created something called a perceptron, one of the earliest neural net- work models. A perceptron is an attempt to simulate a neuron by using a series of inputs, weighted by some factor, which will output a value of 1 if the sum of all the weighted inputs is greater than a threshold, or 0 if it isn’t. Figure 18.6 shows the idea of a percep- tron and its resemblance to a neuron. While a perceptron is just a simple way to model a neuron, many other ideas evolved from this, such as using the same values for various inputs, adding a bias or memory term, and mixing various perceptrons using the output of one as input for others. All of this together formed the current neural networks used in research today. There are several ways to apply neural networks to games, but probably the most predomi- nant is by using neural networks to simulate memory and learning. This field of artificial intelligence is probably one of its most interesting parts, but unfortunately, the topic is too vast to give a proper explanation of it here. Fortunately, neural networks are becoming more and more popular these days, and numerous publications are available about the subject. Deterministic Algorithms Deterministic algorithms are more of a game technique than an artificial intelligence concept. Deterministic algorithms are predetermined behaviors of objects in relation to the universe problem. You will consider three deterministic algorithms in this section—random motion, tracking, and patterns. While some say that patterns aren’t a deterministic algorithm, I’ve included them in this section because they are predefined behaviors. note The universe (or universe problem) is the current state of the game that influences the subject, and it can range from the subject’s health to the terrain slope, number of bullets, number of adversaries, and so on. Figure 18.6 A perceptron and a neuron Random Motion The first, and probably simplest, deterministic algorithm is random motion. Although random motion can’t really be considered intelligence (because it’s random), there are a few things you can make to simulate some simple intelligence. As an example, suppose you are driving on a road, you reach a fork, and you really don’t know your way home. You would usually take a random direction (unless you are super- stitious and always take the right road). This isn’t very intelligent, but you can simulate it in your games like so: NewDirection = rand() % 2; This will give a random value that is either 0 or 1, which would be exactly the same thing as if you were driving. You can use this kind of algorithm in your games, but it isn’t very much fun. However, there are things to improve here. Another example? Okay. Suppose you are watching some guard patrolling an area. Two things might happen: The guard could move in a logical way, perhaps a circle or straight line, but most of the time he will move randomly. He will move from point A to B, then to C, then go to B, then C again, then D, then back to A, and repeat this in a totally different form. Take a look at Figure 18.7 to see this idea in action. His movement can be described in code something like this: Vector2D kGuardVelocity; Vector2D kGuardPosition; int kGuardCycles; /* Initialize random velocity and cycles */ kGuardVelocity[0] = rand () % 10 – 5; Deterministic Algorithms 571 Figure 18.7 A very bad guard kGuardVelocity[1] = rand () % 10 – 5; kGuardCycles = rand () % 20; while (GameIsRunning) { // If we still have some cycles with the current movement while (kGuardCycles— > 0) { A D C B kGuardPosition += kGuardVelocity; } // Change velocity and cycles kGuardVelocity [0] = rand () % 10 – 5; kGuardVelocity [1] = rand () % 10 – 5; kGuardCycles = rand () % 20; } And you have your guard. You might think this isn’t very intelligent, but if you were only playing the game, you would simply see that the guard was patrolling the place, and you would think that he was being intelligent. note Some of the psuedo-code in this chapter is based on the code developed to represent vectors in Chapter 19, “The Mathematical Side of Games.” Tracking When you are trying to catch someone, there are a few things you must do. First, move faster than him, or else you will never catch him, and move in the direction he is from you. There is no logic in running south if he is north of you. To solve this problem and add a little more intelligence to your games, you can use a track- ing algorithm. Suppose the guard spots an intruder. He would probably start running toward him. If you wanted to do this in your game, you would use the following code: Vector2D kGuardVelocity; Vector2D kGuardPosition; Vector2D kIntruderPosition; int iGuardSpeed; // Intruder was spotted, run to him Vector2D kDistance; Chapter 18 ■ Introduction to Artificial Intelligence572 [...]... component and swap it with the X component of the vector, as shown in Equation 19 .21 Figure 19. 7 A perpendicular vector forming a 90 -degree, counterclockwise angle with another vector 595 596 Chapter 19 I The Mathematical Side of Games Equation 19 .21 Just one little thing… You see that reversed T in Equation 19 .21 ? That is the perpendicular symbol vector2d vector2d_perpendicular(vector2d vect) { vector2d newvector... first.components[1] * second.components[1]; } Using the dot product isn’t very informative per se, but the dot product can also be defined by Equation 19 .23 This equation gives a little more information, don’t you agree? In case you didn’t know, ø is the smallest angle formed by the two vectors With a little thought and by combining Equations 19 .22 and 19 .23 , you can get the equation to find the smallest angle... Equation 19 .25 597 598 Chapter 19 I The Mathematical Side of Games double vector2d_perpdotproduct(vector2d first, vector2d second) { return vector2d_dotproduct(vector2d_perpendicular(first), second); } Matrices A simple way of defining a matrix is to say that it is a table of values You can see in Equation 19 .26 that a matrix is defined by a set of rows and columns The number of columns is given by p and... normalize the vector in other words, divide the components of the vector by its total length, as shown in Equation 19 .20 Equation 19 .20 vector2d vector2d_normalize(vector2d vect) { vector2d newvector = vect; double length = vector2d_length(vect); if (length > 0) { newvector.components[0] /= length; newvector.components[1] /= length; } return newvector; } Perpendicular Operation Finding the perpendicular of... programming, especially in game programming Behind the scenes, in the graphics pipeline, and in the physics engine, heavy math is being processed by your computer, often with direct implementation in the silicon (as is the case with most graphics chips) While a huge amount of heavy math is needed to get a polygon on the screen with a software renderer, that is all handled by highly optimized (and fantastically... newvector.components[0] = vect.components[1] * -1; newvector.components[1] = vect.components[0]; return newvector; } Dot Product The dot product is probably the most used operation with vectors You can use it to multiply two vectors, as shown in Equation 19 .22 Equation 19 .22 double vector2d_dotproduct(vector2d first, vector2d second) { return (double) first.components[0] * second.components[0] + first.components[1]... see that in any triangle that contains the center of the circle and the end of the arc as vertices, the hypotenuse of that triangle is the line formed from the circle’s center to the end of the arc Now you need to find the two other lines’ lengths that form the triangle You will find these using the cosine and sine functions The three equations that are important in geometry are cosine, sine, and tangent,... Equation 19. 17 In code you have: vector2d vector2d_multiply(vector2d vect, double multiplier) { vector2d newvector; newvector.components[0] = vect.components[0] * multiplier; newvector.components[1] = vect.components[1] * multiplier; return newvector; } 593 594 Chapter 19 I The Mathematical Side of Games You do the same thing for division, as you can see in Equation 19. 18 Equation 19. 18 To end the normal... degrees and vice versa As you might know, radians is the angle that contains half a circle, as you can see in Figure 19 .2 And you probably know that 180 degrees is also the angle that contains half a circle Knowing this, you can convert any radian unit to degrees, as shown in Equation 19. 1, and vice versa using Equation 19 .2 Figure 19. 1 Relation of the arc length and radius of the circle Figure 19 .2 Half... by using a subscript either with the order of the element or with the component identification, as shown in Equation 19. 14 #include typedef struct vector2d Vectors Figure 19. 4 A 2D vector composed of two scalars defining the orientation Equation 19. 14 { double components [2] ; } vector2d; As you can see, the vector is constituted by an array of two components: X (components[0]) and Y (components[1]) . chapter: ■ Understanding the various fields of artificial intelligence ■ Using deterministic algorithms ■ Recognizing finite state machines ■ Identifying fuzzy logic ■ Understanding a simple. Artificial Intelligence 5 69 Figure 18.5 Mating and mutation of an offspring Chapter 18 ■ Introduction to Artificial Intelligence570 In 19 62, Rosenblatt created something called a perceptron, one of. or this pattern. In games, a pattern can be as simple as making an object move in a circle or as complicated as executing orders, such as attacking, defending, harvesting food, and so on. How is

Ngày đăng: 12/08/2014, 19:20

Từ khóa liên quan

Mục lục

  • CH 18 Introduction to Artificial Intelligence

  • CH 19 The Mathematical Side of Games

  • CH 20 Publishing Your Game

Tài liệu cùng người dùng

Tài liệu liên quan