C语言关于打飞机游戏的小问题
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
#define High 25
#define Width 50
int position_x, position_y;
int enemy_x, enemy_y;
int canvas = {0};
int score;
void gotoxy(int x, int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
void starup()
{
position_x = High - 1;
position_y = Width / 2;
enemy_x = 0;
enemy_y = position_y;
canvas = 1;
canvas = 3;
score = 0;
}
void show()
{
gotoxy(0, 0);
int i, j;
for(i = 0; i < High; i++)
{
for(j = 0; j < Width; j++)
{
if(canvas == 0)
printf(" ");
if(canvas == 1)
printf("*");
if(canvas == 2)
printf("|");
if(canvas == 3)
printf("@");
}
printf("\n");
}
printf("score = %d", score);
Sleep(20);
}
void updateWithoutInput()
{
//子弹的移动
int i, j;
for(i = 0; i < High; i++)
for(j = 0; j < Width; j++)
{
if(canvas == 2)
{
if((i == enemy_x) && (j == enemy_y))
{
score++;
canvas = 0; //敌机被打中消失
enemy_x = 0; //产生新的敌机
enemy_y = rand() % Width;
canvas = 3;
canvas = 0; //子弹消失
}
canvas = 0;
if(i > 0)
canvas = 2; //i, j动态的移动
}
}
//敌机碰撞我机游戏结束
if(enemy_x == position_x && enemy_y == position_y)
{
printf("\n游戏结束\n");
Sleep(3000);
system("pause");
exit(0);
}
//敌机跑出屏幕外
if(enemy_x > High)
{
canvas = 0;
enemy_x = 0;
enemy_y = rand() % Width;
canvas = 3;
score--;
}
//敌机下落
static int speed = 0;
if(speed < 10)
speed++;
if(speed == 10)
{
canvas = 0;
enemy_x++;
speed = 0;
canvas = 3;
}
//问题所在
/*为什么这样写就会出错?
canvas = 0;
enemy_x++;
canvas = 3;
Sleep(50); 延迟50ms再执行 */
}
void updateWithInput()
{
if(kbhit())
{
char input = getch();
if(input == 'a')
{
canvas = 0;
position_y--;
canvas = 1;
}
if(input == 'd')
{
canvas = 0;
position_y++;
canvas = 1;
}
if(input == 'w')
{
canvas = 0;
position_x--;
canvas = 1;
}
if(input == 's')
{
canvas = 0;
position_x++;
canvas = 1;
}
if(input == ' ')
canvas = 2; //固定的发射位置
}
}
int main()
{
starup();
while(1)
{
show();
updateWithoutInput();
updateWithInput();
}
return 0;
}
正确结果:击中敌机后敌机会消失,并且子弹发射速度很快
如图
改用Sleep()则会出现击中敌机后,敌机并没有消失的现象,而且子弹发射速度慢,连成一条直线
求大佬帮忙,小白真的一脸懵逼{:5_100:} 兄弟,这程序我调试了一下,发现之所以第二种写法会出现敌机打中不消失,是因为子弹和敌机是同时一个上升一个下降,导致他们错位不可出现 子弹x==敌机x 这种情况,所以在不会进入if语句把敌机清理重新生成。自己分析一下吧
页:
[1]