Reseting an Array to Play Again Java

Tic Tac Toe in Java

How to create a console Tic Tac Toe game in Coffee

Tic Tac Toe Game (created by author)

Tic Tac Toe Game (created by author)

Tic Tac Toe is a classic programming trouble that many developers encounter on their programming journey. Deceptively simple, Tic Tac Toe can teach developers about:

  • Arrays
  • Booleans
  • Conditionals
  • Functions
  • Looping
  • Variables
  • Data Structures

In this tutorial, we will create a console tic tac toe game that relies on a random number generator to command the computer. Where applicable, I will comment on how the code can be improved. This tutorial is going to employ the nigh bones solution to brand this accessible to all skill levels. Always remember to test your lawmaking at the cease of each section to make sure information technology works! Let's begin.

Annotation: You can bask this entire tutorial in a video format on YouTube:

Youtube link to the tutorial

If you become confused at any time, the total code can exist viewed at any time hither .

Building the Board

For simplicity, this entire tutorial will exist built in one course and feature several functions.

The offset footstep in building our game is to create the lath. We are going to utilize a 2D character array full of dashes [ - ], vertical bars [ | ], and spaces [" "] to create our board. Let'southward create an array called gameBoard and fill up it. We volition also create a function called printBoard() to let us to visualize the board.

A visualization of the gameboard (created by the author)

A visualization of the gameboard (created past the writer)

A quick caption of this code snippet. The vertical bars underscores, and spaces represent the grid for the tic tac toe board. You lot can think of the board as spaces 1–9. The offset space is [0][0]. The second space is [0][two]. The tertiary space is [0][four], etc.

All the indices are noted in the comments. The vertical bars exist; notwithstanding, nosotros are not counting them in our game logic.

printBoard() takes in a second array and prints the array contents to the console. Information technology does this past using a nested for loop. The get-go loop tells the computer, for each graphic symbol row within gameBoard, do the 2d loop.

The second loop is asking, for each graphic symbol inside the row, impress the character out. At the end of each second loop, we create a new line to keep all the characters from being printed on the same line.

                /**Note: Printing the lath could be accomplished using the tradition for loop. I think the foreach loop is easier to read. **/                                for (int row = 0; row < gameBoard.length; row++) {
for (int c = 0; c < gameBoard[0].length; c++) {
System.out.impress(gameBoard[row][c]);
}
Organization.out.println();
}

With this function complete, nosotros take finished building the board.

Placing Pieces

At present that we have congenital our board, let's swoop into the game logic. We demand a style of determining what character represents the thespian and the estimator; and a way of placing these characters on the board. So let's create some rules:

  • The role player will be represented past the X grapheme and the number 1
  • The computer will exist represented by the O character and the number two
  • The valid indices for placing pieces are [0][0] , [0][ii] , [0][4], [i][0] , [one][2] , [i][4], [2][0] , [two][2] , [ii][4]

Using all of these rules, we can create a method called updateBoard. It will allow united states of america to update a position in the gameBoard, based on whose turn it is and what position they pick.

Note: This is the form from before; we accept just added the updateBoard() office under the printBoard() function.

updateBoard() takes in the location in which the slice will exist placed, whose turn information technology is, and the state of the gameBoard.

Using our rules from earlier, the player is equal to one, and their character is X; the computer is equal to 2, and their character is O. An if-else statement was used to determine whose plough it is and what is the correct piece to place.

After we adamant whose plow it is, nosotros need to decide where to place the slice. A switch statement is used to separate the different cases. Example ane represents if the player or calculator chose the get-go position. (Which is the meridian left corner) Depending on who chose that position, the corresponding slice is placed in that location, and nosotros interruption out of the switch statement.

                /** Change the position and player to encounter the pieces movement around the board. Insert this office call in the main method and play effectually with the numbers to see the pieces announced. **/                updateBoard(v, ane, gameBoard);
updateBoard(1, 2, gameBoard);
updateBoard(seven, 1, gameBoard);

At this point, you should be able to: add pieces to the lath for both the estimator, and the actor. Be sure to test this feature out by switching from the role player to the computer.

Getting Histrion Input

Now that nosotros can see the board and place pieces on the board, we want the role player to tell the states where the pieces should go. To do this, we are going to create a new function chosen playerMove(). Within of playerMove(), nosotros are going to utilize the congenital-in Scanner class to retrieve histrion input and include some user validation to make certain the user inputs a valid response.

Annotation: This is the class from before; we have only added the playerMove() function under updateBoard(). We have as well imported the Scanner library and created a new Scanner object on line #5. I have left the main method in for readability.

                /** We have created a static Scanner hither considering we will utilize the player input in other areas. If we create only one case to hold the histrion response, we do not have to worry almost deleted or having multiple Scanner objects. **/              

The playerMove() function itself is uncomplicated. We ask the player what position they would like to move to, salvage that response, and feed it into our updateBoard() function.

                /** Line #15 has code for testing this office. Play effectually with feeding unlike values into the function. Do y'all notice that something is off? **/              

If yous played around with calculation dissimilar values into the lawmaking, you might have noticed that something was off. That is, yous can actually identify characters on top of spaces that already contain characters. This is not immune in Tic Tac Toe, and nosotros need to ready this. To exercise this, we will create a role to validate the player'due south motility before nosotros place the slice.

Validating Moves

To validate if the role player fabricated a valid motion, we need to institute what a valid move is. In our world, nosotros are edifice a game made of dashes [ — ], vertical bars [ | ], and spaces [" "]. The dashes and spaces represent blank areas on the board.

                /**         _ | _ | _     Helpful indices:[0][0] , [0][ii] , [0][4]
_ | _ | _ [1][0] , [1][2] , [1][4]
| | [ii][0] , [2][2] , [ii][4]
**/

Thus, if a player chooses a space with anything other than a nuance or space, that position is either invalid or occupied. For example, [0][1] is a vertical bar, and that is an invalid space for our game.

Note: If you look back in the notes or at the diagram, you can see what values coordinate to the valid spaces.

Annotation: Nosotros take updated the playerMove() function and added isValidMove() function underneath that.

The playerMove() function now checks whether the histrion is making a valid move before placing the piece and updating the board. We updated the playerMove() function to include a while loop and a boolean. The boolean is belongings the result of the isValidMove() role. While the result of theisValidMove() is fake, the program will continue looping endlessly until the histrion inputs a valid move.

Diving into the isValidMove() function, the function accepts the motility input by the player and tests to see if the position that the player entered is empty. If the position is empty, and then true is return, else return false because the position is occupied.

                /** You could implement the validation differently. You could create a gear up for empty positions. You could check if the position was in the empty position fix and return true or simulated based on that. You would need to fill the fix with empty positions in the main method before running the game. **/                import java.util.HashSet;                static Set<Integer> emptyPositions = new HashSet<Integer>();                public static void chief(String [] args){                                  char [][] gameBoard = {{'_','|','_','|','_'},{'_', '|',                  
'_','|','_'},{' ','|',' ','|',' '}};
for(int i =1; i<10; i++){
emptyPositions.add(i);
}

playerMove(gameBoard);

...omitting playerMove ... public static boolean isValidMove(int move, char[][] gameboard){ if(!emptyPositions.contains(move)){
render imitation;
}else{
emptyPositions.remove(motion);
return true;
}
/** Y'all can test this out by calling playerMove() a few times in the primary method. Bank check and come across if your invalid moves from before are allowed now. **/

Simulating the Computer

To keep things unproblematic, nosotros are going to simulate the estimator using a random number generator. The computer will cull a random number between 0–9 each turn. We will phone call the isValidMove() function within the computerMove() office to ensure that our reckoner is likewise moving in valid spaces.

Note: This office is placed under the isValidMove() role.

The computerMove() function is very similar to the playerMove() role. The only difference is the introduction of the random Object. Don't forget to import the Random library. The Random object volition let us to generate a number from 0 to 10.

                /** Yous could end the bound of the random number generator at ten.                int movement = rand.nextInt(x);                  
int motion = rand.nextInt(9)+one;
These ii lines of code are equivalent. Something worth pointing out is that the random number generator begins with zero and ends with the spring number not existence included. That zip could crusade united states problems; notwithstanding, we already handled that in our switch case in isValidMove(). Our valid moves only include 1 - ix. Annihilation else outside that range is automatically considered an invalid move and returns a simulated value for isValidMove().
You tin can exam this out by calling computerMove() a few times in the primary method. Mix information technology up and phone call playerMove() too. You lot should showtime to see the beginnings of a game now. **/

Winning the Game

Our game is starting to have shape; only a few steps are left. We need to determine the winning condition or when the game is over. Following traditional tic tac toe rules, the winning conditions are as follows:

  • A diagonal on the left axis
  • A diagonal on the right axis
  • Three across the superlative horizontal
  • Iii across the heart horizontal
  • Three across the bottom horizontal
  • Iii down the correct side
  • Three down the center
  • Iii down the left side

Visual of all possible winning combinations (created by author)

Visual of all possible winning combinations (created by writer)

Those are the winning weather condition; however, the game could also exist in a tied land, in which all the spaces are filled, and none of the winning atmospheric condition have been met. Following that logic, nosotros desire to check if any of the winning conditions have been met each time the player or estimator moves.

                /** Technically, nosotros exercise not take to check after every move. We can start checking after 5 moves, but we volition check after every move to keep information technology elementary. **/              

The simplest way to check if a winning condition has been met is to check whether all the spaces in a combination are the aforementioned. For example, if [0][0], [1][0], and [2][0] are filled, then the thespian or computer has three down the left side vertically and has won. Let's create a new function called isGameOver().

Note: This part is placed nether the computerMove() function.

This role is a behemothic expansion of the logic used earlier. In that location are viii possible win weather condition and 1 tie condition. This function checks to see if any of the win weather condition take been met past either the computer or the actor. If a win status or necktie has been met, then the game is over, and a true outcome will be returned, else a simulated result will be returned.

                /** In that location are many ways to check to see if the player or computer has won. You could:                - Convert all the rows and diagonals into sets, and check the length. A set can only contain unique values. Thus a winning set will simply have a length of 1.                -Make the current snippet smaller and check to see if the space is equal to the space side by side to information technology. For example is [0][0] == [0][2] == [0][four] and but determine what symbol is inside of the spaces.                -Utilise a for loop for checking instead of using a giant if statement. You could use a loop for the horizontal weather condition, a loop for the vertical, and a loop for the diagonals.                These are but a few ways. There are more than ways than these. **/              

Play Once again?

Information technology might not be credible where to identify this function, and that is considering we haven't created the game loop. A game loop will allow the histrion to play again once a winning condition or tie has been met. To reach this, we are going to wrap the main method in two while loops. The first volition exist checking to encounter if the histrion wants to play once more, and the 2nd will be checking to see if the game is over. We volition create ii booleans, gameOver, and playAgain.

Note: This is the main function of our game. All the other functions are written outside of this function.

playAgain is the main while loop. While playAgain is true, the entire game will continue. Nosotros starting time the game by welcoming the player and assuasive them to make the first motility. The game will continue by calling the playerMove() function and go through all the methods we created earlier. Then nosotros will bank check the state of the board on line #12 using the isGameOver() function. If the game is over, we pause out of the inner while loop and ask the player if they want to play again.

If the game is not over, it will become the computer'southward plow, and the sequence volition repeat again and again until a win condition or tie has been met. Once isGameOver() returns false, we volition print out the score and ask the actor if they want to play again. We volition reuse the scanner from earlier the save the thespian's input. Based on the input of the thespian, we volition end the game or restart the game.

If you are looking closely, line # 34 contains a function that we have not written yet called resetBoard(). That is because it was non relevant until at present. This function sets the board back to its offset land. You could add together a bespeak system to proceed the score if yous wanted.

Fin

We are washed. Y'all now accept a complete Tic Tac Toe console game written in Java. The world is your oyster. Proceed to sharpen your coding skills by creating other games and never end learning. Snake might be a fun game to take on. One time again here is the final code in all its glory, if you need a reference.

spearsaftely1985.blogspot.com

Source: https://medium.com/codex/tic-tac-toe-e53212028341

0 Response to "Reseting an Array to Play Again Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel