Go Down

Topic: Starting the program over thoughts please (Read 352 times) previous topic - next topic

kevin1ab

Hello,
I'm getting better at coding and to learn more I'm writing a game that at this time prints to the serial console
and accepts [y] or [n] input from the keyboard to tell the program what to do.
When I'm done I hope to port it to my LCD shield and use the UP and DOWN buttons for [y] and [n].
With that lead up, there are points in the program where the game play ends before the end of
all the code in void_loop().  There is randomseed data in play so the game may go 1 step
or all the way thru 6 steps before finishing. This makes each game play unique, challenging the player
to make choices for the next move.

At each step, the player is notified if they won or lost.

Then they are asked to play again [y] (of course they do :) )

I would like at this point to have the program start from scratch at the top of void_loop() again
without running any more code.

Code: [Select]

Serial.print("You Won!. Game Over");
delay (3000);
Serial.print("Play Again???");
while(!Serial.available()>0) Serial.read(); { 
  key = Serial.read();
  if (key == 'y'){

//  EXIT THE PROGRAM AND RESTART FROM THE TOP
//sorry to yell :)       



I know that a 'break' jumps out of a loop but I'm not jumping from a loop so that won't work.
Most of my steps are wrapped up as functions.

Code: [Select]

{
step1 ();
step2 ();
step3 ();

//etc, etc

}


Is this a good reason to use a goto label?
have it goto a bailout: label ?

Any other smart ways to do this?

Thanks in advance.
Kevin




Arrch

Don't use GoTo

Post all of your code, not snippets.

What you're looking for is likely a return statement, but that is just a shot in the dark without seeing all of your code.

michinyon

If you want to go back to the start of the loop() function,  there is at least 2 different approaches

Put your code inside another while or for loop,  and then break from that loop.

Put in a "return" statement.  This should return from loop() to the hidden main() function,  which
will start the loop() function again.  I don't recall ever seeing an arduino program do this, but there
is no reason I can think of why it won't work.

kevin1ab

Thank you guys. I did think about putting the whole thing in a loop and using a break.
I didn't understand the return function so you just helped me learn [and I read it, and now it is crystal clear] and I
thank you for that.
Kevin

UKHeliBob

Personally I would still favour a while loop.  That way there is no confusion about what you are actually returning to.  It is also easier to see what condition(s) cause the while loop to end.
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

Go Up