Home > Enterprise >  "Press key to play again" Snake project in C
"Press key to play again" Snake project in C

Time:10-17

Hi im making snake game and its almost done but i want to add play again button that restarts the game and i dont know how Any ideas?

Main file:

#include "SourceCode&Setup.h" //Game source code
#include <stdio.h>    
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <math.h>


void main()
{

    setup();
    while(GameOver!=1)
    {
        DrawBorder();
        Input();
        Movement();
    }
    
}

CodePudding user response:

You could simply put your gameplay into a do {} while() loop:

#include "SourceCode&Setup.h" //Game source code
#include <stdio.h>    
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <ctype.h>
#include <math.h>

int main(void)
{
    char again;
    do 
    {
        setup();
        while(GameOver!=1)
        {
            DrawBorder();
            Input();
            Movement();
        }

        printf("Play again (y/n)?\n");
        int ret = scanf(" %c", &again);
        if (ret != 1)
          again = 'n';  // don't play again in case of error.
        
    } while (tolower(again)=='y');    
}

Depending on what setup does, you may need to adjust it to be able to be called multiple times.

CodePudding user response:

On a high level I would suggest the following:

  1. Create a initializeGame() function that sets all variables used during the game to its default. For example setting the score to 0
  2. Use getchar() to wait for a keypress after finishing the game. This pauses the program until the user presses a key in the console. If the input char is 'n' then exit()
  3. In your main() function: Create another while(true) loop that resets the game state after every play

CodePudding user response:

LABLE:
     while(GameOver!=1)
    {
    DrawBorder();
    Input();
    Movement();
  cout<<"Press one to play again:";
  cin>>x;
  if(x==1)
    {
       goto LABLE;
     }
  else
      break; 
    }
  
  •  Tags:  
  • c
  • Related