打飞机游戏
这个游戏的原理比较简单,我们要实现这个游戏,首先要实现的就是怎么打印出飞机,和怎么操控飞机的移动,显然这些用简单的循环语句和分支语句就能实现。而敌机出现的话就更简单了,只要随机生成敌机的水平坐标,竖直坐标就让敌机从顶部落下(当然,你也可以随机生成竖直坐标),我们只需要控制随机数的范围就好了 例如 rand()%30; 随机生成0-29范围内的随机数。
其次,我们要做的就是如何攻击,当飞机发射子弹时,bullet_x会等于plane_x,bullet_y = plane_y - 1;我们要想子弹往上移动,只需要bullet_y --,就能实现。
最后,我们就只需要判断,子弹攻击到敌机,和飞机碰到敌机。当子弹坐标等于敌机坐标时,敌机死亡,当飞机碰到敌机时,游戏结束。
原理很简单,这里就不多做解释了,上代码。
#include<stdio.h>
#include<windows.h>
#include<conio.h>
int plane_x, plane_y;
int bullet_x, bullet_y;
int target_x, target_y;
int height = 21;
int width = 41;
int speed;
int kill;
int score;
int flag;
void start() {
int i;
for (i = 0; i < height - 3; i++) {
if (i == height / 2 - 1) {
printf(" WASD分别控制\n");
printf(" 上下左右移动\n");
printf(" 空格射击\n");
printf(" (按任意键继续)");
}
else
printf("\n");
}
plane_x = width / 2;
plane_y = height / 2;
target_x = rand() % 41;
target_y = 0;
speed = 15;
kill = 0;
score = 0;
flag = 0;
_getch();
}
void hideCursor() {
CONSOLE_CURSOR_INFO cursor_info = { 1,0 };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
}
void gotoxy(int x, int y) {
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
void show() {
int i, j;
gotoxy(0, 0);
for (j = 0; j < height; j++) {
for (i = 0; i < width; i++) {
if (i == plane_x && j == plane_y)
printf("*");
else if (i == target_x && j == target_y)
printf("@");
else if (i == bullet_x && j == bullet_y) {
printf("|");
bullet_y--;
}
else
printf(" ");
}
printf("|\n");
}
for (i = 0; i <= width / 2; i++) {
printf(" ̄");
}
printf("\n");
printf("当前得分:%d\n", score);
}
void updateWithInput() {
char input;
if (_kbhit()) {
input = _getch();
switch (input) {
case 's':
case 'S': plane_y++;
break;
case 'w':
case 'W': plane_y--;
break;
case 'a':
case 'A': plane_x--;
break;
case 'd':
case 'D': plane_x++;
break;
case ' ':
bullet_x = plane_x;
bullet_y = plane_y - 1;
break;
}
if (plane_x < 0)
plane_x = 0;
else if (plane_x > width - 1)
plane_x = width - 1;
if (plane_y < 0)
plane_y = 0;
else if (plane_y > height - 1)
plane_y = height - 1;
}
}
void updateWithoutInput() {
if (plane_x == target_x && plane_y == target_y)
flag = 1;
if (bullet_x == target_x && bullet_y == target_y) {
score += 5;
kill = 1;
bullet_y = -1;
}
if (kill == 1) {
target_x = rand() % 20;
target_y = 0;
kill = 0;
}
static int t = 0;
if (t == speed) {
target_y++;
t = 0;
}
else
t++;
if (target_y > height)
kill = 1;
}
int main() {
system("color 0A");
hideCursor();
char input;
int k = 1;
while (1) {
if (k == 1) {
start();
k = 0;
}
else {
gotoxy(0, 0);
for (int i = 0; i < 10; i++) {
printf("\n");
}
printf("游戏结束,最终得分:%d(按任意键继续)", score);
_getch();
system("cls");
start();
}
while (!flag) {
show();
updateWithoutInput();
updateWithInput();
}
}
return 0;
}