In our latest workshop we began to look at classes and arrays and agents.
During the workshop we created squares which could move randomly about on the canvas and we could create new additions each time the mouse was clicked. Firstly we were introduced to creating classes, which we hadn’t done before. This is done by using the word “class” and then putting all the data inside square brackets. The class then has to be called at the start of the document.
Above you can see that we created a class called “Agent”, then we put in some data (float x, y; and color c;) then in our “constructor are we create a function called “Agent” with three parameters named x, y and c. Inside the function agent we used “this” which tells processing that we want to use the global variable x, and then we assigned that to the local variable x (inside the parameters). In the methods section we created a method called void update which contained the information that we wanted to use for our squares when they are called. Then in the draw section of the class we created a the squares using the rect function and assigned them the variables x and y, which are equal to random(-10, 10); and random(-50, 50);
Then in the main section of the code we created an Arraylist called agents at the top of the document. In the setup section we used “new” to assign the arraylist agents to a new arraylist, which means that when we click the mouse we create a new addition to the arrayList, which means that each one is unique and move to different pixels to one another (as we used random to determine where the squares appear on the canvas). In the draw section we created a for loop with the variable i which states that while i is less than agents.size() then iterate i. Inside the for loop we called the Class Agent and named it agent (which was really confusing) and then assigned agent to get i. We then also assigned agent to the methods update and draw, which we had created in the class beforehand. Finally we created another function called mousePressed and made a new Agent class called “tmpAgent” which created a new Agent each time the mouseX and mouseY were used and also made the colour random.
I found this quite confusing (as my explanation probably suggests) and I think that I will have to practice quite a lot to fully understand how this code works (and it will probably take me a long time to be able to write code like this off the top of my head). But this has been a good introduction to really interesting concepts in programming.To take a look at a live version of the code click here.