Creating a Loop to Play Again in Java

Projection Intro

Apply a 2D array to make a Tic Tac Toe game — and practice using conditionals, loops, and functions!

This is a challenging project for Java coders familiar with basic concepts, and is too smashing practice for AP Calculator Science students.

  • Coding language: Java
  • Approx. lines of code: ~150
  • Approx. time needed to build: thirty-60 min

Who is this for?

  • Coding feel in linguistic communication: Beginner
  • Juni level: Coffee Level 1
  • Challenge Level: Difficult

Learning Outcomes

Core concepts practiced:

  • 2D arrays
  • Functions

Prerequisite concepts to know/review:

  • Variables
  • Input and output
  • Conditionals
  • Loops

Just using these cadre concepts, we can create a whole game of Tic Tac Toe from start to cease.

Moreover, we learn how we tin plow a commonly played game into code by learning to think like a programmer. Without farther ado, let's go started!

Project Demo

Click run to play the Tic Tac Toe Java game yourself beneath!

You tin can also view my project solution lawmaking if you get stuck.

Specific features to consider:

  1. After asking us for our names, the program prints out a 3x3 board filled with dashes, signifying empty spots.
  2. Each turn information technology asks either player 1 or thespian 2 to enter a row and col index which is where they want to identify their 10 and o, and then the lath is printed once more with the x or o in the right spot.
  3. If the position the thespian entered is "off the board" or already has an ten or o on it, then our plan notifies the histrion, who is prompted to enter another row and col.
  4. Once the role player wins by getting three in a row, cavalcade, or diagonal, the plan prints that thespian one or 2 has won and prints out the terminal lath.

General order of steps to implement:

  1. Create a Tic Tac Toe lath and fill it with dashes.
  2. Create a office that draws the lath like a foursquare.
  3. Go on rails of the role player'southward turn and what symbol they are using.
  4. Keep asking the user to enter a row and col until they are valid.
  5. Gear up the right position on the lath to the proper symbol.
  6. Create a function that checks if either role player has won.
  7. Check if the game has ended in a necktie.
  8. Use a loop to keep the game going.

How do we do each of these steps?

Step 1: Create a 3x3 array to stand for the tic tac toe board and fill up it with dashes.

We demand to make a 2D array of characters, which tin can be x, o, or -.

Hint: We can use the following line of code to make a 3x3 array of chars: char[][] board = new char[iii][3]

Now we accept to fill our lath with dashes.

Hint: We can use a nested for loop to iterate through each position on our board. Inside both for loops, nosotros can prepare board[i][j] equal to a nuance.

Stride 2: Ask the users for their names.

First, we import the Scanner to help us get input from the user, by adding import coffee.util.Scanner to the tiptop of our program.

Then, we create our Scanner variable.

Next, we print out a message asking the user to blazon in their name using System.out.impress().

Nosotros store their input in a Cord chosen p1.

Do the same for p2.

Stride 3: Create a function that draws the board and prints it out like a 3x3 foursquare.

In order for our role to draw the board and impress information technology out, do we demand to pass a parameter into the function? Exercise we need to return anything?

Hint: We need to pass in the lath 2d array in society for the office to be able to print it. We don't need to return annihilation since the office is simply press out the board.

Within our function, nosotros need to impress out each position on our lath.

Hint: If we do System.out.println(), so each position is on a new line.
Hint: If we practise Organization.out.print(), then all of the positions are on i line.
Hint: We can do System.out.print() in the inner for loop, and do System.out.println() at the end of the outer for loop so that information technology starts a new line after each row has been printed.

Step 4: Impress out the right thespian'south turn and store the player's char (ten or o).

Nosotros need a way to keep track of which actor's turn it is in our game.

Hint: We can use a boolean called player1 which is true if it is actor 1'southward turn and simulated if it is actor 2's plow.

We can employ a conditional to cheque whose turn it is.

Too, we can use cord concatenation to print out the player's proper name.

Footstep v: Ask the user for the row and col and check if it is valid.

Print a message asking the user for a row and employ the Scanner to get their input, storing it in a variable called row; repeat this for col.

Now, why would the row and col the user entered not be valid?

Hint: If the user types a row and col that is a spot that is not on the board, then the row and col aren't valid. Use a conditional to check if the row and col are not greater than 2 and non less than 0.
Hint: If the user types a row and col that is a spot that already has an x or o on it, then the row and col aren't valid. Apply a conditional to check if the position on the lath at row and col does not already have an x or o.

Pace 6: Use a loop to keep asking the player to enter a valid row and col.

If the user enters a row and col that is out of bounds or a row and col that already has an x or o on it, then we want to enquire the user to re-enter a row and col. We tin use a loop to do this!

Hint: We tin can employ a while(true) loop and interruption once the role player has entered a valid row and col.

Footstep 7: Set the right position on the board to the player char.

Outside of the while loop, nosotros know that we have a valid row and col. We can get the position on the board by doing board[row][col].

At present we can set this position to exist equal to the char of the player, which we stored in the variable c.

Step 8: Create a office that checks if either thespian has won.

In tic tac toe, a player wins if they have 3 of their symbols in one row, column, or diagonal.

Let's start with rows. We tin employ a for loop to iterate through each row i.

Inside the for loop, we can utilize a provisional to check if board[i][0] equals board[i][i] and if board[i][i] equals board[i][2]. Remember, we as well have to check if board[i][0] doesn't equal a dash so that we don't win if there are three empty spots in a row. If that is all true, then we can return the value of lath[i][0].

Nosotros can repeat like steps for columns.

At that place are ii diagonals on the board that we accept to check. Nosotros can use two if statements to bank check the two diagonals, similar to the if statements we used for rows and columns.

If nosotros achieve the end of our function, that means that nobody has won. Here, we tin just render a space.

Step ix: Print out which player has won if a role player has won.

In our main method, we tin can apply the function nosotros just created to bank check if a histrion has won.

Hint: We tin can use conditionals to check if our function returns x or o. If it returns x, then impress that player 1 has won. If it returns o, so print that thespian two has won.

Pace 10: Check if the game has concluded in a tie.

Tic tac toe ends in a tie if nobody has won and the board is total. We already have checked if someone has won. Now nosotros just demand to check if the lath is total.

Let's create a function that returns true if the lath is full and false if there are even so empty spots on the lath. Remember, an empty spot is a dash.

Hint: We can use nested for loops to iterate through each position on the board. Inside the inner for loop, nosotros tin can use a conditional to bank check if board[i][j] is equal to -, and if then, return true.

Once we stop going through the nested for loops and detect that no position on the board equals a nuance, then nosotros know that the board is full and so we tin can render true.

Step 11: Utilise a loop to go on the game going.

We can create a boolean called gameEnded and initially set it to false. Inside the if statement where nosotros check if a thespian has won or if it is a tie, we can ready gameEnded to truthful.

We can make a while loop, with its condition simply being gameEnded, so that the programme keeps asking a role player to enter a row and col until in that location is a winner or a tie.

If we run our program, we notice that the histrion doesn't alternate every round. How can we ready this?

Hint: If there is no winner and no tie, we can switch the player1 boolean by writing the post-obit: player1 = !player1. The ! ways not, so if player1 was truthful, this line sets it to not true, or false, and if player1 was fake, this line sets it to not false, or true.

Subsequently the while loop is over, we can draw the lath a final time so that both players can see the final state of the lath.

Great job! Ready for a challenge?

Now, instead of a basic 3x3 lath, let'south make our Tic Tac Toe game work for whatever size board!

It's definitely a tough challenge, but yous can do it!

Who is this for?

  • Coding experience in language: Beginner
  • Juni level: Coffee Level one
  • How would you describe the challenge level? Hard

Learning outcomes

Core concepts practiced:

  • 2nd arrays
  • Functions

Prerequisite concepts to know/review:

  • Variables
  • Input and output
  • Conditionals
  • Loops

Demo

Click run to see the project yourself below!

Y'all tin can also view my project solution lawmaking if you get stuck.

Full general order of steps to implement:

  1. Create a variable that stores the size of our board.
  2. Change the nested for loops and then that they iterate the correct number of times, instead of only 3 times.
  3. Alter the conditions that check if our row and col are out of bounds.
  4. Rewrite the function that checks for a winner to get in work for any board size – this is a challenging step!

How do we do each of these steps?

  1. We can create a variable n in our principal method that represents the size of our board and brand our board nxn.
  2. We need to utilise board.length and board[0].length in the nested for loops in our functions instead of 3.
  3. When checking if the row and col are out of bounds, we have to bank check if row and col are greater than or equal to northward instead of checking if row and col are greater than 2.
  4. Finally, the function in which we check if a player has won needs to be rewritten in a fashion that works for whatever lath size.

For the last stride, the full general construction is as follows:

  • Create a boolean that is true if you accept northward chars in a row or column or diagonal that you are checking.
  • Create a variable called value which stores i of the positions on the row or column or diagonal that you are checking.
  • If value is equal to a dash, then you can gear up the boolean to faux since there is an empty space.
  • Else, loop through all of the other positions on the row or column or diagonal that you lot are checking.
  • If a position does non equal value, then you can set the boolean to false and break out of the loop.
  • Outside the loop, if the boolean nevertheless is true, return value.

More creative suggestions:

  • Try asking both players what symbol they want to use in the game!

Smashing task — now check out more tutorials!

Thanks for watching and hope you had fun making this project with me!

Built the project above? We'd love to see it! If you're interested in sharing your coding project or experiences with diversity in STEM, please reach out to u.s.a. at hi@learnwithjuni.com.

Visit our coding projects web log page to notice our other tutorials in more coding languages!

Demand more help, or want to keep learning?

A Juni instructor teaching Python.

A Juni Instructor teaches bones Java to a young student.

Looking upwardly your coding questions is ane of the best ways to learn!

Another great fashion to larn is from an experienced coder or instructor. Irith is a Juni student who started as a beginner in our AP Estimator Science track with a Juni Instructor. After learning more from our USACO and Web courses, he now loves to code his own projects and build iPhone apps!

Juni Learning Computer Science Instructors work closely with students ages 8-eighteen, and are specially trained to suit to each kid's unique learning fashion, stride, and interests.

Read more about our online coding courses and curriculum, or speak with a Juni Advisor today by calling (650) 263-4306 or emailing advisors@learnwithjuni.com.


mooreorlintands1970.blogspot.com

Source: https://junilearning.com/blog/coding-projects/java-beginner-tic-tac-toe-tutorial/

0 Response to "Creating a Loop to Play Again in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel