Question: Language being used is Java. Need help completing the tic-tac-toe program. I have placed comment lines where I need help. They are located within the

Language being used is Java. Need help completing the tic-tac-toe program. I have placed comment lines where I need help. They are located within the four methods I have implemented. checkWinner(), checkRows(), checkColumns(), checkDiagonals().

import java.util.Random;

public class Project { public static void main (String[]args) { boolean gameEnded = false; int i = 0; for (; i<9; i++) { play(); System.out.println(" play" + (i+1) + ": "); print(); if(checkWinner()) { gameEnded = true; System.out.printf(" Player %s has won ", player ==1 ? "O" : "X"); } } if(i == 9 && !gameEnded) { System.out.println(" Game has ended in a draw"); } } static int[] grid = new int[9]; static int player = 1; static boolean checkWinner() { //TODO. Need help here. Returns true if either X or O has won the game } static boolean checkRows() { //TODO. Need help here. Returns true if one of the rows has all three X's or O's } static boolean checkColumns() { //TODO. Need help here. Returns true if one of the columns has all three X's or O's } static boolean checkDiagonals() { //TODO. Need help here. Returns true if one of the diagonals has all three X's or O's } static private void flip() { player = player == 1 ? 2: 1; } static void play() { int next = nextPlay(); while(grid[next] > 0) { next = nextPlay(); } grid[next] = player; flip(); } static int nextPlay() { return new Random().nextInt(9); } static private String getCell (int pos) { int player = grid[pos]; String ret = " "; if (player ==1) { ret = " X "; } else if (player ==2) { ret = " O "; } return ret; } static void print() { System.out.printf("%s|%s|%s ", getCell(0), getCell(1), getCell(2)); System.out.println("-----------"); System.out.printf("%s|%s|%s ", getCell(3), getCell(4), getCell(5)); System.out.println("-----------"); System.out.printf("%s|%s|%s ", getCell(6), getCell(7), getCell(8)); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!