47 lines, 7 of them comments ยท 368 tokens, written in 3 seconds for $0.0040


 1  let x, y; // Ball position
 2  let xspeed, yspeed; // Speed of the ball
 3  let ballSize = 50; // Diameter of the ball
 4  
 5  function setup() {
 6    createCanvas(400, 400);
 7    // Initial position of the ball at the center
 8    x = width / 2;
 9    y = height / 2;
10    // Random speeds for the ball
11    xspeed = random(2, 5);
12    yspeed = random(2, 5);
13    fill(random(255), random(255), random(255)); // Random ball color on load
14  }
15  
16  function draw() {
17    background(220);
18    moveBall();
19    bounceBall();
20    drawBall();
21  }
22  
23  function moveBall() {
24    x += xspeed;
25    y += yspeed;
26  }
27  
28  function bounceBall() {
29    // Check for a collision with the edges
30    if (x > width - ballSize / 2 || x < ballSize / 2) {
31      xspeed *= -1;
32      changeColor();
33    }
34  
35    if (y > height - ballSize / 2 || y < ballSize / 2) {
36      yspeed *= -1;
37      changeColor();
38    }
39  }
40  
41  function drawBall() {
42    ellipse(x, y, ballSize, ballSize);
43  }
44  
45  function changeColor() {
46    fill(random(255), random(255), random(255));
47  }