虽然graphics.h是TC的库,不过本人是用VC写的,很容易只要在网上down下来库文件就好了,在此不做教程了!#include <time.h>
#include <math.h>
#include <conio.h>
#include <graphics.h>
#define STARS 200
#define PI 3.1415926536
struct Star3D
{
double x;
double y;
double z;
};
Star3D s3d[STARS];
char Astar[STARS];
double viewZ =3;
void Point()
{
srand(time(NULL));
double axy, a;
for(int i=0; i<STARS; i++)
{
s3d[i].z = 2.0 * rand() / RAND_MAX - 1;
axy = sqrt(1 - s3d[i].z * s3d[i].z);
a = 2 * PI * rand() / RAND_MAX;
s3d[i].x = cos(a) * axy;
s3d[i].y = sin(a) * axy;
}
}
void axisX(Star3D &p, double angle)
{
double y = p.y;
p.y = p.y * cos(angle) + p.z * sin(-angle);
p.z = y * sin(angle) + p.z * cos(angle);
}
void axisY(Star3D &p, double angle)
{
double x = p.x;
p.x = p.x * cos(angle) + p.z * sin(-angle);
p.z = x * sin(angle) + p.z * cos(angle);
}
void axisZ(Star3D &p, double angle)
{
double x = p.x;
p.x = p.x * cos(angle) + p.y * sin(-angle);
p.y = x * sin(angle) + p.y * cos(angle);
}
POINT Projection(Star3D p)
{
POINT s2d;
s2d.x = (int)(p.x * ( viewZ / (viewZ - p.z) ) * 200 + 0.5) + 320;
s2d.y = (int)(p.y * ( viewZ / (viewZ - p.z) ) * 200 + 0.5) + 240;
return s2d;
}
MOUSEMSG m;
void main()
{
initgraph(640, 480);
Point();
BeginBatchDraw();
int c;
POINT s2d;
while(!kbhit())
{
m = GetMouseMsg();//等待鼠标消息,如果不想要鼠标操作,可注掉此段
if(m.uMsg==WM_LBUTTONDOWN)
{
if(viewZ==1)viewZ=3;
else viewZ=1;
}
cleardevice();
for(int i=0; i<STARS; i++)
{
axisX(s3d[i], PI/180);
axisY(s3d[i], PI/170);
axisZ(s3d[i], PI/160);
s2d = Projection(s3d[i]);
switch(i%5)
{
case 0:Astar[i]='A';break;
case 1:Astar[i]='S';break;
case 2:Astar[i]='T';break;
case 3:Astar[i]='A';break;
case 4:Astar[i]='R';break;
}
outtextxy(s2d.x, s2d.y, Astar[i]);
}
FlushBatchDraw();
Sleep(10);
}
if(viewZ==1)viewZ=3;
else viewZ=1;
EndBatchDraw();
closegraph();
}