Simple Application of Data Structures in games

Source: Internet
Author: User

In the compilation of games, there are inevitably a lot of application data structures. Some simple games are only composed of several data structures. Therefore, data structures play an important role in game programming.
This article mainly describes the application of data structures in games, including introduction to linked lists, sequence tables, stacks, queues, binary trees, and graphs. Before reading this article, readers should understand the data structure and be familiar with the functions of C/C ++. Now let's start with the linked list!

1. Linked List
In this section, we will explain the application of linked lists in the game through an airplane shooting game similar to lightning. In airplane games, the linked list is mainly used in the pop-up module. First, the number of aircraft bullets is unpredictable because of frequent occurrence and elimination. The main advantage of a linked list is that it can be easily inserted or deleted. We will introduce the Linked List data structure into it. First, analyze the followingSource code, In which we define the coordinate structure and the bullet chain table.

struct cpoint
{< br> int X; // X axis coordinate
int y; // y axis
};

Struct bullet
{
Struct Bulle * next;// Point to the next bullet
Cpoint bulletpos;// Bullet coordinates
Int m_ispeed;// Speed of the bullet
};

NextCodeThe list is the definition of a bullet in an airplane:

Class cmyplane
{
Public:
Void addbullet (struct bullet *); // Add the bullet function and play it at intervals
Void refreshbullet (); // Refresh the bullet
Privated:
Struct bullet * st_llmybullet; // Declare an airplane bullet chain table
};

In void addbullet (struct bullet *), all we need to do is to insert a node into the linked list and add it at intervals, which will produce continuous pop-up results.
This is the main source code of the function:

Void addbullet (struct bullet *)
{
Struct bullet * st_llnew, * st_lltemp; // Define a temporary linked list
St_llnew = _ struchead; // Linked list header (initialized)
St_llnew-> (bullet st_llmybullet *) malloc (sizeof (st_llmybullet )); // Allocate memory
St_lltemp = _ newbullet; // Temporary storage value
St_llnew-> next = st_lltemp-> next; st_lltemp-> next = st_llnew;
}

In the void refreshbullet () function, we only need to refresh the linked list once and update the data of the bullets. The main source code is as follows:

while (st_llmybullet-> next! = NULL)
{
// search
st_llmybullet-> bulletpos. x-= m_ispeed; // update bullet data
.........
st_llmybullet = st_llmybullet-> next; // search operation
} / span>

After the above analysis, in the game, the linked list is mainly applied to applications with large-scale deletion and addition. However, it also has a corresponding disadvantage, that is, the query is sequential search, which is time-consuming and has a low storage density and has a high requirement for space.
If you control the game data to limit the large-scale addition, that is, to determine the upper limit of memory requirements, you can apply the sequence table to replace the linked list. In some cases, ordered tables can make up for the loss of linked list time performance. Of course, the application linked list and sequence table mainly depend on the specific situation at that time. Now, in our next section, the most widely used data structure in the game-sequence table.

2. Sequence Table
In this section, we mainly invest in the construction of RPG maps, which sounds scary, but in the RPG map system (especially the brick map system ), it mainly uses the simplest member-sequence table in the data structure.
We define a simple brick Map System with a view of 90 degrees, which is combined by multiple sequential connected map blocks. This is probably the case with the early RPG map system. We define each graph block as follows:

Struct Tile// Define the Block Structure
{
Int m_iacesse;// Record whether the block can pass
......// Records the image pointer of each graph block.
};

If m_iacesse = 0, the block cannot pass. If it is 1, the block can pass.
We generate the following map:

Tile themaptile [10] [5];

In addition, can we add this graph block to it through a cycle to initialize the map.
Indicates:

0 1 2 3 4 5 6 7 8 9
0 1 1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 1 1 1 1 0
2 0 0 0 0 1 1 1 1 0
3 0 0 0 0 0 1 1 1 1 0
4 1 1 1 1 1 1 1 1 1 1 1

Figure 1


As you can see, this map is displayed in a sequence table. When we control a person's movements in the map, we can judge the next graph block that the person is going to go to see if it can pass. For example, when a character is going to go to the graph block (), we use the following code to determine whether the graph block can pass:

Int isacesse (x, y)
{
Return themaptile [x, y]. m_iacesse;// Return the value of whether the image block passes.
}

The above is just a simple map example. Through the sequence table, we can represent more complex brick maps. In addition, a large number of sequence tables are also used in the popular whole map, in the whole frame.
Now, let's go to the next section:

3. Stack and queue
Stack and queue are two special linear structures. In games, they are generally used in script engines, Operation interfaces, and data determination. In this section, a simple script engine function is used to introduce the stack. the queue and stack are similar in usage and will not be used as an example.
When setting a script file, we usually define some basic syntaxes, which requires a compilation of interpretation syntax.Program. A syntax check function is listed here. The main function is to check whether "()" is paired. Implementation idea: we stipulate that "()" can be used in a script statement, so there will be the following rule: The left and right brackets must be matched with the left brackets first, there are right brackets. In nested use, the left brackets allow single or continuous appearance and are paired with the parentheses to be displayed, the left parenthesis can be temporarily saved while waiting for the right parenthesis to appear. If the left parenthesis is not found after the right brace appears, it is not paired. From the perspective of program implementation, if left parentheses appear consecutively, the left parentheses that appear later should be matched with the first right parenthesis. The process of saving the left bracket is consistent with the matching Pin solution of the right bracket and the post-first-out principle in the stack. We can press the left parenthesis we read into the set stack. When we read the right parenthesis, We will pin it with the left parenthesis in the stack. If the left parenthesis does not pop at the top of the stack, this indicates that a pairing error occurs. Alternatively, when the parentheses are read, the left parenthesis still exists in the stack. This also indicates a pairing error.
The general idea is as follows. Please refer to the code snippet:

Struct // Define the stack structure
{
Int m_idata [100]; // Data segment
Int m_itop; // It is usually specified that the bottom position of the stack is at the low end of the Vector
} Seqstack;

Int check (seqstack * stack) // Syntax check function
{
Char sz_ch;
Int Boolean; push (stack ,'#'); // Press the stack, # for judging data
Sz_ch = getchar (); // Value
Boolean = 1;
While (sz_ch! = '\ N' & Boolean)
{
If (sz_ch = '(')
Push (stack, CH );
If (sz_ch = ')')
If (gettop (stack) = '#') // Read stack top
Boolean = 0;
Else
Pop (stack ); // Output Stack
Sz_ch = getchar ();
}
If (gettop (stack )! = '#') Boolean = 0;
If (Boolean) cout <"right "; // Output judgment Information
Else
Cout <"error ";

Here we will only introduce the reading of the script. Later, we will conduct an in-depth study on the script structure in the introduction to the figure.
In short, when there is a situation in the game where the first (stack), the first (Queue), you can use these two data structures, for example, transition Zone in the middle of the table in the Age of empire.

4. Binary Tree
Tree is widely used. Binary Trees are an important type of trees. Here, we mainly study a binary tree application method: decision tree. Its main application is to describe the classification process and process determination optimization.
Artificial intelligence usually has many classification judgments. Now there is an example: Set the life value D of the protagonist. After other conditions are omitted, the condition is determined as follows: When a monster encounters the protagonist, the reaction of the monster follows the following rule:
 

Table 1

According to the conditions, we can use the following commonAlgorithmTo determine the reaction of a monster:

If (d <100) State = laugh, single pick;
Else if (d <200) State = single pick;
Else if (d <300) State = bloodthirsty magic;
Else if (d <400) State = call companion;
Else state = escape;

The above algorithm is applicable in most cases, but its time performance is not high. We can use the decision tree to improve its time performance. First, analyze the common characteristics of the main character's life value, that is, to predict the percentage of each condition to the total condition, and use these ratios as weights to construct the optimal binary tree ), set Algorithms as decision trees. Assume that these percentages are:

Table 2

The constructed Harman tree is:

Figure 2

The algorithm is as follows:

If (d >=200) & (d <300) State = bloodthirsty magic;
Else if (D> = 300) & (d <500) State = call companion;
Else if (D> = 100) & (d <200) State = single pick;
Else if (d <100) State = mocking, single pick;
Else state = escape;

Through calculation, the efficiency of the two algorithms is about, which is obvious. The improved algorithm improves the time performance much.
Generally, in instant strategy games, such decision algorithms have high time performance requirements. You can perform more in-depth research on Binary Trees. Now, let's go to the last section of this article: the introduction of the graph, and finally we are about to finish.

5. Figure
In the game, most application graphs are path searches, that is, a * algorithm discussion. Because of introduction to a * algorithm and path searchArticleMany. Here, we will introduce another application of graphs: describing the relationship between plots in plot scripts.
In a game, there may be many branch plots, and there are certain prerequisites between these branch plots, that is, some branch Plots can only start to develop after other branch plots are completed, while some branch plots do not have such constraints.
Through analysis, we can use the AOV Network (Activity on vertex Network. Now let's assume that we have the following plot:

Plot No. Plot Prerequisites
C1 Robbers None
C2 Injured C1
C3 Buy medicine C2
C4 See a doctor C2
C5 Cure C3, C4


Note:: In the AOV network, directed loops should not appear. Otherwise, the order of vertices will enter an endless loop. That is, the plot cannot develop correctly. We can use the topological order to check whether a loop exists in the graph. the topological sorting is described in the data structure book, so we will not describe it here.
The above plot is shown in the form of a graph (this graph is a directed graph and Its Relationship is shown in the table above ):
 

Figure 3

The directed graph is represented by an adjacent matrix. See the following code snippet:

Struct mgraph
{
Int vexs [maxvex];// Vertex Information
Int arcs [maxlen] [maxlen];// Adjacent matrix
......
};

Vertex information is stored in the plot file.
Represent the given plot as an adjacent matrix:

0 1 0 0 0
0 0 1 1 0
0 0 0 0 1
0 0 0 0 1
0 0 0 0 0

Figure 4


We stipulate that each plot has a sequential relationship, but it is not developed by players. It is represented by 1. When the plot is developed, it will be expressed in 2. For example, if we have already developed the plot where a robber was encountered, then the relationship between C1 and C2 vertices can be expressed in 2. Note, it does not mean that C2 has developed, but that C2 can be developed.
See the following code:

class crelation
{< br> public:
crelation (char * filename); // constructor, read the plot information file into the cache
void setrelation (INT actionrelation ); // set the plot to be developed
bool searchrelation (INT actionrelation); // find whether the plot has evolved
bool savebuf (char * filename ); // save it to a file
......
privated:
char * Buf; // memory buffer of the adjacent matrix
......
};

here, we place the adjacent matrix indicating the relationship of the plot in the buffer, and use the interface function to modify the plot relationship. In the bool searchrelation (INT actionrelation) function, we can use the breadth-first search method for search. There are a lot of books about this and the code is very long. Here I will not give an example.
we can also use an adjacent linked list to represent this graph. However, using a linked list will occupy more memory. The main advantage of an adjacent linked list is that it represents a dynamic graph, it is not suitable here.
In addition, another application of graphs is pathtracing. The famous A * algorithm is based on this data structure. Artificial Intelligence also requires its foundation. Now, this section is complete.
now we can take a rest. After these five sections, we must have a general understanding of the use of the data structure in the game. The data structure actually has many application aspects in the game, I just introduced a small part of this article. I hope you can share more experience in game programming with me. Due to the limited experience of the author, it is inevitable that there will be omissions in the article. For more information, see my email address ( iceryeah2000@163.com ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.