Stars

The program realizes the dynamic effect of two-dimensional starry sky.

// Compiler Env: Visual C++ 6.0~2022,EasyX_2023大暑版
// https://easyx.cn
//
#include <graphics.h>
#include <time.h>
#include <conio.h>

#define MAXSTAR 200	// Total number of stars

struct STAR
{
	double	x;
	int		y;
	double	step;
	int		color;
};

STAR star[MAXSTAR];

// Initialize the stars
void InitStar(int i)
{
	star[i].x = 0;
	star[i].y = rand() % 480;
	star[i].step = (rand() % 5000) / 1000.0 + 1;
	star[i].color = (int)(star[i].step * 255 / 6.0 + 0.5);	// The faster the speed, the brighter the color
	star[i].color = RGB(star[i].color, star[i].color, star[i].color);
}

// Moving stars
void MoveStar(int i)
{
	// Wipe the original star
	putpixel((int)star[i].x, star[i].y, 0);

	// Calculate new location
	star[i].x += star[i].step;
	if (star[i].x > 640)	InitStar(i);

	// Draw the new star
	putpixel((int)star[i].x, star[i].y, star[i].color);
}

// Main function
int main()
{
	srand((unsigned)time(NULL));	// Set random seed
	initgraph(640, 480);			// Create a graphics window

	// Initialize all stars
	for(int i = 0; i < MAXSTAR; i++)
	{
		InitStar(i);
		star[i].x = rand() % 640;
	}

	// Draw the stars, press any key to exit
	while(!_kbhit())
	{
		for(int i = 0; i < MAXSTAR; i++)
			MoveStar(i);
		Sleep(20);
	}

	closegraph();					// Close the graphics window
	return 0;
}

For more examples, please refer to https://codebus.cn

(贡献者:Krissi  编辑