Blackiey
Blackiey

Reputation: 23

How to return to the game? after finishing the game

I am doing a TicTacToe Program, the only missing part is to have the user to choose whether to quit the game or to replay. I can't find a way to "return" to the gaming.

import java.io.*;

public class Expierment
{
        static char c1 [] = new char[10];
        static char c2 [] = new char[10];
        static char c3 [] = new char[10];
        static char p1;
        static char p2;
        static boolean gameOver = false;
        public static void main(String args[])
        {
            int counter = 0;
            int p1Wins = 0;
            int p2Wins = 0;
            int r1 = 0;
            int r2 = 0;
            int r3 = 0;
            int r4 = 0;
            int r5 = 0;
            int r6 = 0;
            int r7 = 0;
            int r8 = 0;
            int r9 = 0;
            int pick1 = 0;
            int pick2 = 0;
            int pick3 = 0;
            int pick4 = 0;
            int pick5 = 0;
            int pick6 = 0;
            int pick7 = 0;
            int pick8 = 0;
            int pick9 = 0;
            char turn = 'X';
            int choice = menu();
            switch(choice)
            {
                case 1:
                    System.out.println("The game is called 'Tic-Tac-Toe', you should have known it. If you don't, search it.")  ;
                case 2:
                    gameOver = false;
                    break;
                case 3:
                    System.out.println("\nSee you next time !!");
                    return;
                default:
                    System.out.println("\nYou hit the wrong key......\n");
                    return;
            }//end of switch
            System.out.println("\nPlayer 1 initials ?");
            String n1 = GCS();
            p1 = n1.charAt(0);
            System.out.println("\nPlayer 2 initials ?");
            String n2 = GCS();
            p2 = n2.charAt(0);
            c1[2]='1';
            c2[2]='2';
            c3[2]='3';
            c1[1]='4';
            c2[1]='5';
            c3[1]='6';
            c1[0]='7';
            c2[0]='8';
            c3[0]='9';
        printBoard ();
        while(gameOver!=true)
        {
            System.out.println("Which spot ?");
            int pick = Integer. parseInt(GCS());
                switch (pick)
            {
                case 1:
                    if (r1<1)
                {
                    c1[2] = turn;
                    r1++;
                }
                else
                {
                    System.out.println("That column is full, pick another.\n");
                    continue;
                }
                    break;                  
                case 2:
                    if (r2<1)
                {
                    c2[2] = turn;
                    r2++;
                }
                else
                {
                    System.out.println("That column is full, pick another.\n");
                    continue;
                }
                    break;                  
                case 3:
                    if (r3<1)
                {
                    c3[2] = turn;
                    r3++;
                }
                else
                {
                    System.out.println("That column is full, pick another.\n");
                    continue;
                }
                    break;
                case 4:
                    if (r4<1)
                {
                    c1[1] = turn;
                    r4++;
                }
                else
                {
                    System.out.println("That column is full, pick another.\n");
                    continue;
                }
                    break;
                case 5:
                    if (r5<1)
                {
                    c2[1] = turn;
                    r5++;
                }
                else
                {
                    System.out.println("That column is full, pick another.\n");
                    continue;
                }
                    break;
                case 6:
                    if (r6<1)
                {
                    c3[1] = turn;
                    r6++;
                }
                else
                {
                    System.out.println("That column is full, pick another.\n");
                    continue;
                }
                    break;
                case 7:
                    if (r7<1)
                {
                    c1[0] = turn;
                    r7++;
                }
                else
                {
                    System.out.println("That column is full, pick another.\n");
                    continue;
                }
                    break;
                case 8:
                    if (r8<1)
                {
                    c2[0] = turn;
                    r8++;
                }
                else
                {
                    System.out.println("That column is full, pick another.\n");
                    continue;
                }
                    break;
                case 9:
                    if (r9<1)
                {
                    c3[0] = turn;
                    r9++;
                }
                else
                {
                    System.out.println("That column is full, pick another.\n");
                    continue;
                }
                    break;
                default:
                    System.out.println("Seriously?! Pick a possible spot.\n");
                    continue;
                }//end of switch
            if (turn=='X') turn = 'O';
            else turn = 'X';
            printBoard();
            if (checkWinner())
            {
                while(gameOver==true)
                {
                    int Echoice = EGM();
                    switch(Echoice)
                    {
                        case 1:
                            System.out.println("The game is called 'Tic-Tac-Toe', you should have known it. If you don't, search it.")  ;
                        case 2:
                            gameOver = false;
                            menu();

                            break;
                        case 3:
                            System.out.println("\nSee you next time !!");
                            return;
                        default:
                            System.out.println("\nYou hit the wrong key......\n");
                            return;
                    }//end of switch
                }//end of while true
                return;
            }
            counter ++;
            if (counter==9)
            {
                System.out.println("\n\nYou tied.\n");
                return;
            }
        }//end of while not true
    }//end of main

    public static boolean checkWinner()
    {
            for (int k=0; k<2; k++)
        {
            if ((c1[k]!=' ')&&(c1[k]==c2[k])&&(c1[k]==c3[k]))
            {
                System.out.println("\nYo " + c1[k] + " is the winner!\n");
                gameOver=true;
                return true;
            }//checks column 1-3 horizontally
        }//end of horizontal check

        for (int m=0; m<2; m++)
        {
            if((c1[m]!=' ')&&(c1[m]==c1[m+1])&&(c1[m+1]==c1[m+2])&&(c1[m]==c1[m+2]))
            {
                System.out.println("\nYo " + c1[m] + " is the winner!\n");
                gameOver=true;
                return true;
            }//checks column 1 vertically
            if((c2[m]!=' ')&&(c2[m]==c2[m+1])&&(c2[m+1]==c2[m+2])&&(c2[m]==c2[m+2]))
            {
                System.out.println("\nYo " + c2[m] + " is the winner!\n");
                gameOver=true;
                return true;
            }//checks column 2 vertically
            if((c3[m]!=' ')&&(c3[m]==c3[m+1])&&(c3[m+1]==c3[m+2])&&(c3[m]==c1[m+2]))
            {
                System.out.println("\nYo " + c3[m] + " is the winner!\n");
                gameOver=true;
                return true;
            }//checks column 3 vertically
                if ((c1[m]!=' ')&&(c1[m]==c2[m+1])&&(c1[m]==c3[m+2]))
            {
                System.out.println("\nYo " + c1[m] + " is the winner!\n");
                gameOver=true;
                return true;
            }//checks upward diagonal
                if ((c3[m]!=' ')&&(c3[m]==c2[m+1])&&(c3[m]==c1[m+2]))
            {
                System.out.println("\nYo " + c1[m] + " is the winner!\n");
                gameOver=true;
                return true;
            }
        }//end of vertical check
                return false;
    }//end of checkWinner

    public static void printBoard()
    {
        System.out.println("_______");
        for (int j = 2; j > -1; j--)
        {
            System.out.println("|" + c1[j] + "|" + c2[j] + "|" + c3[j] + "|");
            System.out.println("-------");
        }
    }//end of printBoard

    public static int menu()
    {
        System.out.println("Tic-Tac-Toe ~ Main Menu\n\n1. Instructions\n2. Play a 1 player game"+"\n3. Exit\n");
        int selection = Integer.parseInt(GCS());
        return selection;
    }//end of menu

    public static int EGM()
    {
        System.out.println("Tic-Tac-Toe ~ End of Game Menu\n\n1. Instructions\n2. Play again"+"\n3. Exit\n");
        int Eselection = Integer.parseInt(GCS());
        return Eselection;
    }

    public static String GCS()
    {
        int noMoreInput=-1;
        char enterKeyHit='\n';
        int InputChar;
        StringBuffer InputBuffer = new StringBuffer(100);

        try
        {
            InputChar=System.in.read();
            while(InputChar != noMoreInput)
            {
                if((char)InputChar !=enterKeyHit)
                {
                    InputBuffer.append((char)InputChar);
                }
                else
                {
                    InputBuffer.setLength(InputBuffer.length()-1);
                    break;
                }
                InputChar=System.in.read();
            }
        }
        catch (IOException IOX)
        {
            System.err.println(IOX);
        }
        return InputBuffer.toString();
        }//end of GCS
}//end of public class

Upvotes: 0

Views: 418

Answers (5)

ILMTitan
ILMTitan

Reputation: 11017

Even dirtier than the do-while method. Will eventually cause stack-overflow.

//your current main method
boolean playAgain = prompt the user
if(playAgain){
    main(args);
}

Upvotes: 1

Yanick Rochon
Yanick Rochon

Reputation: 53546

With the current program layout, there is no "clean" way to accomplish that. Here are some constructive criticism :

  • Your main method should only be a bootstrapper

You should only initialize your program in your main method. Consequently, try to have 1 method doing only 1 thing. You're design now has the game menu and game main loop inside the same method.

Your game loop could look like this:

while still playing
   read input from user
   if game is active
      process game input
      update game
   else
      process menu input
      update menu

This way, you only need to swith the game is active state for the menu or the game. Etc.

Your GCS method is way too complicated, just replace it with :

Scanner scanner = new Scanner();     // put this somewhere at the class level (so it is reusable)
...
String input = scanner.nextLine();   // put this somewhere in a method reading an input
  • Variable abuse

Instead of initializing many variables, perhaps (like other have suggested) you could use arrays, or more specifically a 2-dimensional array.

int grid[][] = new int[3][3];
// grid[0][0] points to the top-left cell, grid[2][2] points to the bottom right one

Or you could use a single int to store everything; represent your grid as a bit array

int grid = 0;   // empty grid
...
// set player move
grid |= (1 << (y*3)+x) << PLAYER_OFFSET;  // PLAYER_OFFSET: 0=player 1, 16=player 2
// reset (clear) player move
grid &= ~((1 << (y*3)+x) << PLAYER_OFFSET); // ...
// check if player move is set
boolean isSet = (grid >> ((1 << (y*3)+x) << PLAYER_OFFSET)) && 1;   // ...

Why are bit arrays cool? Because to check if a player wins, you don't need fancy for..loop and other complicated algorithms, just validate against a winning pattern... :

int pattern = 273; // test for diagonal from [0,0] to [2,2], or bits "100 010 001"
boolean isWinning = (grid && (pattern << PLAYER_OFFSET)) != 0;

That's it!


Also, using 0 to 9 may be good to identify the grid cell, however as input value is not that intuitive for a player. Many games (chess, checkers, LOA, etc.) and applications (Excel, Calc, etc.), for example, are using the Algebraic chess notation system. Converting the notation in x and y is very simple. For example :

boolean cellPlayed = false;
while (!cellPlayed) {
   String cellStr = scanner.readLine().toLower();   // ex: "b2" for the center cell
   try {
      int gridx = cellStr.charAt(0) - 'a';   // ex: for "b2" should return 1
      int gridy = cellStr.charAt(1) - '1';   // ex: for "b2" should return 1

      grid(gridx][gridy] = playerValue;      // 1 for "player 1" and 2 for "player 2"
      cellPlayed = true;
   } catch (Exception e) {
      System.out.println("Error! Invalid input");
   }
}

Don't feel discouraged! We all start somewhere! :)

Upvotes: 1

awestover89
awestover89

Reputation: 1763

Things would be a lot more clear with a more concise main method. The really quick and dirty way would be to copy everything in your main method into a new method and just call that method from the main and when the user chooses to start a new game.

Upvotes: 0

Platinum Azure
Platinum Azure

Reputation: 46193

You really should get some of that code out of the main function.

Specifically, I'd put the whole game loop in a separate function, maybe called playGame(), which contains the logic for playing the game, checking winner, etc., and either returns the winner or just prints the winner and returns void.

Then the main function could put a call to playGame() in a loop, and at the end of the loop, ask the user if s/he wants to play again.

In general, you want each function to do one logical task. You've done well with moving checkWinner out, now do the same with some of the other code.

If you need help on the "asking the user about playing again", leave a comment and I'll make an edit to address that.

Upvotes: 2

Amir Afghani
Amir Afghani

Reputation: 38541

quick and dirty pseudo-code - not modular

do {    
   //everything in your main goes here
   .
   .
   .    
   playAgain = prompt the user
} while(playAgain);

Upvotes: 1

Related Questions