Netterpillars: Artificial Intelligence and Sprites

Một phần của tài liệu net game programming with directx 9.0 (2003) (Trang 72 - 127)

Overview

In this chapter we'll explore the concepts of artificial intelligence (AI) and sprites. We'll also extend our knowledge of GDI+ functions, including some tips intended to give us a boost in performance. To accomplish these goals and illustrate these concepts, we'll create a game called .Netterpillars.

.Netterpillars is an arcade game in which each player controls a caterpillar (in fact, a "netterpillar") that takes part in a mushroom-eating race with other netterpillars. The objective of the game is to be the last surviving netterpillar, or the longest one (they grow when they eat) when every mushroom has been eaten.

We'll describe the game in more detail in the section "The Game Proposal" later in this chapter.

.Netterpillars is a more complex game than the one we saw in the last chapter because it involves the following components:

Figure 2-1: .Netterpillars, this chapter's sample game

AI: Creating a game with opponents will make us exercise our ability to create a computer-controlled character that challenges players, while giving them a fair chance of winning.

Sprites: Using nonblocky game objects will force us to find a way to draw nonrectangular moving objects on screen. Including a background image in our game screen will help us to check if our moving code is working (remember, in the last chapter we simply painted the objects with the flat background color).

GDI+: Creating an interface where many objects (one to four caterpillars, wooden branches, and a lot of mushrooms) will be drawn and interact with each other will challenge us to find a faster way to update the screen.

While covering these topics, we'll also look at new concepts related to object-oriented programming so we can create easily reuseable classes to improve the productivity when coding our games. For example, a

"sprite" class is something that almost any game will need; so we can code it once and use it forever. We'll discuss all these points in the next sections, starting with some object-oriented concepts.

.NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen

Hatton

ISBN:1590590511

Apress © 2003 (696 pages)

The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio.

Table of Contents

.NET Game Programming with DirectX 9.0 Foreword

Preface Introduction

Chapter 1 - .Nettrix: GDI+ and Collision Detection

Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites

Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+

Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen

Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay

Chapter 9 -D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

Bonus Chapter Porting .Nettrix to Pocket PC Appendix A- The State of PC Gaming Appendix B- Motivations in Games Appendix C- How Do I Make Games?

Appendix D- Guidelines for Developing Successful Games Index

List of Figures List of Tables

Object-Oriented Programming

There are many technical books that explain the academic details of object-oriented analysis (OOA) and object-oriented programming (OOP). It's not our goal to enter into such particulars, but instead loosely define a few terms and demonstrate some practical uses of these techniques.

The main idea behind creating objects is to make our code simpler to write and easier to maintain. By creating high-level objects to take care of specific tasks, we can build our games using these objects without needing to remember every tiny detail about a new game.

A good analogy to consider is jigsaw puzzles: How many blue skies have you seen in different puzzles?

And, for each one, you always have to put the pieces together one by one, regardless of the skies you have assembled before. If we could use OO concepts on puzzles, we would assemble the sky once, and for every new puzzle we could use this ready-made sky as a starting point, and build only the different parts around it.

Even considering a single puzzle, the analogy is still relevant: It's far easier to assemble the puzzle if we put similar pieces in different groups, assemble the groups, and then glue them together to see the final picture. That's pure OOP: Group related functions and data inside objects, code and test the objects, and then code the interface between them.

Table 2-1 lists some common terms used when talking about object-oriented programming and analysis, along with a definition of each.

Table 2-1: Common Object-Oriented Terminology

TERM DEFINITION

Class The code we write that is used as a blueprint to create objects. It can have methods, properties, and events.

Object An instance of a class, or, in other words, a variable of a specific class, after the object has been created.

Methods Functions defined inside a class.

Properties or attributes

Variables defined inside a class.

Events Procedures in the call triggered by the object called. May be associated to a user action (such as clicking a button) or to a system action (such as a specific time slice elapsed).

Constructor Special method called when creating an object—in Visual Basic .NET, this is any function with the New name.

Destructor Special method called when the object is being destroyed. In Visual Basic, to code the destructor we have to override (see the Overriding entry) the Dispose method of the base class.

Inheritance Object-oriented concept which defines that one class can be derived from another class or classes (called base or mother classes), and inherit their interface and code (called the derived or child class).

Overriding Object-oriented concept which defines that a derived class can create a different implementation of a base class method, to deal with specific needs of the derived class.

Interface The set of public methods, properties, and events of one class. Public elements are visible to any program that creates an object from a class.

When applied to a method, this means its parameters and return values.

.NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen

Hatton

ISBN:1590590511

Apress © 2003 (696 pages)

The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio.

Table of Contents

.NET Game Programming with DirectX 9.0 Foreword

Preface Introduction

Chapter 1 - .Nettrix: GDI+ and Collision Detection

Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites

Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+

Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen

Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay

Chapter 9 -D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

Bonus Chapter Porting .Nettrix to Pocket PC Appendix A- The State of PC Gaming Appendix B- Motivations in Games Appendix C- How Do I Make Games?

Appendix D- Guidelines for Developing Successful Games Index

List of Figures List of Tables

Encapsulation Concept related to the puzzle analogy: All details are embedded in the class, so the program that creates the object doesn't need to care about them.

Overloading Object-oriented concept which states that one method can have many different interfaces, while keeping the same name.

Polymorphism Object-oriented concept which says that different objects can have different implementations of the same function. An Add method, for example, can sum integers and concatenate strings.

Note We'll refer to these concepts and terms throughout the rest of the book, reinforcing their meanings as we go along.

Continuing with the introductory concepts of this chapter, let's talk about artificial intelligence, giving a real- life application of this concept born in science fiction books.

.NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen

Hatton

ISBN:1590590511

Apress © 2003 (696 pages)

The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio.

Table of Contents

.NET Game Programming with DirectX 9.0 Foreword

Preface Introduction

Chapter 1 - .Nettrix: GDI+ and Collision Detection

Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites

Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+

Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen

Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay

Chapter 9 -D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

Bonus Chapter Porting .Nettrix to Pocket PC Appendix A- The State of PC Gaming Appendix B- Motivations in Games Appendix C- How Do I Make Games?

Appendix D- Guidelines for Developing Successful Games Index

List of Figures List of Tables

Artificial Intelligence

AI, for our purposes, is the code in a program that determines the behavior of an object—in other words, how each game object will act upon and react to the game environment in each specific time frame.

The game's AI is often confused with the game physics, or the "simulation" as some gamers prefer to call it. While the AI decides what to do, the physics sets the constraints and limits of the AI and your game play.

Some examples will make this distinction clearer:

Classic pinball games have no AI, only physics.

In the SimCity game series, when players can't build a new residential block over a river, it's the game physics acting. When the Sims start creating their houses, it's the game AI's turn.

In the 3-D maze fever started long ago by Castle Wolfenstein, the game physics tells players that they can't go through walls, and that their bullets will lower the enemy's energy until death. The game AI tells the enemy to turn around and fire at players if they shoot him, or if he "hears" them shooting.

A good game project usually has the physics and the AI very well defined and separated, and most times the AI acts just like a player over the game physics. For example, in a multiplayer race game, the players control some cars, and the AI will drive all cars with no pilots, ideally with the same difficulties that the human players have.

AI Categories

We can divide the AI into three categories:

Environmental AI: The kind of AI found in games like SimCity, where the environment (in this example, the city) acts as a lifelike environment, reacting to the player input and including some unexpected behavior of its own.

Opposing player AI: Used in games where the AI will act like a player playing against the human. For example, in chess and other board games, we usually have a very sophisticated AI to play the part of an opponent.

Nonplayer characters (NPCs): Many games have computer-controlled characters that could be friendly (for example, the warriors that join players in a quest on role-playing games, or RPGs, like Diablo), unfriendly (the monsters and enemies in 3D mazes), or neutral (the characters are there just to add color to the environment, such as the cooker at the Scumm bar in LucasArts' The Secret of Monkey Island).

Of course this division exists only for teaching purposes; sometimes there's no distinct barrier between the categories.

General AI Considerations

Without entering into specific details, there are some things we have to remember when writing AI code:

Don't let users find out that the AI has access to their internal data. For example, in games like Microsoft's Age of Empires, players only see part of the map. Even though the AI can access the full map, the computer-controlled tribes don't act as if they know all the players' characters positions.

Create different levels of difficulty. Having a game with different levels lets players decide how tough they want their opponents to be. In some chess games, for example, players can choose how many future moves the computer will analyze, making the game easier or harder.

.NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen

Hatton

ISBN:1590590511

Apress © 2003 (696 pages)

The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio.

Table of Contents

.NET Game Programming with DirectX 9.0 Foreword

Preface Introduction

Chapter 1 - .Nettrix: GDI+ and Collision Detection

Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites

Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+

Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen

Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay

Chapter 9 -D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

Bonus Chapter Porting .Nettrix to Pocket PC Appendix A- The State of PC Gaming Appendix B- Motivations in Games Appendix C- How Do I Make Games?

Appendix D- Guidelines for Developing Successful Games Index

List of Figures List of Tables

Let the AI fail sometimes. If there's anything computers do well, it's executing code exactly the same way over and over. If you are coding a shooter game where the computer can shoot the player, don't forget to make the computer miss sometimes; and don't forget that an opponent that never misses is as bad as an opponent that always misses. Players play the game to win, but if they don't find it challenging, they'll never play your game again.

Don't forget to take into account the environment variables. If players can't see through the walls, the NPCs must act as if they can't either. If the computer-controlled adversary has low energy, but is very well protected by walls, he or she won't run away. If players can hear sounds when someone is approaching or when someone shoots, the NPCs must act like they hear it too.

Always add some random behavior. The correct balance of randomness will challenge players more, without making the game so unpredictable that it becomes unplayable. If the game has no element of chance, players can find a "golden path" that will allow them to always win when using a specific strategy.

Let the AI "predict" players' moves. In some games, it's possible to predict players' moves by

analyzing the possibilities based on the current situation, like in a checkers game. But in other games the AI can "cheat" a little, pretending that it predicted the moves of a good human player. For

example, if the AI discovers that a player is sending soldiers through a narrow passage in the direction of its headquarters, it can put a sentinel in the passage and pretend that it "had considered" that someone could use that passage. And never forget to give players a chance (they can kill the sentinel, for example)!

Common AI Techniques

When talking about AI, it's usual to hear about neural networks, genetic algorithms, fuzzy logic, and other technical terms. It's beyond the scope of this book to explain each of these approaches, but those who want to get deeper on the AI topic can search for these terms on the Internet to discover lots of interesting sites and relevant discussion groups.

These terms, when applied to games, have the main goals of adding unpredictability to the game actions and helping to create a game that seems to learn players' tricks and adapt to them to be more

challenging. To take a more practical approach, we can obtain these results by applying some simple tricks that will require a lot less effort. In the next sections we discuss some of these tricks.

Adaptable Percentage Tables

A neural network can be simplified as a table with adaptable results, represented by percentages. For example, when coding a war game, we can create a table to help the AI choose the tactics with which to attack the other players. The AI will use each tactic a set percentage of the time depending on the success rate that is represented by the percentage. The greater the success rate, the more often this tactic will be used. The table can be filled with some initial values, as shown in Table 2-2, and can evolve according to the results of each turn in the game.

Table 2-2: Starting Values for an Adaptable Percentage Table

ATTACK TYPE PERCENTAGE

Attack with "V" formation 20 percent

Divide the soldiers in small groups and attack in waves 20 percent Guerrilla attack—surprise attack with a few soldiers, shoot and run away 20 percent

Attack with full force, in a big group 20 percent

Surround the player and attack from every direction 20 percent

.NET Game Programming with DirectX 9.0 by Alexandre Santos Lobão and Ellen

Hatton

ISBN:1590590511

Apress © 2003 (696 pages)

The authors of this text show how easy it can be to produce interesting multimedia games using Managed DirectX 9.0 and programming with Visual Basic .NET on Everett, the latest version of Microsoft's Visual Studio.

Table of Contents

.NET Game Programming with DirectX 9.0 Foreword

Preface Introduction

Chapter 1 - .Nettrix: GDI+ and Collision Detection

Chapter 2 - .Netterpillars: Artificial Intelligence and Sprites

Chapter 3 - Managed DirectX First Steps: Direct3D Basics and DirectX vs. GDI+

Chapter 4 - River Pla.Net: Tiled Game Fields, Scrolling, and DirectAudio Chapter 5 - River Pla.Net II: DirectInput and Writing Text to Screen

Chapter 6 - Magic KindergarteN.: Adventure Games, ADO.NET, and DirectShow Chapter 7 - Magic KindergarteN. II: Animation Techniques and Speech API Chapter 8 - .Netterpillars II: Multiplayer Games and Directplay

Chapter 9 -D-iNfEcT: Multithreading, Nonrectangular Windows, and Access to Nonmanaged Code

Bonus Chapter Porting .Nettrix to Pocket PC Appendix A- The State of PC Gaming Appendix B- Motivations in Games Appendix C- How Do I Make Games?

Appendix D- Guidelines for Developing Successful Games Index

List of Figures List of Tables

After each attack, we'll change the table values according to the results. For example, if the attack is successful, we can add 10 percent to its corresponding percentage column on the table; if not, subtract 10 percent, distributing the difference to the other attack types. After some attacks, the program will "learn"

which kind of attack is most efficient against the current player. For example, if the AI uses the first kind of attack (in "V" formation) and it was successful, the table would be updated to the values shown in Table 2- 3.

Table 2-3: Adaptable Percentage Table Values After a Successful "V" Formation Attack

ATTACK TYPE PERCENTAGE

Attack with "V" formation 30 percent

Divide the soldiers into small groups and attack in waves 17.5 percent Guerrilla attack—surprise attack with a few soldiers, shoot and run away 17.5 percent

Attack with full force, in a big group 17.5 percent

Surround the player and attack from every direction 17.5 percent

In the next turn, if the AI tries an attack using the guerrilla tactic and it fails, the table will be updated again, to the values shown in Table 2-4.

Table 2-4: Adaptable Percentage Table Values After a Failed Guerrilla Attack

ATTACK TYPE PERCENTAGE

Attack with "V" formation 32.5 percent

Divide the soldiers in small groups and attack in waves 20 percent Guerrilla attack—surprise attack with a few soldiers, shoot and run away 7.75 percent

Attack with full force, in a big group 20 percent

Surround the player and attack from every direction 20 percent And so on ...

Of course in a real game it's better to add many interacting factors. For example, we can choose the best attack for each type of terrain or climatic condition. The more factors we take into account, the better results we'll have. In games like SimCity, there are dozens (sometimes even hundreds) of factors that contribute to generating the desired result.

Line of Sight

For games that use NPCs, a classical problem is how to discover if the computer character can see the player or not. There are many different solutions to this problem, but possibly the simplest one is the line of sight algorithm. We can implement this in a few steps:

Consider an NPC's eyes as a point just in front of it. It will be "looking" in this direction.

1.

Using the techniques for calculating the distance between two points, which we saw in the previous chapter, calculate the distance between the NPC and the player's character. If distance to the player is greater than a certain value (the "seeing distance"), the NPC can't see the player, as shown in Figure 2-2.

2.

Một phần của tài liệu net game programming with directx 9.0 (2003) (Trang 72 - 127)

Tải bản đầy đủ (PDF)

(573 trang)