C language to play the plane game

Time:2021-10-26

This example shares the specific code of playing aircraft games in C language for your reference. The specific contents are as follows

Compilation environment: vs2019

Requirements:

In the same plane, control the three directions of artillery firing, fire shells in the space, and the enemy and friendly aircraft will always fly randomly in the sky. If they hit the enemy aircraft flying in the sky, one point will be added and one point will be deducted if they hit the friendly aircraft

Idea:

First initialize the program, then draw the description and map, and then enter the infinite cycle, in which the three main steps are realized: the aircraft flying in the sky, controlling the game content through the AWD space bar, and adding points when the game conditions are met.

Practice:

First of all, to achieve the animation effect of the aircraft, the essence is to output three strings on the X axis on the console, and make the three strings seem to move at the same time. Here I draw on the experience of writing the horse racing competition: in the first infinite cycle, I cycle and output the first, second and third strings respectively to represent the first step, and then add three string X-axis coordinate values. In the second infinite cycle, I clear the traces of the last string movement, and then output three strings respectively to represent the second step. Because the inner for loop does not have a sleep function, it looks like the effect of three strings moving at the same time. In this way, the three aircraft can be represented by an infinite loop.
Next, change the gun muzzle pointing direction (one character) through the getch function. While the gun muzzle pointing is switched, the initialization position of the shell will also change. When pressing the space, the shell (one character) will move continuously along the set route from its initialization position. When the horizontal and vertical axis coordinates match the aircraft coordinates, judge whether it is an enemy aircraft | – 0 >, If yes, the score is plus one, otherwise the score is minus one.
In addition, there are many details in the program, which will not be repeated here.

Difficulties:

It looks like three strings are moving at the same time. This is an algorithm. If you learn it, you should remember it as firmly as you remember the basic knowledge. After understanding the principle, it is easier to master.

explain:

This is a simple small program. There are many ways to achieve the same effect in the program, and I use a lot of arrays to store, count and use various different data. In fact, similar effects can also be achieved through a single linked list. In my current cognition, the writing method of using array and direct output string has the advantages of simplicity and clarity. But it also leads to a fatal defect in the display effect.

be careful:

In the program due to compiler reasons_ Kbhit() and_ The getch() function may cause errors when compiled on other compilers. The solution is to remove the “” in front of the function.

Operation effect:

Code implementation:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#include <string.h>


void HideCursor();  // hide cursor
void gotoxy(int x, int y); // Cursor positioning

#Define r 26 // maximum value of x-coordinate of each random tail of the aircraft
#Define n 20 // customs clearance score

int ax[3] = { 0 };  // Three aircraft tail coordinates, global
int y[3] = { 3,7,11 }; // Three Y-axes, global, look-up table method to determine the y-axis position of the aircraft 
    //Because the flight distance of the shell is to add two grids at a time, in order to correspond to parity, the y-axis here must be even
int i;   // Cyclic variable
int fd[3];   // Control aircraft type

Void cshcxhs() // initialization function
{
 System ("title playing airplane Games")// title
 system("mode con cols=100 lines=30"); // 100 wide and 30 high
 HideCursor();    // Cursor hiding

 gotoxy(46, 12);    // Introduce the rules of the game
 Printf ("rules of the game:");
 gotoxy(36, 14);
 Printf ("w a d key controls the direction, and the space bar launches shells");
 gotoxy(26, 16);
 Printf ("one point will be added if you hit enemy aircraft and one point will be deducted if you hit friendly aircraft");
 gotoxy(40, 18);
 Printf ("end game with accumulated score% d", n);
 Sleep(2800);

 system("cls");
 
 int k;     // Cyclic variable
 gotoxy(40, R);    // Initialize the fort
 for (k = 0; k < 17; k++)
 printf("_");

 gotoxy(46, R);
 printf("[_O_]");
 gotoxy(48, 25);    // Middle X: 48
 printf("|");

 int j;
 srand((unsigned)time(NULL));  // Initialize random seed
 For (J = 0; J < 3; j + +) // initialize the initial X coordinate of the aircraft and write it outside the loop
 {
 ax[j] = rand() % R;
 fd[j] = rand() % 2;
 }

 gotoxy(0, R);
 Printf ("score:")// Fractional X coordinate 9
}

Void hcfjhs() // draw the aircraft function
{
 gotoxy(ax[i], y[i]);  // First, output the whole aircraft at the tail of the aircraft

 if (fd[i] == 1)  
 printf("|---0>"); 
 else    
 printf(">>>>>>"); 

 gotoxy(ax[i] - 1, y[i]); // Remove the traces left by the tail of the aircraft
 printf(" ");

 ax[i]++;   // Then the tail coordinates of the aircraft will increase automatically, and the whole aircraft will be output from the tail next time
}

Void dhpdxshs() // draw the plane and make it disappear when flying over x94
{
 For (I = 0; I < 3; I + +) // one step for each aircraft
 {
 hcfjhs();

 If (AX [i] + 6 > = 94) // judge whether each aircraft head exceeds 94
 {
  gotoxy(94, y[i]); // If the conditions are met, a space is output at 94 of each aircraft
  printf(" ");
  If (AX [i] + 6 > 100) // if the aircraft head of each aircraft exceeds 100, reset a random number
  {
  ax[i] = rand() % R; // Modify to a random number less than R
  fd[i] = rand() % 2;
  }
 }
 }
}

int da = 2;  // Da = 1 is the leftmost default middle turret direction, global variable
int yip = 0;  // Whether to fire or not, 0 does not open, 1, 2 and 3 directions
int rtde = 1;  // Whether the firing is completed or not, we must wait for the shell to be fired


int shells_ x;  // Shell coordinates
int shells_y;

void ckkzhs()
{
 char ch;
 ch = _getch();

 if (ch == 'd' || ch == 'D')
 {
 gotoxy(49, 25);
 printf("/");  // Turret turn right
 gotoxy(47, 25);
 printf(" ");
 da = 3;   // Rightmost state
 }
 if (ch == 'A' || ch == 'a')
 {
 gotoxy(47, 25);
 printf("\\");  // Escape character
 gotoxy(48, 25);
 printf(" ");
 da = 1;   // Leftmost state
 }
 if (ch == 'W' || ch == 'w')
 {
 gotoxy(48, 25);
 printf("|");  
 gotoxy(47, 25);
 printf(" ");
 gotoxy(49, 25);
 printf(" ");
 da = 2;
 }

 If (CH = = '& & rtde = = 0) // the cannon is in the firing completed state, and press the space
 {
 If (DA = = 2) // middle turret orientation
  yip = 2;
 
 If (DA = = 1) // left
 {
  yip = 1;
  shells_ x = 45;  // Initialize the coordinates of the shell
 }
 If (DA = = 3) // right
 {
  yip = 3;
  shells_x = 51;
 }
 shells_ y = 23;  // Initialize the coordinates of the shell
 }
}

Void dpfshs() // fire shells in three different directions
{
 rtde = 1;   // Cycle, when the shell moves, it means that the firing is not completed
 if (yip == 2)
 {
 shells_x = 48;
 gotoxy(shells_x, shells_y-=2);
 printf("o");
 gotoxy(shells_x, shells_y+2);
 printf(" ");
 }
 if (yip == 1)
 {
 gotoxy(shells_x-=2, shells_y-=2);
 printf("o");
 gotoxy(shells_x+2, shells_y+2);
 printf(" ");
 }
 if (yip == 3)
 {
 gotoxy(shells_x+=2, shells_y-=2);
 printf("o");
 gotoxy(shells_x-2, shells_y+2);
 printf(" ");
 }

 If (shells_y < = 1) // shells cross the boundary and eliminate shells
 {
 yip = 0;  // The shell crossed the border and stopped
 gotoxy(48, 1);  // And eliminate
 printf(" ");
 gotoxy(23, 1);
 printf(" ");
 gotoxy(73, 1);
 printf(" "); 
 rtde = 0;  // The shell has crossed the boundary. After firing, the next round of firing can be carried out
 }
}

int score;   // score

Void pdfsjzhs() // judge whether to hit and statistics
{
 
 for (i = 0; i < 3; i++)
 {
  If (shells_x > = ax [i] & & shells_x < = ax [i] + 6 & & shells_y = = y [i]) // when hit
  {
  if(fd[i]==1)
   score++;   // Hit once, score plus one
  else
  {
   score--;
   if (score <= 0)
   score = 0;
  }

  rtde = 0;   // When hit, the firing is complete

  gotoxy(ax[i]-1, y[i]);  // After hitting, eliminate the aircraft at the tail of the original aircraft
  printf(" ");

  ax[i] = rand() % R;  // Modify to a random number less than 10
  fd[i] = rand() % 2;  // The type of aircraft has changed

  gotoxy(shells_x, shells_y); // Output a blank space where the plane is hit to eliminate the shell body
  printf(" ");

  shells_ x = 0, shells_ y = 0; // The shell hit the aircraft, the shell crossed the boundary, and the next space will automatically initialize the shell
  }
 }
 
 gotoxy(9, R);
 printf("%d",score);

 If (score > = n) // judge the end of the game
 {
 system("cls"); // Clear screen
 gotoxy(39,15); 
 Printf ("you have cleared the customs, and the final score is:% d!", n);
 gotoxy(0, 29);
 exit(0);
 }

}

Void process() // process
{
 while (1)
 {
 dhpdxshs();  // Aircraft animation function

 if (_kbhit()) 
 {
  ckkzhs(); // Operation function
 }
 
 dpfshs();  // Cannon effect function
 pdfsjzhs();  // Determine whether to hit and statistics

 Sleep(18);
 }
}

int main()
{
 cshcxhs(); // Initialization program

 process(); // technological process

 return 0;
}

void HideCursor()
{
 CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
 SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

void gotoxy(int x, int y)
{
 COORD pos = { x,y };
 SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}

deficiencies:

When I output the aircraft in the program, I use the writing method of directly outputting the whole aircraft at the tail of the aircraft and the self increasing x coordinate of the tail of the aircraft. This is a very stupid but simple method. This approach makes it impossible to eliminate the aircraft fuselage one by one while flying over the maximum width of the console. Once the aircraft head crosses the maximum width of the console, there will be a program output error. Therefore, in order to retain the effect of “let the aircraft fly out of the boundary section by section”, which makes the aircraft disappear naturally, We have to use the last six X-axis grids on the y-axis where the last aircraft is located as the board to block the aircraft, so as to achieve a similar effect.

Because the program is creative, it is all written by myself. Due to my limited ability, I vaguely feel that there are a lot of problems in code reusability, rigorous structure and low operation efficiency in my program while writing this program. At the same time, I use the practice of writing blindly and Chinese Pinyin for many function and variable identifiers.

As a novice of C language, I always have a learning and humble attitude towards unknown knowledge. I would be grateful if someone could put forward suggestions on reusability, preciseness and operation efficiency of my program.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.