How to Create Turn-Based Games

Save

Game development can be fun and exciting. However, it's also a tremendous challenge with a steep learning curve. While the old two player game Tic Tac Toe may not be as exciting as Quake or Advance War, it introduces some fundamentals of working turn-based game design. Input must be taken in from the player, processed according to the rules of the game, and output again in a form the player can understand.

Things You'll Need

  • Computer
  • Java Development Kit
  • Java Runtime Environment
  • Java IDE
  • Create a new class called TicTacToeGame. If you are using a Java IDE such as Netbeans or Eclipse, this will be handled automatically for you. If you are using a text editor and the command line compiler, then you'll need to create a file named TicTacToeGame.java and insert the following class skeleton into it:

    /**

    • This class represents a 2 player game of TicTacToe.
      */
      class TicTacToeGame {
      // All other code in the tutorial will go in this space!
      }
  • Define your variables. There are a few ways you could do this, but the way this tutorial chooses is a simple 2D array of single characters to represent the board, with the current player, either X or O, stored as a character. Also, to ensure consistency and enhance readability of your code later, define a few constants for the characters used for X, O, and empty. Insert the following:

    /**
    * The board. The char is either 'X', 'O', or ' ' . These are defined in the constants.
    */
    private char[][] board = new char[3][3]

    GO

    char currentPlayer

    GO

    public static final char X = 'X'

    GO

    public static final char O = 'O'

    GO

    public static final char NONE = ' '

    GO

    Whenever a value is stored on the board, compared to another value on the board, or stored in currentPlayer, you should use the your declared constants X, Y, and NONE. As mentioned above, this enhances readability and robustness of code.

  • Initialize the game. Only one constructor is needed for our TicTacToe board.

    /**

    • Initializes the board.
      */
      public TicTacToeBoard() {
      // You could also use a double-nested for loop to fill the board.
      board[0][0] = NONE
      GO

      board[0][1] = NONE

      GO

      board[0][2] = NONE

      GO

      board[1][0] = NONE

      GO

      board[1][1] = NONE

      GO

      board[1][2] = NONE

      GO

      board[2][0] = NONE

      GO

      board[2][1] = NONE

      GO

      board[2][2] = NONE

      GO

      // Set the current player equal to the X constant you defined earlier.
      currentPlayer = X

      GO
      }

  • Add the \"makeMove\" method. This method should take three arguments: the xCoord, yCoord, and currentPlayer.

     /**
    * Make a move.
    * @param xCoord the x coord to mark
    * @param yCoord the y coord to mark
    * @param player the player to use. This should be one of the constants : X, O
    * @return true if move occurred. False if move is forbidden because square is full.
    */
    boolean makeMove(int xCoord, int yCoord, char player) {
    if (board[xCoord][yCoord] == NONE) {
    board[xCoord][yCoord] = player

    GO

            return true

    GO

        } else {
    return false

    GO

        }
    }

    Remember to always define your JavaDoc comments.

  • Create a method to draw the board. There are a number of ways to do this, but the most elegant way is a simple, double-nested loop.

      /**
    * Draws the current board to the console using System.out
    */
    void drawBoard() {
    for (int x = 0; x < board.length; x++) {
    for (int y = 0; y < board[x].length; y++) {
    	// Draw the X and Os on the board so far (as well as the blank spaces).
    	System.out.print(\" \" + board[x][y] + \" \")

    GO

            	// Draw the vertical lines between columns.
    if (y < 2) {
    System.out.print(\"|\")

    GO

                }
    }
    System.out.println()

    GO

            // Draw horizontal lines between rows.
    System.out.println(\"---+---+---\")

    GO

        }

    }

  • Write your game play loop. All games contain some sort of game loop that defines the start of the game, executes the game rules, and tests for a game winner or end condition. Here is the game play loop for the TicTacToe game:

     void play() {
    boolean playing = true

    GO

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in))

    GO

        while (playing) {

    try {
    boolean validMove = false

    GO

                // Keep asking the player for coordinates until she gives a valid response!
    while (!validMove) {
    drawBoard()

    GO

                    System.out.println(\"Current Player is: \" + currentPlayer)

    GO

                    System.out.println(\"What x coordinate? \")

    GO

                    // READ COORDINATES
    int xCoord = new Integer(in.readLine())

    GO

                    System.out.println(\"What y coordinate? \")

    GO

                    int yCoord = new Integer(in.readLine())

    GO

                    validMove = makeMove(xCoord, yCoord, currentPlayer)

    GO

                    if (!validMove) System.out.println(\"ERROR: Invalid move!\")

    GO

                }

    // Change the current player.
    if (currentPlayer == X) {
    currentPlayer = O

    GO

                } else {
    currentPlayer = X

    GO

                }

    // If we have a winner, then congratulate them and end the game!
    if (this.testWinner() != NONE) {
    drawBoard()

    GO

                    System.out.println(\"Winner is : \" + this.testWinner())

    GO

                    return

    GO

                }
    // Test for input errors from the keyboard, and print debug information if one is encountered. This is not just a good idea, it is required by the in.ReadLine() function.
    } catch (IOException e) {
    e.printStackTrace()

    GO

            }
    }

    (see references 1)

  • There is one function mentioned in the play() loop that has not yet been written: testWinner(). It is the most difficult function of all, and there are many ways to go about testing for the TicTacToe winner. The following is the most obvious, but not the most efficient, solution to the problem:

    /**

     * This function will test the board to see if there is a winner.
    * @return X if X has won the game. O if O has won the game. NONE if none have won the game. This uses the constants provided by the class.
    */
    char testWinner() {

    // TOP ROW

        if (board[1][0] == board[0][0] &&
    board[1][0] == board[2][0]) {
    return board[1][0]

    GO

        }

    // MIDDLE HORIZONTAL ROW

        if (board[1][1] == board[0][1] &&
    board[1][1] == board[2][1]) {
    return board[1][1]

    GO

        }

    // BOTTOM ROW

        if (board[1][2] == board[0][2] &&
    board[1][2] == board[2][2]) {
    return board[1][2]

    GO

        }

    // LEFT ROW

        if (board[0][1] == board[0][0] &&
    board[0][0] == board[0][2]) {
    return board[0][0]

    GO

        }

    // MIDDLE VERTICAL ROW

        if (board[1][1] == board[1][0] &&
    board[1][0] == board[1][2]) {
    return board[1][1]

    GO

        }

    // RIGHT ROW

        if (board[2][1] == board[2][0] &&
    board[2][0] == board[2][2]) {
    return board[2][0]

    GO

        }

    // TOP LEFT DIAGONAL

        if (board[0][0] == board[1][1] &&
    board[0][0] == board[2][2]) {
    return board[0][0]

    GO

        }

    // TOP RIGHT DIAGONAL

        if (board[0][2] == board[1][1] &&
    board[0][2] == board[2][0]) {
    return board[0][2]

    GO

        }

    // If it gets here, no one won this round.

        return NONE

    GO

    }

    It simply proceeds through the board, testing every possible winning combination of squares and seeing if one of the players has it.

  • Create the main function. Finally, you'll need to create a main function to give your program a place to start. This main function will be very simple: It will just initialize your TicTacToeGame class and start the play() method. Insert the following function into your class:

    public static void main(String[] args) {
    TicTacToeGame game = new TicTacToeGame()
    GO
    game.play()
    GO
    }

    Now you have a functioning TicTacToe game!

References

Promoted By Zergnet

Comments

You May Also Like

  • How to Program 3D Games in Java

    If you want to generate 3D games, Java provides you an API, which best suits for creating 3D games. The java 3D...

  • How to Make a Strategy Board Game

    Strategy board games have been around for thousands of years, and come in a dizzying variety. With so many games already around,...

  • How to Make a Java Game With NetBeans

    NetBeans is a popular integrated development environment for the Java programming language. It is sponsored by Oracle and is free to use...

  • Fun Games That Are Similar to Wizard 101

    "Wizard101" is a free massively multiplayer online role-playing game (MMORPG) featuring a turn-based combat system. It's a game designed for preteens, but...

  • Excel Game Tutorials

    Microsoft Excel is a versatile program capable of many tasks. Data management, charts, and reports are commonly created using the program. But...

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!