Using random in JSP5 - processing

Does someone know how I can fix this problem?
var Arguments [2003,1002,3932,10203,2030,1828912,12912]
var Argument = Arguments[Math.floor(Math.random() * Arguments.length)]
Because of these variables, a random argument is always chosen at the beginning. However, if you are in the program and switch from page to page, it will keep the random value it had at the beginning. I want him to be constantly creating new values.
In the draw function I call the argument like this:
text(Argument, 300,180);

If I understand your question and the comments correctly, you need re-assign Argument to be a different random value each time you switch pages, such as this line every time it switchs:
Argument = Arguments[Math.floor(Math.random() * Arguments.length)];
You don't put var there every time. Give it a value in setup(), then re-assign it when you need another value.
Unless, of course, I completely missed your problem.

In p5.js there is a helpful function called random
so you could use it like this
var Arguments [2003,1002,3932,10203,2030,1828912,12912]
var Argument = Arguments[random(0, Arguments.length - 1)]
you can read more about it here

Make argument into a function.
var Arguments [2003,1002,3932,10203,2030,1828912,12912];
var Argument = function(){
return Arguments[ Math.floor( Math.random() * Arguments.length ) ];
}
text(Argument(), 300,180);

If you make a random selection in setup() it will only happen once in your whole script. Also, Don't choose variable names that might already be used by the system (I suspect "arguments" might be.
let args = [2003,1002,3932,10203,2030,1828912,12912];
let a;
function setup() {
createCanvas(400, 400);
a = random(args);
}
function draw() {
background(220);
textSize(30);
text(a,50,70);
}
function mousePressed() {
a = random(args);
}

Related

mousePressed method is launching prematurely in p5js

I created the following function using p5.js and the mousePressed method is firing immediately when the page loads. It doesn't wait for me to click the button object to display a paragraph containing the ans variable.
What am I doing wrong?
function setup() {
var ans = generate();
var checkMe = createButton('Check Answer');
checkMe.mousePressed(createP(ans));
}
Let's take a closer look at this line:
checkMe.mousePressed(createP(ans));
This could be split into two lines:
var createPValue = createP(ans);
checkMe.mousePressed(createPValue);
In other words, you're calling the createP() function, and then passing the value returned (which is probably undefined) into the mousePressed() function. I'm surprised this doesn't cause an error in the JavaScript console.
Instead, what you want to do is pass a function as a value into the mousePressed() function. Since you need to use a parameter, you might do that this way:
function callCreateP(){
createP(ans);
}
checkMe.mousePressed(callCreateP);
Notice that callCreateP doesn't have parentheses () after its name when we pass it into the mousePressed() function. That's because we're using it as a value instead of directly calling it.
You could shorten that to this line:
checkMe.mousePressed(function(){ createP(ans); });

Processing - If statement and ids

I'm an Italian student and I'm new in programming. I need your help for a school project.
I'm making a blob tracking program using Daniel Shiffman's tutorials. Currently I have 2 blobs on the screen. I am identifying them with 2 IDs: number 0 and number 1.
I need to put some conditions on those blobs: if one blob is in a certain part of the screen and the other one is in another part, I need to call a function.
I don't know how to put the if conditions separately for the two ids. Below is some pseudo code of what I would like to achieve:
for (id==0)
if (...) and
for (id==1)
if(...) then {
void()
}
I would really appreciate any help!
I don't really know where you want the blobs to be when the desired function fires, but I can try to give you an example...
Blob
Assign some sort of position variable, in this case PVector, to your blob object.
class Blob {
PVector position;
Blob (PVector position) {
this.position = position;
}
void update() {
*random movements, etc...*
}
}
Create two blob objects
Create two objects and assign a position to each of them.
Blob[] blobs = new Blob[2];
void setup() {
size(400, 400);
blobs[0] = new Blob(5, new PVector(40, 40));
blobs[1] = new Blob(13, new PVector(100, 100));
}
Check if blobs is at left or right side of the screen
I check if blob[0] is at the left side of the screen and if blob[1] is at right side of the screen. If they are, at the same time, the desiredFunction(); will fire.
void draw() {
for (int i = 0; i < blobs.length; i++) {
blobs.update();
}
if (blobs[0].position.x < (width / 2) && blobs[1].position.x < (width / 2) {
desiredFunction();
}
}
Remember
This is just an example. You could of course check other parts of the screen instead of the left and right parts. You can also use IDs on your blobs instead of an array, I just thought it was better to just use an array in this case.
PS: I wrote this answer without having processing started. The code has certainly a couple of typing errors.
For the example you have described, you can achieve this using the && operator in one if statement.
First assign the conditions you want to test to boolean variables. For example, create the boolean variables id0IsThere, and id1IsThere, and set them to true if the blobs are in the locations you want them to be in. Then use the following if statement:
if (id0IsThere && id1IsThere) {
yourFunction();
}
The && operator means that the code inside the if statement that executes yourFunction() is only executed if both conditions are true. In this case, if both blobs are in the positions you want them to be in. Hope that helps. Read more about if statements and the && operator here:
https://processing.org/reference/if.html
https://processing.org/reference/logicalAND.html

Is there anything wrong with this pattern for a JS library?

I admittedly know little about the inner workings of javascript, but need to make a library and would like to learn (hence asking here). I understand using the closure and exporting to window to not pollute the global namespace, but beyond that it confuses me a bit.
(function() {
var Drop = window.Drop = function() {
var files = [];
var add = function(word) {
files.push(word);
return files;
}
return {
files: files,
add: add
}
}
})()
// All of these seem to be the same?
var a = Drop();
var b = new Drop();
var c = new Drop;
// Each has their own state which is what I want.
a.add("file1");
b.add("file2");
c.add("file3");
Why are all three ways of "initializing" Drop the same?
What exactly gives them the ability to have their own state?
Is there an alternative to the return syntax to export those functions on Drop?
Is there just a flat out better best practice way of creating a self contained library like this?
I have searched around the net, but have found very little consistency on this subject.
The first way (Drop()) just calls the function as normal, so this is the global object (window in browser environments). It does its stuff and then returns an object, as you'd expect.
The second way (new Drop()) creates a new Drop object and executes the constructor with this set to that object. You do not, however, use this anywhere and return an object created from an object literal, so the Drop object is discarded and the object literal returned instead.
The third way (new Drop) is semantically the same as the second; it is only a syntactic difference.
They all have their own state because each time you call Drop, it has its own set of local variables distinct from the local variables of any other call to Drop.
You could transform your code to use the normal new syntax and prototypes. This has a few advantages: namely, you only create the add function once rather than one for each Drop call. Your modified code might look like this:
function Drop() {
this.files = [];
}
Drop.prototype.add = function(word) {
this.files.push(word);
return this.files;
};
By doing this, though, you lose being able to call it without new. There is, however, a workaround: You can add this as the first line inside function Drop:
if(!(this instanceof Drop)) {
return new Drop();
}
Since when you call it with new, this will be a Drop, and when you call it without new, this will be something other than a Drop, you can see if this is a Drop, and if it is, continue initializing; otherwise, reinvoke it with new.
There is also another semantic difference. Consider the following code:
var drop = new Drop();
var adder = drop.add;
adder(someFile);
Your code will work here. The prototype-based code will not, since this will be the global object, not drop. This, too, has a workaround: somewhere in your constructor, you can do this:
this.add = this.add.bind(this);
Of course, if your library's consumers are not going to pull the function out of the object, you won't need to do this. Furthermore, you might need to shim Function.prototype.bind for browsers that don't have it.
No. It's all a matter of taste.
Why are all three ways of "initializing" Drop the same?
// All of these seem to be the same?
var a = Drop();
var b = new Drop();
var c = new Drop;
When you use new in JavaScript to invoke a function, the value of this inside the function becomes the new object.
But the reason they're the same in your case is that you're not using this at all. You're making a separate object using object literal syntax, and returning it instead, so the new has no impact.
What exactly gives them the ability to have their own state?
Because each function invocation makes a new object, each object is entirely different for each invocation.
The functions assigned to the object are recreated in each Drop invocation, and therefore create a closure over the enclosing variable scope. As such, the files array of each invocation is continuously accessible to the functions made in each respective invocation.
Is there an alternative to the return syntax to export those functions on Drop?
Yes. Assign the functions and array to this, and remove the return statement. But that will require the use of new. Alternatively, put the functions on the .prototype object of Drop, and they'll be shared among all instances made using new, but keep the array assigned to this in the constructor so that it's not shared.
For the prototyped functions to reference the array, they would use this.files.
Is there just a flat out better best practice way of creating a self contained library like this?
JavaScript is very flexible. There are many ways to approach a single problem, each with its own advantages/disadvantages. Generally it'll boil down to taking advantage of closures, of prototypal inheritance, or some combination of both.
Here's a full prototypal inheritance version. Also, the outer (function() {})() isn't being used, so I'm going to add a variable to take advantage of it.
(function() {
var totalObjects = 0; // visible only to functions created in this scope
var Drop = window.Drop = function() {
this.files = [];
this.serialNumber = totalObjects++;
}
Drop.prototype.add = function(word) {
this.files.push(word);
return this.files;
};
})();

Google UI Script validateMatches doesn't work, validateNotMatches does

I am designing a form using Google Scripting. I have two text boxes that need to hold time values, and I want to make sure the input is valid.
function setupTimeValidators(widget) {
var timeRe = /(0[1-9])|(1[0-2]):[0-5][0-9] ?[ap]m/i;
var onValid = (UiApp.getActiveApplication().createClientHandler()
.validateMatches(widget, timeRe)
.forTargets(widget)
.setStyleAttribute("background", "#FFFFFF"));
var onInvalid = (UiApp.getActiveApplication().createClientHandler()
.validateNotMatches(widget, timeRe)
.forTargets(widget)
.setStyleAttribute("background", "#FFCCCC"));
widget.addKeyUpHandler(onValid);
widget.addKeyUpHandler(onInvalid);
}
The onInvalid parts changes the textbox background color as soon as I start typing in the textbox, but it never changes back to white when I get to 01:11 pm. (I have tested this with other values.)
I am sure my regular expression works, because I tested it like so:
function test() {
Browser.msgBox(/(0[1-9])|(1[0-2]):[0-5][0-9] ?[ap]m/i.test("01:11 pm")); // true
Browser.msgBox(/(0[1-9])|(1[0-2]):[0-5][0-9] ?[ap]m/i.test("00:11 pm")); // false
Browser.msgBox(/(0[1-9])|(1[0-2]):[0-5][0-9] ?[ap]m/i.test("10:11 pm")); // true
Browser.msgBox(/(0[1-9])|(1[0-2]):[0-5][0-9] ?[ap]m/i.test("10:90 pm")); // false
}
Any ideas what could be going on? Thanks!
You can't use a regex object with validateMatches or validateNotMatches.. you should use a string representation of the regex, as such:
var timeRe = "(0[1-9])|(1[0-2]):[0-5][0-9] ?[ap]m";
var flags = "i";
...
.validateMatches(widget, timeRe, flags)

Basic syntax for an animation loop?

I know that jQuery, for example, can do animation of sorts. I also know that at the very core of the animation, there must me some sort of loop doing the animation. What is an example of such a loop?
A complete answer should ideally answer the following questions:
What is a basic syntax for an effective animation recursion that can animate a single property of a particular object at a time? The function should be able to vary its target object and property of the object.
What arguments/parameters should it take?
What is a good range of reiterating the loop? In milliseconds? (Should this be a parameter/argument to the function?)
REMEMBER:
The answer is NOT necessarily language specific, but if you are writing in a specific language, please specify which one.
Error handling is a plus. {Nothing is more irritating (for our purposes) than an animation that does something strange, like stopping halfway through.}
Thanks!
typically (for jQuery at least) this is not done in a loop, but rather in a series of callbacks.
pseudojavascript:
function startAnimation(element, endPosition, duration) {
var startPosition = element.position;
var startTime = getCurrentTime();
function animate() {
var timeElapsed = getCurrentTime() - startTime;
if (timeElapsed > duration) {
element.position = endPosition;
stopTimer();
} else {
// interpolate based on time
element.position = startPosition +
(endPosition - startPosition) * timeElapsed / duration;
}
}
startRepeatingTimerWithCallbackAndInterval(animate, 1.0 / 30.0);
}
It's also possible to use objects to store starting data instead of closures.
This doesn't completely answer all the points in the question, but it's a starting point.

Resources