Interactive Graphics

Just using our programming skills to produce static "drawings" is not satisfying. Luckily we have a couple small functions which allow for user interaction - in other words, we'll be able to write mini-games soon!

Our two new friends are:

These two should be used together, wrapped in the endless while loop (you may allow it to exit after some condition though) - so that program repeatedly checks for new click coordinates from user (and may do some action if click happened).

Their definitions are like this:

graph.click()    -- returns two (!) values, for X and Y
graph.delay(millis)

The first function should be used in assignment with two variables on the left (otherwise we only give single X value). The second takes integer parameter - milliseconds to wait (i.e. 1000 is for 1 second).

Let's try the small example which draws circles whenever user clicks on the canvas.

graph.init()
c = 0                  -- circles counter
while c < 10 do        -- let's stop after 10 circles
  x, y = graph.click()
  if x >= 0 then       -- negative value means there was no new click yet
    graph.circle(x, y, 20 + c * 5)
    c = c + 1
  end
  graph.delay(30)
end

As you may note from the comment or by experiment, graph.click() returns -1, -1 if there was no click since the previous call to this function. This prevents program from crazily drawing zounds of circles at the same point.