知乎上看到的,学习一下。。。
#include<iostream>
#include<conio.h>
#include<Windows.h>
using namespace std;
class game
{
private:
int high,width;
int bird_x, bird_y;
int bar1_y, bar_xDown, bar_xTop;
int score;
public:
void startup();
void show();
void updateWithoutInput();
void updateWithInput();
void gotoxy(int x,int y);
}g;
void game::gotoxy(int x, int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
void game::startup()
{
high = 20;
width = 50;
bird_x = 0;
bird_y = width / 3;
bar1_y = width / 2;
bar_xDown = high / 3;
bar_xTop = high / 2;
score = 0;
}
void game::show()
{
gotoxy(0,0);
int i, j;
for (i = 0; i < high; i++)
{
for (j = 0; j < width; j++)
{
if ((i == bird_x) && (j == bird_y))
{
cout << "@";
}
else if ((j == bar1_y) && ((i < bar_xDown) || (i > bar_xTop)))
{
cout << "*";
}
else
{
cout << " ";
}
}
cout << endl;
}
cout << "SCORE:" << score;
}
void game::updateWithoutInput()
{
bird_x++;
bar1_y--;
if (bird_y==bar1_y)
{
if ((bird_x >= bar_xDown) && (bird_x <= bar_xTop))
{
score++;
}
else
{
system("cls");
cout << "GAME OVER!!!" << endl;
cout << " your score:" << score << endl;
system("pause");
exit(0);
}
}
if (bar1_y<0)
{
bar1_y = width;
int temp = rand() % int(high*0.8);
bar_xDown = temp - high / 10;
bar_xTop = temp + high / 10;
}
Sleep(200);
}
void game::updateWithInput()
{
char input;
if (kbhit())
{
input = getch();
if (input == ' ')
{
bird_x -= 2;
}
}
}
int main()
{
g.startup();
while (1)
{
g.show();
g.updateWithoutInput();
g.updateWithInput();
}
return 0;
}