Tic-Tac-Toe Game [ User Vs Computer ] On Java

in #utopian-io6 years ago (edited)

What Will I Learn?

  • You will learn how to use variables,loops and arrays
  • You will learn how to make a tic tac toe game

Requirements

  • Knowledge of coding on Java and Eclipse
  • Eclipse and Java must be setted up on the computer.

Difficulty

  • Intermediate

Tutorial Contents

Hello,in this tutorial we are going to make a player vs computer tic-tac-toe game by using java on eclipse.First i defined my needed one line library then named my program.After i defined integer type variables in a,b,c which is my rows and a1,c3 etc. is my columns,then i defined a new static named "Scanner" to scan where user and computer is choosed to make their move.

import java.util.Scanner;


public class TicTacToeGameByDrewie
{

static int A1, A2, A3, B1, B2, B3, C1, C2, C3;

static Scanner sc = new Scanner(System.in);

public static void main(String[] args)
{

In the next step i defined my strings to welcome the user,and show user moves.In the below i used Boolean,this function is used to define True/false situation.GameisWon variable is false at that line because game has not started yet.

public static void main(String[] args)
{
String prompt = "Welcome to Tic-Tac-Toe Game. Please enter your first move: ";
String humanMove = "";
String computerMove = "";
boolean gameIsWon = false; 

Now we are going to use for and if loop together.We made i<=9 because in this game there can be maximum 9 moves.First we define human move."Prompt" is used to get input from the user so we are asking user to make the first movement.

Updateboard is used after user made his/her move,we put in on the screen and then we display is with using "displayboard".We do same thing for the computer in the below and if the user won we use our "gameiswon" class to find out.We define it on user and computers code lines and use if loop to check who won with using "true".In the last line we check if it is draw and if noone won we print out to say "it is a draw".

for (int i = 1; i <=9; i++)
{
humanMove = getMove(prompt);
updateBoard(humanMove, 1);
displayBoard();
if (isGameWon())
{
System.out.println("You beated me!");
gameIsWon = true;
break;
}

if (i < 9)
{
computerMove = getComputerMove();
System.out.println("I will play at " + computerMove);
updateBoard(computerMove, 2);
displayBoard();
if (isGameWon())
{
System.out.println("I beated you!");
gameIsWon = true;
break;
}
prompt = "Please enter your next move: ";
i++;
}
}
if (!gameIsWon)
System.out.println("It's a draw!");
}

1.png

Now game is beggining.First of all we create a class to get users move if user make a wrong input for example "a4" this is a wrong input,we will warn user.Then we create another class,if the input is valid we define all the rows and columns with using "equalsignorecase" this method is basically compares the strings that you have defined.We equal them all to zero so if the user or computer make a movement it will change.

public static String getMove(String prompt)
    {
        String play;
        System.out.print(prompt);
        do
        {
            play = sc.nextLine();
            if (!isValidPlay(play))
            {
                System.out.println("That is not a valid play.");
            }
        } while (!isValidPlay(play));
        return play;
    }

    public static boolean isValidPlay(String play)
    {
        if (play.equalsIgnoreCase("A1") & A1 == 0)
            return true;
        if (play.equalsIgnoreCase("A2") & A2 == 0)
            return true;
        if (play.equalsIgnoreCase("A3") & A3 == 0)
            return true;
        if (play.equalsIgnoreCase("B1") & B1 == 0)
            return true;
        if (play.equalsIgnoreCase("B2") & B2 == 0)
            return true;
        if (play.equalsIgnoreCase("B3") & B3 == 0)
            return true;
        if (play.equalsIgnoreCase("C1") & C1 == 0)
            return true;
        if (play.equalsIgnoreCase("C2") & C2 == 0)
            return true;
        if (play.equalsIgnoreCase("C3") & C3 == 0)
            return true;
        return false;
    }
       

2.png

Now until here user and computer has made their move now we have to show it to user and update it.To do this we use "equalsignorecase" again.Basically we define users movement to the program with evaluating all the possibilities.

public static void updateBoard(String play, int player)
    {
        if (play.equalsIgnoreCase("A1"))
            A1 = player;
        if (play.equalsIgnoreCase("A2"))
            A2 = player;
        if (play.equalsIgnoreCase("A3"))
            A3 = player;
        if (play.equalsIgnoreCase("B1"))
            B1 = player;
        if (play.equalsIgnoreCase("B2"))
            B2 = player;
        if (play.equalsIgnoreCase("B3"))
            B3 = player;
        if (play.equalsIgnoreCase("C1"))
            C1 = player;
        if (play.equalsIgnoreCase("C2"))
            C2 = player;
        if (play.equalsIgnoreCase("C3"))
            C3 = player;
    }
       

In this step because of we haven't made an applet,we have to draw a tic-tac-toe game for the visuality.With using system.print.out as you know we asked user to make first move above after user choose where to move for example "a1" this lines will draw a X to a1.

Then we must define to the program who is playing.To do that we create another class and as you know we defined "square".This is to find out whos turn is it.If it is users turn program will draw X if not it will draw "O".

      public static void displayBoard()
    {
        String line = "";
        System.out.println();
        line = " " + getXO(A1) + " | " + getXO(A2) + " | " + getXO(A3);
        System.out.println(line);
        System.out.println("-----------");
        line = " " + getXO(B1) + " | " + getXO(B2) + " | " + getXO(B3);
        System.out.println(line);
        System.out.println("-----------");
        line = " " + getXO(C1) + " | " + getXO(C2) + " | " + getXO(C3);
        System.out.println(line);
        System.out.println();
    }

    public static String getXO(int square)
    {
        if (square == 1)
            return "X";
        if (square == 2)
            return "O";
        return " ";
    } 

3.png

In the final step we do same thing we did for the user.We define computers move to the program with creating a class and using if loop to evaluate the possibilities and define each line and column and equal to zero.

Then we create another class to define the possibilites of winning.You can win with making 3 line cross,vertical or horizontal so we define all the possibilities and if user or computer made it through the 3 lines correctly we use "return true" which will show the message whoever won.It can be a draw so if any of cases didn't happen it will return false "draw" message.

public static String getComputerMove()
    {
        if (A1 == 0)
            return "A1";
        if (A2 == 0)
            return "A2";
        if (A3 == 0)
            return  "A3";
        if (B1 == 0)
            return  "B1";
        if (B2 == 0)
            return  "B2";
        if (B3 == 0)
            return  "B3";
        if (C1 == 0)
            return  "C1";
        if (C2 == 0)
            return  "C2";
        if (C3 == 0)
            return  "C3";
        return "";
    }

    public static boolean isGameWon()
    {
        if (isRowWon(A1, A2, A3))
            return true;
        if (isRowWon(B1, B2, B3))
            return true;
        if (isRowWon(C1, C2, C3))
            return true;
        if (isRowWon(A1, B1, C1))
            return true;
        if (isRowWon(A2, B2, C2))
            return true;
        if (isRowWon(A3, B3, C3))
            return true;
        if (isRowWon(A1, B2, C3))
            return true;
        if (isRowWon(A3, B2, C1))
            return true;
        return false;
    }
public static boolean isRowWon(int a, int b, int c)
    {
        return ((a == b) & (a == c) & (a != 0));
    }
}

4.png

Whole code with the screenshots and output

    import java.util.Scanner;

public class TicTacToeGameByDrewie
{

    static int A1, A2, A3, B1, B2, B3, C1, C2, C3;

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args)
    {
        String prompt = "Welcome to Tic-Tac-Toe Game. Please enter your first move: ";
        String humanMove = "";
        String computerMove = "";
        boolean gameIsWon = false;


        for (int i = 1; i <=9; i++)
        {

            humanMove = getMove(prompt);
            updateBoard(humanMove, 1);
            displayBoard();
            if (isGameWon())
            {
                System.out.println("You beated me!");
                gameIsWon = true;
                break;
            }

            if (i < 9)
            {
                computerMove = getComputerMove();
                System.out.println("I will play at " + computerMove);
                updateBoard(computerMove, 2);
                displayBoard();
                if (isGameWon())
                {
                    System.out.println("I beated you!");
                    gameIsWon = true;
                    break;
                }
                prompt = "Please enter your next move: ";
                i++;
            }
        }
        if (!gameIsWon)
            System.out.println("It's a draw!");
    }

    public static String getMove(String prompt)
    {
        String play;
        System.out.print(prompt);
        do
        {
            play = sc.nextLine();
            if (!isValidPlay(play))
            {
                System.out.println("That is not a valid play.");
            }
        } while (!isValidPlay(play));
        return play;
    }

    public static boolean isValidPlay(String play)
    {
        if (play.equalsIgnoreCase("A1") & A1 == 0)
            return true;
        if (play.equalsIgnoreCase("A2") & A2 == 0)
            return true;
        if (play.equalsIgnoreCase("A3") & A3 == 0)
            return true;
        if (play.equalsIgnoreCase("B1") & B1 == 0)
            return true;
        if (play.equalsIgnoreCase("B2") & B2 == 0)
            return true;
        if (play.equalsIgnoreCase("B3") & B3 == 0)
            return true;
        if (play.equalsIgnoreCase("C1") & C1 == 0)
            return true;
        if (play.equalsIgnoreCase("C2") & C2 == 0)
            return true;
        if (play.equalsIgnoreCase("C3") & C3 == 0)
            return true;
        return false;
    }

    public static void updateBoard(String play, int player)
    {
        if (play.equalsIgnoreCase("A1"))
            A1 = player;
        if (play.equalsIgnoreCase("A2"))
            A2 = player;
        if (play.equalsIgnoreCase("A3"))
            A3 = player;
        if (play.equalsIgnoreCase("B1"))
            B1 = player;
        if (play.equalsIgnoreCase("B2"))
            B2 = player;
        if (play.equalsIgnoreCase("B3"))
            B3 = player;
        if (play.equalsIgnoreCase("C1"))
            C1 = player;
        if (play.equalsIgnoreCase("C2"))
            C2 = player;
        if (play.equalsIgnoreCase("C3"))
            C3 = player;
    }

    public static void displayBoard()
    {
        String line = "";
        System.out.println();
        line = " " + getXO(A1) + " | " + getXO(A2) + " | " + getXO(A3);
        System.out.println(line);
        System.out.println("-----------");
        line = " " + getXO(B1) + " | " + getXO(B2) + " | " + getXO(B3);
        System.out.println(line);
        System.out.println("-----------");
        line = " " + getXO(C1) + " | " + getXO(C2) + " | " + getXO(C3);
        System.out.println(line);
        System.out.println();
    }

    public static String getXO(int square)
    {
        if (square == 1)
            return "X";
        if (square == 2)
            return "O";
        return " ";
    }

    public static String getComputerMove()
    {
        if (A1 == 0)
            return "A1";
        if (A2 == 0)
            return "A2";
        if (A3 == 0)
            return  "A3";
        if (B1 == 0)
            return  "B1";
        if (B2 == 0)
            return  "B2";
        if (B3 == 0)
            return  "B3";
        if (C1 == 0)
            return  "C1";
        if (C2 == 0)
            return  "C2";
        if (C3 == 0)
            return  "C3";
        return "";
    }

    public static boolean isGameWon()
    {
        if (isRowWon(A1, A2, A3))
            return true;
        if (isRowWon(B1, B2, B3))
            return true;
        if (isRowWon(C1, C2, C3))
            return true;
        if (isRowWon(A1, B1, C1))
            return true;
        if (isRowWon(A2, B2, C2))
            return true;
        if (isRowWon(A3, B3, C3))
            return true;
        if (isRowWon(A1, B2, C3))
            return true;
        if (isRowWon(A3, B2, C1))
            return true;
        return false;
    }

    public static boolean isRowWon(int a, int b, int c)
    {
        return ((a == b) & (a == c) & (a != 0));
    }
}

   

5.png

6.png

7.png

8.png

9.png

Outputs

10.png

11.png

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules, and is considered as plagiarism. Plagiarism is not allowed on Utopian, and posts that engage in plagiarism will be flagged and hidden forever.

Plagiarised from here or somewhere else; it's not your code.

You can contact us on Discord.
[utopian-moderator]

hello,what is plagiarisim? @amosbastian