C语言实现飞机大战游戏
屏幕中将出现下落的敌机,按wasd移动你的飞机,并且使用空格键来开火击落敌机
代码如下:
game.h:
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
void HideCursor();
void gotoxy(int x, int y);
void DataInit();
void Show();
void UpdateWithoutInput();
void UpdateWithInput();
test.cpp:
#include "game.h"
int position_x, position_y;
int high, width;
int bullet_x, bullet_y;
int enemy_x, enemy_y;
int score;
int main()
{
HideCursor(); //隐藏光标
DataInit(); //数据初始化
while (1)
{
Show(); //显示画面
UpdateWithoutInput(); //与用户无关的数据更新
UpdateWithInput(); //与用户有关的数据更新
}
return 0;
}
game.cpp:
#include "game.h"
extern int high;
extern int width;
extern int position_x;
extern int position_y;
extern int bullet_x;
extern int bullet_y;
extern int enemy_x;
extern int enemy_y;
extern int score;
void DataInit()
{
high = 20;
width = 30;
position_x = high / 2;
position_y = width / 2;
bullet_x = -1;
bullet_y = position_y;
enemy_x = 0;
enemy_y = position_y;
score = 0;
}
void Show()
{
gotoxy(0, 0);
int i, j;
for (i = 0; i < high; i++)
{
for (j = 0; j < width; j++)
{
if (i == position_x && j == position_y)
printf("*");
else if (i == bullet_x && j == bullet_y)
{
printf("|");
}
else if (i == enemy_x && j == enemy_y)
{
printf("@");
}
else
printf(" ");
}
printf("\n");
}
printf("the score is: %d\n", score);
}
void UpdateWithoutInput()
{ if (enemy_x == bullet_x && enemy_y == bullet_y)
{
score++;
enemy_x = -1;
enemy_y = rand() % width;
bullet_x = -2;
}
if (enemy_x > high)
{
enemy_x = -1;
enemy_y = rand() % width;
}
if (bullet_x > -1) //控制子弹
bullet_x--;
static int speed = 0;
if (speed < 10)
speed++;
if (speed == 10)
{
enemy_x++;
speed = 0;
}
}
void UpdateWithInput()
{
char input;
if (_kbhit())
{
input = _getch();
if (input == 'w' && position_x > 1)
position_x--;
if (input == 's' && position_x < high - 1)
position_x++;
if (input == 'a' && position_y > 1)
position_y--;
if (input == 'd' && position_y < width - 1)
position_y++;
if (input == ' ')
{
bullet_x = position_x - 1;
bullet_y = position_y;
}
}
}
fix.cpp:
该代码用来实现隐藏光标,清屏不闪屏等问题
#include "game.h"
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);
}