闲来没事做了个飞机大战的雏形
主要用了Windows API控制界面刷新和隐藏光标。
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <Windows.h>
int score=0,enemy_x=0,enemy_y=4,bullet_x=-1,bullet_y=0,my_x=8,my_y=2,step=1;
int space_x=3,space_y=4;
void gotoxy(int x,int y){//清屏
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X=x;
pos.Y=y;
SetConsoleCursorPosition(handle,pos);
}
void HideCursor(){//隐藏光标
CONSOLE_CURSOR_INFO cursor_info={1,0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
}
void draw_sx(){//画行
for(int i=0;i<space_x;++i){
printf("\n");
}
}
void draw_sy(){//画列
for(int i=0;i<space_y;++i){
printf(" ");
}
}
void draw(){//画
draw_sy();
printf("score:%d",score);
draw_sx();
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
draw_sy();
if(i==enemy_x&&j==enemy_y){//敌机
printf("@");
}else if(i==bullet_x&&j==bullet_y){//子弹
printf("|");
}else if(i==my_x&&j==my_y){//本机
printf("*");
}else{
printf(" ");
}
}
printf("\n");
}
bullet_x--;
step++;
if(bullet_x==enemy_x&&bullet_y==enemy_y){//打中了
score++;
bullet_x=-1;
}
if(step==20){//每20次循环移动一次敌机
step=1;
if(rand()%2){
if(rand()%2){
enemy_x++;
}else{
enemy_x--;
}
}else{
if(rand()%2){
enemy_y++;
}else{
enemy_y--;
}
}
}
}
void input(){
if(kbhit()){
switch(getch()){
case 'w':
my_x--;
break;
case 's':
my_x++;
break;
case 'a':
my_y--;
break;
case 'd':
my_y++;
break;
case ' '://空格发射子弹
bullet_x=my_x-1;
bullet_y=my_y;
break;
}
}
}
int main(){
srand(time(NULL));//随机数种子
HideCursor();//隐藏光标
while(1){
gotoxy(0,0);//刷新
draw();//画
input();//检测输入
Sleep(100);//延时
}
return 0;
}