• c++ 简单的动态银河星空绘制(类应用)


    话不多说直接贴代码:

     1 #include <graphics.h>
     2 #include <time.h>
     3 #include <conio.h>
     4 
     5 #define MAXSTAR 500 // 星星总数
     6 
     7 class  star
     8 {
     9 private:
    10     int x;
    11     int y;
    12     int color;
    13     double step;
    14 public:
    15     star();//默认构造函数初始化
    16     void move(void);
    17 };
    18 star::star()
    19 {
    20     x = rand() % 640;
    21     y = rand() % 480;//产生0-480的的坐标
    22     step = (rand() % 5000) / 1000.0 + 1;
    23     color = (int)((step / 6) * 255 + 0.5);
    24     color = RGB(color, color, color);
    25 }
    26 
    27 void star::move()
    28 {
    29     putpixel(x, y, BLACK);
    30     x = x + (int)step;
    31     if (x > 640)
    32     {
    33         x = 0;
    34         y = rand() % 480;//产生0-480的的坐标
    35         step = (rand() % 5000) / 1000.0 + 1;
    36         color = (int)((step / 6) * 255 + 0.5);
    37         color = RGB(color, color, color);
    38     }
    39     putpixel(x, y, color);
    40 }
    41 
    42 // 主函数
    43 void main()
    44 {
    45     srand((unsigned)time(NULL));    // 随机种子
    46     initgraph(640, 480);            // 创建绘图窗口
    47 
    48     star sky[MAXSTAR];
    49 
    50     while (!_kbhit())
    51     {
    52         for (int i = 0; i < MAXSTAR; i++)
    53         {
    54             sky[i].move();
    55         }
    56         Sleep(20);
    57     }
    58     closegraph(); // 关闭绘图窗口
    59 }

     如上述代码所示,代码的基本思想创建一个类里面包含隐藏数据以及类方法作为公共接口,我们首先创建一个类定义的数组,数组的每一个成员代表着一颗星星,我们要想绘制一个动态的银河星空我们就要让星星从左至右依次循环,再一次循环中星星的颜色不变,位移不变只是x轴数据一直在随着step步进,然后擦掉之前自己坐标画出的点,当超过绘制范围时这点的处理很关键,此时要把x=0,而y,color,step这些都要重新进行随机化这样整体的星空效果才能出来,每个星星移位结束后进行延时进行下一轮循环。下面是一个静态的x效果图:

  • 相关阅读:
    456. 132 Pattern
    496. Next Greater Element I
    503. Next Greater Element II
    341. Flatten Nested List Iterator
    232. Implement Queue using Stacks
    225. Implement Stack using Queues
    208. Implement Trie (Prefix Tree)
    思考--为何早晨型人更容易成功
    Listary的使用
    【运维】虚拟机如何安装CentOS
  • 原文地址:https://www.cnblogs.com/yskn/p/9032626.html
Copyright © 2020-2023  润新知