基於 EasyX
// 程序名稱:星空
// 編譯環境:Visual C++ 6.0,EasyX_20200902
// 最後更新:2009-2-22
//
#include <graphics.h>
#include <time.h>
#include <conio.h>
#define MAXSTAR 200 // 星星總數
struct STAR
{
double x;
int y;
double step;
int color;
};
STAR star[MAXSTAR];
// 初始化星星
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); // 速度越快,顏色越亮
star[i].color = RGB(star[i].color, star[i].color, star[i].color);
}
// 移動星星
void MoveStar(int i)
{
// 擦掉原來的星星
putpixel((int)star[i].x, star[i].y, 0);
// 計算新位置
star[i].x += star[i].step;
if (star[i].x > 640) InitStar(i);
// 畫新星星
putpixel((int)star[i].x, star[i].y, star[i].color);
}
// 主函數
int main()
{
srand((unsigned)time(NULL)); // 隨機種子
initgraph(640, 480); // 打開圖形窗口
// 初始化所有星星
for(int i=0; i<MAXSTAR; i++)
{
InitStar(i);
star[i].x = rand() % 640;
}
// 繪製星空,按任意鍵退出
while(!_kbhit())
{
for(int i=0; i<MAXSTAR; i++)
MoveStar(i);
Sleep(20);
}
closegraph(); // 關閉圖形窗口
return 0;
}
基於 Raylib
除了 API 改用 raylib 外,Star 自身的修改和繪製從面向過程改爲了面向對象。
// based on https://codebus.cn/yangw/starry-sky
#include "raylib.h"
#include "raylib_helper.hpp"
#include <stdlib.h>
#include <time.h>
#define WIDTH 640
#define HEIGHT 480
#define MAXSTAR 200 // 星星總數
class Star
{
public:
double x;
int y;
double step;
Color color;
void init()
{
x = rand() % WIDTH;
y = rand() % HEIGHT;
step = (rand() % 5000) / 1000.0 + 1;
int c = (int)(step * 255 / 6.0 + 0.5); // 速度越快,顏色越亮
color = make_color(c, c, c, 255);
}
void move()
{
// 擦掉原來的星星
// putpixel((int)x, y, 0);
DrawPixel(x, y, BLACK);
// 計算新位置
x += step;
if (x > WIDTH)
{
init();
}
// 畫新星星
//putpixel((int)x, y, color);
DrawPixel(x, y, color);
}
};
Star star[MAXSTAR];
void startup()
{
srand((unsigned)time(NULL));
InitWindow(WIDTH, HEIGHT, "Starry Sky");
SetTargetFPS(60);
// 初始化所有星星
for (int i = 0; i < MAXSTAR; i++)
{
star[i].init();
}
}
void update()
{
for(int i=0; i<MAXSTAR; i++)
{
star[i].move();
}
}
void show()
{
BeginDrawing();
{
ClearBackground(BLACK);
}
EndDrawing();
}
int main()
{
startup();
while (!WindowShouldClose())
{
update();
show();
}
CloseWindow();
return 0;
}