处理中的创意编程|S1(Random Walker)

创意编程是一种编程方法, 其目的是创建具有表现力和视觉效果的东西, 而不是纯粹具有功能性的东西。这种类型的编程方法用于创建现场艺术品, 图形模拟和可视化算法。存在许多用于创意或视觉编程的工具和库, 其中处理最广泛地使用。处理是一种开放源码的编程语言和IDE, 它是为可视化编程而构建的。可以免费下载处理这里。它也可以作为python方言(processing.py)和javascript框架(p5.js)。在本文中, 我们将构建一个简单的随机沃克程序, 它只是一个在画布上随机移动的球。
每个处理草图通常包含两个功能-

  • setup()–它在开始时被调用一次, 通常用于初始化目的。
  • draw()–默认情况下每秒调用30次, 使动画的默认帧速率为每秒30帧。
实施草图
示例代码已使用处理库和处理IDE用Java编写。
Walker w; //Walker objectvoid setup() //Called at the beginning once { size( 640 , 360 ); //Declaring size of the output window w = new Walker(); //Initializing the new walker object }void draw() //Called every frame { background( 255 ); //Setting a white background w.display(); //Displaying the walker object }

【处理中的创意编程|S1(Random Walker)】实施Walker类
class Walker //The walker class { PVector location; //A vector object representing the locationWalker() //Constructor to initialize the data member. { //Initial location of the walker object is //set to the middle of the output window. location = new PVector(width /2 , height /2 ); }void display() //Function to display the walker object { //Drawing a black circle of radius 10 at location fill( 0 ); ellipse(location.x, location.y, 10 , 10 ); } }

此时,如果我们运行草图,它只显示一个位于输出屏幕中心的球-
为了移动walker对象,我们将向walker类添加一个walk()函数,并在草图中的draw()函数中调用它。我们还在Walker中添加了一个checkEdges()函数,以防止Walker对象移出屏幕。我们还必须修改草图,以包括我们添加到Walker类中的新函数。我们还可以做另外一件事,将background()函数移动到setup()中。这样,背景就不会每次都被更新,我们就能看到沃克物体留下的痕迹。
草图的修改实施
//Program to implement random walkerWalker w; //Walker objectvoid setup() //Called at the beginning once { size(640, 360); //Declaring size of the output window background(255); //Setting a white background w = new Walker(); //Initializing the new walker object }void draw() //Called every frame { w.walk(); //Walking the Walker object w.checkEdges(); //Checking for edges of the output screen. w.display(); //Displaying the walker object }

Walker类的修改实现-
class Walker //The walker class { PVector location; //A vector object representing the locationWalker() //Constructor to initialize the data member. { //Initial location of the walker object is //set to the middle of the output window. location = new PVector(width /2, height /2); }void walk() { //The x and y values of the location //vector are incremented by a random value //between -5 and 5 location.x += random(-5, 5); location.y += random(-5, 5); }//Function to prevent the Walker to move out of the screen void checkEdges() { if (location.x < 0) location.x = 0; else if (location.x> width) location.x = width; if (location.y < 0) location.y = 0; else if (location.y> height) location.y = height; }void display() //Function to display the walker object { //Drawing a black circle of radius 10 at location fill(0); ellipse(location.x, location.y, 10, 10); } }

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

    推荐阅读