#include<bits/stdc++.h>
#include<stdlib.h>
#include<windows.h>
#include<conio.h>
#include <time.h>
#include <dos.h>
#define Speed 4
#define Bar 30 //障碍数
using namespace std;
int player_x,player_y;
int high,width;
int speed;
int iskill;
clock_t start,end;
double my_time;
void gotoxy(int x, int y) //光标移动到x,y位置
{
COORD pos = {x,y};
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);// 获取标准输出设备句柄
SetConsoleCursorPosition(hOut, pos); //两个参数分别是指定哪个窗体,具体位置
}
void HideCursor() // 用于隐藏光标
{
CONSOLE_CURSOR_INFO cursor_info = {1, 0}; // 第二个值为0表示隐藏光标
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);//函数和结构体都在windows.h中定义。
}
struct bars
{
int y;
int x;
}bar[Bar];
void startup()
{
srand(time(NULL));
HideCursor();
high=27;
width=100;
player_x=high-5;
player_y=width/2;
speed=0;
iskill=0;
for(int i=0;i<Bar;i++)
{
bar[i].y=rand()%width;
bar[i].x=rand()%high/4+high/4;
}
}
void show()
{
gotoxy(0,0);
for(int i=0;i<high;i++)
{
for(int j=0;j<width;j++)
{
if(i==player_x&&
j==player_y) printf("*");
for(int z=0;z<Bar;z++)
{
if(bar[z].y==j&&
bar[z].x==i)
{
cout<<"#";
j++;
}
}
if(i!=player_x||
j!=player_y) printf(" ");
}
printf("|\n");
}
for(int j=0;j<width+1;j++)
cout<<"-";
cout<<endl;
printf("你坚持了:%.3lf秒!\n",my_time);
if(my_time>=100)
{
gotoxy(0,0);
cout<<"恭喜你完成挑战!\n"<<
"输入空格退出"<<endl;
char input;
while(1)
{
input=getch();
if(input==' ') break;
}
// system("pause");
exit(0);
}
if(iskill==1)
{
cout<<"呜呜,失败了\n";
system("pause");
exit(0);
}
}
void updateWithoutInput()
{
end=clock();
my_time=(double)(end - start)/CLOCKS_PER_SEC;
if(speed<Speed-my_time/30) speed++;
if(speed>=Speed-my_time/30)
{
for(int i=0;i<Bar;i++)
{
if(bar[i].x>player_x)
bar[i].x--;
if(bar[i].x<player_x)
bar[i].x++;
if(bar[i].y>player_y)
bar[i].y--;
if(bar[i].y<player_y)
bar[i].y++;
}
speed=0;
}
for(int i=0;i<Bar;i++)
{
if(bar[i].x==player_x
&&bar[i].y==player_y)
iskill=1;
}
}
void updateWithInput()
{
char input;
if(kbhit())
{
input=getch();
if(input==27) system("pause");
if(input=='s') player_x++;
if(input=='w') player_x--;
if(input=='a') player_y--;
if(input=='d') player_y++;
if(player_x>=high-1) player_x=high-1;
if(player_y>=width-1) player_y=width-1;
if(player_x<=0) player_x=0;
if(player_y<=0) player_y=0;
}
}
int main()
{
cout<<"是男人就坚持100秒"<<endl<<
"输入任意键开始"<<endl;
system("pause");
start=clock();
startup(); //数据初始化
while(1) //游戏循环执行
{
show(); //游戏画面
updateWithoutInput(); //与输入无关更新
updateWithInput(); //与输入有关更新
}
return 0;
}