Stopping a forever loop with buttons

25 views
Skip to first unread message

Lauren Rennison

unread,
Nov 9, 2020, 11:08:31 PM11/9/20
to Pencil Code
I would like my students to create virtual alarms with Pencil Code.

I am stuck on a problem where I have various buttons: 
one button is to confirm everything is okay;
the second button sets off the alarm in a forever loop (I don't want it to stop until another button or key is pressed);
the third button resets the alarm (with the hope of overriding the forever loop)

I have tried various different loop options and also tried the stop() code but I can't get anything to work the way I have in mind.

My code so far is this: 

start = ->
  button 'Click this if everything is okay!', ->
    wear 'smile'
  button 'Set off alarm', ->
    forever 1, ->
      dot green, 30
      pause 0.1
      dot red, 30
      pause 0.1
  button 'Reset alarm', -> 
    wear 'turtle'
    cs()
    do start
 
do start

Is there a way that I can add or change something something in either of the the 'Reset alarm' or the 'Set off alarm' buttons to make it so that if I press a key on the keyboard or click the third button, the whole code clears the screen and goes back to the starting point? Otherwise I have to use the usual PencilCode stop/play buttons or refresh the page entirely.

Also please let me know if this might also be affected by any sound effects (tone or play).

Thanks,

Lauren

Andrew Petusky

unread,
Sep 24, 2024, 12:40:58 PM9/24/24
to Pencil Code
This response is about 4 years too late... But it was a nice idea and deserving of a response!

The forever function returns a number value that can be used with stop() to end that specific "forever loop".  I used the variable f1Code to record it.  But to make f1Code accessible in the function that gets called by the reset button, I had to define it outside of the set off alarm button.  (Variable scoping is a convoluted topic.  These notes attempt to explain https://pencilcoder.net/notes/CustomFunctions_Notes.html )


speed 10  # made it faster so that animations in the forever loop complete
          #  within a second

start = ->
  f1Code = undefined  #use a variable outside the scope of the callback functions
  #  (i.e., the anonymous functions created by the -> in the button code)

  button 'Click this if everything is okay!', ->
    wear 'smile', 100

  button 'Set off alarm', ->
    wear green #you can't see anything if the smile is in the way!
    f1Code = forever 1, ->
      dot green, 30
      tone 440, 0.2

      pause 0.1
      dot red, 30
      pause 0.1
  button 'Reset alarm', ->
    wear 'turtle'
    #see f1Code
    if not( f1Code==undefined ) #this prevents a crash if the forever does not exist yet
      stop(f1Code)  
      f1Code = undefined #reset f1Code

      cs()
      do start
 
do start

Reply all
Reply to author
Forward
0 new messages