Question

1 Overview For this assignment you are required to write a Java program that plays (n, k)-tic-tac-toe; (n, k)-tic- tac-toe is3 Classes to Implement You are to implement at least 3 Java classes: Dictionary.java, nk_TicTacToe.java, and Record.java. Youin the board starting at the top left position and moving from left to right and from top to bot- tom. For example, for the c3.2 Dictionary This class implements a dictionary. You must implement the dictionary using a hash table with separate chainin• public int get(String config): A method which returns the score stored in the dictionary for the given configuration, or -13.3 nk Tic Tac Toe This class implements all the methods needed by algorithm computerPlay, which are described below. The con• public boolean isDraw(): Returns true if gameBoard has no empty positions left and no player has won the game. • public int

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The code consists of a total of 9 .java classes which includes the 3 basic classes as per the question(with all the required functionalities).

To run the code:

$ java Play <board size> <inline to win> <depth> <blocked spots ...>

Example, for basic 3*3 tic tac toe board:

$ java Play 3 3 3

All the codes with the file names are given below.

Filename: nk_TicTacToe.java

public class nk_TicTacToe {

private char[][] gameBoard; // GameBoard
private int inLine; // Required number of squares in a row to win
public nk_TicTacToe (int board_size, int inline, int max_levels) {

// Create a new Game Board of size board_size
gameBoard = new char[board_size][board_size];

// Fill board with empty characters
for (int i = 0; i < board_size; i++) {
for (int j = 0; j < board_size; j++) {
gameBoard[i][j] = ' ';
}
}

inLine = inline;
}
public Dictionary createDictionary() {
Dictionary dictionary = new Dictionary(4599);
return dictionary;
}
public int repeatedConfig(Dictionary configurations) {
String board = getGBString();


if(configurations.get(board) != null){
return configurations.get(board).getScore();

} else {
return -1;

}
}
public void insertConfig(Dictionary configurations, int score, int level){
String board = getGBString();

try {
configurations.put(new Record(board, score, level));
} catch (DuplicatedKeyException e) {
System.err.println(e.getMessage());
}
}
public void storePlay (int row, int col, char symbol) {
gameBoard[row][col] = symbol;
}
public boolean squareIsEmpty (int row, int col){

try {
return gameBoard[row][col] == ' ';
} catch (Exception e) {
return false;
}
}
public boolean wins (char symbol) {

int inlineCount = 0; // Records the number in a row

// Checks each Row for a win
for (int i = 0; i < gameBoard.length; i++) {

// Reset the counter for the row
inlineCount = 0;

for (int j = 0; j < gameBoard.length; j++) {
if (gameBoard[i][j] == symbol) {
inlineCount = inlineCount + 1; // Add one onto count

} else {
inlineCount = 0; // Reset count
}

if (inlineCount == getInLine()) { // Check if count is enough to win
return true;
}
}
}

// Checks each Column for a win
for (int k = 0; k < gameBoard.length; k++) {

// Reset the counter for the row
inlineCount = 0;

for (int l = 0; l < gameBoard.length; l++) {
if (gameBoard[l][k] == symbol) {
inlineCount = inlineCount + 1; // Add one onto count

} else {
inlineCount = 0; // Reset count
}

if (inlineCount == getInLine()) { // Check if count is enough to win
return true;
}
}
}

// Check Left Diagonal (top half - Along rows - Descending)
for (int m = 0; m < gameBoard.length; m++) {
inlineCount = 0;
if((gameBoard.length - m) >= inLine){
for (int n = 0; n < gameBoard.length; n++) {

if ( (m + n) < gameBoard.length) { // Keep index in array bounds
if (gameBoard[n][n + m] == symbol) {
inlineCount = inlineCount + 1; // Add one onto count

} else {
inlineCount = 0; // Reset count
}

if (inlineCount == getInLine()) { // Check if count is enough to win
return true;
}
} else {
inlineCount = 0;
}
}
}
}

// Check Left Diagonal (bottom half - Along Columns - Descending)
for (int m = 0; m < gameBoard.length; m++) {
inlineCount = 0;
if((gameBoard.length - m) >= inLine){
for (int n = 0; n < gameBoard.length; n++) {

if ( (m + n) < gameBoard.length) { // Keep index in array bounds
if (gameBoard[n + m][n] == symbol) {
inlineCount = inlineCount + 1; // Add one onto count

} else {
inlineCount = 0; // Reset count
}

if (inlineCount == getInLine()) { // Check if count is enough to win
return true;
}
} else {
inlineCount = 0;
}
}
}
}
// Check Left Diagonal (top half - Along Rows - Ascending)
for (int q = 0; q < gameBoard.length; q++) {
inlineCount = 0;
if((gameBoard.length - q) >= getInLine()){
for (int r = gameBoard.length - 1; r >= 0; r--) {

if ( (r - q) >= 0) { // Keep index in array bounds
if (gameBoard[gameBoard.length-r-1][r - q] == symbol) {
inlineCount = inlineCount + 1; // Add one onto count

} else {
inlineCount = 0; // Reset count
}

if (inlineCount == getInLine()) { // Check if count is enough to win
return true;
}

}

}
}
}

// Check Left Diagonal (top half - Along Columns - Ascending)
for (int q = 0; q < gameBoard.length; q++) {
inlineCount = 0;
if((gameBoard.length - q) >= getInLine()){
for (int r = gameBoard.length - 1; r >= 0; r--){

if ( (r - q) >= 0 && gameBoard.length-r < gameBoard.length) { // Keep index in array bounds
if (gameBoard[r-q][gameBoard.length-r] == symbol) {
inlineCount = inlineCount + 1; // Add one onto count

} else {
inlineCount = 0; // Reset count
}

if (inlineCount == getInLine()) { // Check if count is enough to win
return true;
}

}

}
}
}

return false;
}
public boolean isDraw(){

// Check for empty spots
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard.length; j++) {
if (getTileType(i,j) == ' '){
return false;

}
}
}

// Check if player or computer has won the game
if (wins('o') || wins('x')) {
return false;
}

// Otherwise, return it's a draw
return true;
}
public int evalBoard(){

if (wins('o')){
return 3;

} else if (wins('x')) {
return 0;

} else if (isDraw()) {
return 1;

} else {
return 2;
}

}
private String getGBString(){
String board = "";

// Iterate through board double array
for (int i = 0; i < gameBoard.length; i++){
for (int j = 0; j < gameBoard.length; j++){
// Add onto board string
board = board + gameBoard[i][j];
}
}

return board;
}
private int getTileType(int row, int col){
try {
// Attempt to look up tile type and return it
return gameBoard[row][col];
} catch (IndexOutOfBoundsException e) {
// If out of bounds, return blocked (since this cannot be played)
return 'b';
}
}
private int getInLine(){
return inLine;
}
}

Filename: Record.java

public class Record {

private String config;
private int score;
private int level;
public Record(String config, int score, int level){
this.config = config;
this.score = score;
this.level = level;

}
public String getConfiguration(){
return config;
}
public int getScore() {
return score;
}
public int getLevel() {
return level;
}

}

Filename: DictionaryADT.java

public interface DictionaryADT {
public int put (Record record) throws DuplicatedKeyException;

public void remove (String config) throws InexistentKeyException;

public Record get (String config);

public int numElements();
}

Filename: Dictionary.java

public class Dictionary implements DictionaryADT {

private Node[] table;
private int tableSize;
private int elements;

public Dictionary(int tableSize) {
this.tableSize = tableSize;
table = new Node[tableSize];
}
private int hashFunction(String config) {

int hashKey = 0;

for (int i = 0; i < config.length(); i++) {
hashKey = (hashKey * 43 ) % tableSize;
hashKey += (int) config.charAt(i);
}

return hashKey % tableSize;
}
public int put(Record record) throws DuplicatedKeyException {

int hashKey = hashFunction(record.getConfiguration());

// Check if config is already in the table
if(get(record.getConfiguration()) != null) {
throw new DuplicatedKeyException("config is already in the table");
}

// Key is empty, create a new node
if (table[hashKey] == null){
table[hashKey] = new Node(record);
return 0;
} else {

// Get the Front of the Linked List
Node currentRecord = table[hashKey];
while (currentRecord.getNext() != null) {

// Iterate until end
currentRecord = currentRecord.getNext();
}

currentRecord.setNext(new Node(record));
this.elements = numElements() + 1;
}

return 1;
}
public void remove(String config) throws InexistentKeyException {

int hashKey = hashFunction(config);

Node currentNode = table[hashKey];

if (currentNode == null) {
throw new InexistentKeyException("config not found in the table");
}
while (currentNode != null) {
if (currentNode.getRecord().getConfiguration().equals(config)) {
table[hashKey] = currentNode.getNext();
break;
} else {
currentNode = currentNode.getNext();
}
}
}
public Record get(String config) {

int hashKey = hashFunction(config);

Node currentNode = table[hashKey];

while (currentNode != null) {
if (currentNode.getRecord().getConfiguration().equals(config)) {
return currentNode.getRecord();

} else {
currentNode = currentNode.getNext();
}
}

return null;
}
public int numElements() {
return elements;
}
}

Filename: DuplicatedKeyException.java

public class DuplicatedKeyException extends Exception {

public DuplicatedKeyException (String message) {
super(message);
}
}

Filename: InexistentKeyException.java

public class InexistentKeyException extends Exception {
public InexistentKeyException (String message) {
super(message);
}
}

Filename: Node.java

public class Node {

private Record record; // Info (TTTRecord) to store in the Node
private Node nextNode; // the next connected node

public Node(Record record){
this.record = record;
this.nextNode = null;
}
public Node getNext() {
return nextNode;
}
public void setNext(Node next){
this.nextNode = next;
}
public Record getRecord() {
return record;
}
public void setRecord(Record newRecord) {
this.record = newRecord;
}
}

Filename: Play.java

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.util.*;
import java.io.*;

public class Play extends JFrame {
static final long UID = 0;


// Characters
private final char COMP = 'o';
private final char HUMAN = 'x';
private final char BLOCKED = 'b';

// Timers
private final int MIN_DELAY = 300; // Delay before computer shows move
private final int MAX_COMP_MOVES = 10000; // Number of move tries before computer gives up

// GUI
private JButton[][] gameDisplay; // Game Board
private nk_TicTacToe TTT; // Tic Tac Toe Class

private int maxLevel; // Max level of tree
private Dictionary configurations;
private int numBlockedPos; // Number of positions to block

private int blockedPos []; // Blocked Positions

private ClickHandler handler;

private int numCalls = 0;
private boolean thinking = false;


public Play (int size, int toWin, int depth, int num, int[] blocked) {
Container c = getContentPane();
c.setLayout(new GridLayout(size, size));
gameDisplay = new JButton[size][size];
Icon emptySquare = new ImageIcon("empty.gif");
handler = new ClickHandler(size);

       /* Board is represented as a grid of clickable buttons */
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++) {
gameDisplay[i][j] = new JButton("", emptySquare);
gameDisplay[i][j].setEnabled(true);
add(gameDisplay[i][j]);
gameDisplay[i][j].addActionListener(handler);
}

// board_size = size;
maxLevel = depth;
numBlockedPos = num;
blockedPos = blocked;
TTT = new nk_TicTacToe(size, toWin, depth); /* User code needed to play */

for (int i = 0; i < numBlockedPos; ++i) {
int row = blockedPos[i] / size;
int col = blockedPos[i] % size;
gameDisplay[row][col].setIcon(new ImageIcon("blocked.gif"));
gameDisplay[row][col].paint(gameDisplay[row][col].getGraphics());

TTT.storePlay(row, col, BLOCKED);
}

}


public static void main(String[] args) {
int size = 0;
int toWin = 0;
int depth = 0;

       // Check if correct params provided
if (args.length < 3) {
System.out.println("Usage: java Play <board-size> <to win> <depth> <blocked positions ...>");
System.exit(0);
}

// Attempt to assign initial game values
try {
           /* Size of the game board */
size = Integer.parseInt(args[0]);
toWin = Integer.parseInt(args[1]);
depth = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out.println("Invalid program argument");
System.exit(0);
}

       // Block all BLOCKED positions
int numOfBlocked = args.length - 3;

int[] blocked = new int[numOfBlocked];

for (int i = 0; i < numOfBlocked; ++i) {
blocked[i] = Integer.parseInt(args[3 + i]) - 1;
if ((blocked[i] < 0) || (blocked[i] >= size * size)) {
System.out.println("Invalid board position " + blocked[i]);
System.exit(0);
}
}

       // Create a GameBoard and Start the Game
JFrame gameWindow = new Play(size, toWin, depth, numOfBlocked, blocked);

// Set screen size
gameWindow.setSize(size * 90, size * 100);
gameWindow.setVisible(true);

// Listen for closing events
gameWindow.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
});

// Randomly choose who goes first
if (Math.random() > 0.5)
((Play)gameWindow).handler.displayComputerPlay();
}

private class ClickHandler implements ActionListener {
private int board_size;
private boolean game_ended = false;

/* Constructor. Save board size in instance variable */
public ClickHandler(int size) {
board_size = size;
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JButton) { /*
                                                       * Some position of the
                                                       * board was selected
                                                       */
int row = -1, col = -1;

if (game_ended)
System.exit(0);
               /* Find out which position was selected by the player */
for (int i = 0; i < board_size; i++) {
for (int j = 0; j < board_size; j++)
if (event.getSource() == gameDisplay[i][j]) {
row = i;
col = j;
break;
}
if (row != -1)
break;
}

if (TTT.squareIsEmpty(row, col)) {
                   /* Valid play, mark it on the board */
gameDisplay[row][col].setIcon(new ImageIcon("human.gif"));
gameDisplay[row][col].paint(gameDisplay[row][col].getGraphics());

TTT.storePlay(row, col, HUMAN);
if (TTT.wins(HUMAN))
endGame("Human wins");
else {
if (TTT.isDraw())
endGame("Game is a draw");
else
displayComputerPlay();
}
} else
System.out.println("Invalid play");

}
}

private void displayComputerPlay() {
PossiblePlay pos;

Date d = new Date();
long start = d.getTime();
numCalls = 0;
thinking = false;

pos = computerPlay(COMP, -1, 4, 0);

if (thinking) System.out.println("");
long end = d.getTime();
try {
if (end-start < MIN_DELAY)
Thread.sleep(MIN_DELAY-end+start);
}
catch (Exception e) {
System.out.println("Something is wrong with timer");
}

TTT.storePlay(pos.getRow(), pos.getCol(), COMP);
gameDisplay[pos.getRow()][pos.getCol()].setIcon(new ImageIcon("computer.gif"));
if (TTT.wins(COMP))
endGame("Computer wins");
else if (TTT.isDraw())
endGame("Game is a draw");
}

/* Explore the game tree and choose the best move for the computer */
private PossiblePlay computerPlay(char symbol, int highest_score, int lowest_score, int level) {

char opponent; // Opponent's symbol
PossiblePlay reply; // Opponent's best reply

int bestRow = -1;
int bestColumn = -1; // Position of best play

int value;
int lookupVal;

if (level == 0) /* Create new hash table */
configurations = TTT.createDictionary();

if (symbol == COMP) {
opponent = HUMAN;
value = -1;
} else {
opponent = COMP;
value = 4;
}

if (++numCalls == MAX_COMP_MOVES) {
System.out.print("Please wait ..");
thinking = true;
}
else if ((numCalls % MAX_COMP_MOVES) == 0) System.out.print(".");


// Scan entries of the game board in random order
int row, column;
row = (int)(Math.random() * board_size);

for (int r = 0; r < board_size; r++) {
column = (int)(Math.random() * board_size);
for (int c = 0; c < board_size; c++) {
if (TTT.squareIsEmpty(row, column)) { // Empty position
TTT.storePlay(row, column, symbol); // Store next play
if (TTT.wins(symbol) || TTT.isDraw() || (level >= maxLevel))
// Game ending situation or max number of levels
// reached
reply = new PossiblePlay(TTT.evalBoard(), row, column);
else {
lookupVal = TTT.repeatedConfig(configurations);
if (lookupVal != -1)
reply = new PossiblePlay(lookupVal, row, column);
else {
reply = computerPlay(opponent, highest_score, lowest_score, level + 1);
if (TTT.repeatedConfig(configurations) == -1)
TTT.insertConfig(configurations, reply.getScore(), 0);
}
}
TTT.storePlay(row, column, ' ');

if ((symbol == COMP && reply.getScore() > value)
|| (symbol == HUMAN && reply.getScore() < value)) {
bestRow = row;
bestColumn = column;
value = reply.getScore();

                           /* Alpha/beta cut */
if (symbol == COMP && value > highest_score)
highest_score = value;
else if (symbol == HUMAN && value < lowest_score)
lowest_score = value;

if (highest_score >= lowest_score)
return new PossiblePlay(value, bestRow, bestColumn);
}

}
column = (column + 1) % board_size;
}
row = (row + 1) % board_size;
}
return new PossiblePlay(value, bestRow, bestColumn);
}

/* Prompt the user for a key to terminate the game */
private void endGame(String mssg) {
System.out.println(mssg);
System.out.println("");
System.out.println("Click on board to terminate game");
game_ended = true;
}

}
}

Filename: PossiblePlay.java

public class PossiblePlay {
private int row, col; /* Row and column of the play */
private int score; /* play's score */

public PossiblePlay(int v, int r, int c) {
row = r;
col = c;
score = v;
}

public int getRow() {
return row;
}

public int getCol() {
return col;
}

public int getScore() {
return score;
}
}

Thank you!

If you have any queries regarding the solution please ask.

Add a comment
Know the answer?
Add Answer to:
1 Overview For this assignment you are required to write a Java program that plays (n,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a program to Simulate a game of tic tac toe in c#

    Write a program to Simulate a game of tic tac toe. A game of tic tac toe has two players. A Player class is required to store /represent information about each player. The UML diagram is given below.Player-name: string-symbol :charPlayer (name:string,symbol:char)getName():stringgetSymbol():chargetInfo():string The tic tac toe board will be represented by a two dimensional array of size 3 by 3 characters. At the start of the game each cell is empty (must be set to the underscore character ‘_’). Program flow:1)    ...

  • JAVA TIC TAC TOE - please help me correct my code Write a program that will...

    JAVA TIC TAC TOE - please help me correct my code Write a program that will allow two players to play a game of TIC TAC TOE. When the program starts, it will display a tic tac toe board as below |    1       |   2        |   3 |    4       |   5        |   6                 |    7      |   8        |   9 The program will assign X to Player 1, and O to Player    The program will ask Player 1, to...

  • Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game....

    Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game. The objective of this project is to demonstrate your understanding of various programming concepts including Object Oriented Programming (OOP) and design. Tic Tac Toe is a two player game. In your implementation one opponent will be a human player and the other a computer player. ? The game is played on a 3 x 3 game board. ? The first player is known as...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

  • Implement a tic-tac-toe game. At the bottom of these specifications you will see a template you...

    Implement a tic-tac-toe game. At the bottom of these specifications you will see a template you must copy and paste to cloud9. Do not change the provided complete functions, or the function stub headers / return values. Currently, if the variables provided in main are commented out, the program will compile. Complete the specifications for each function. As you develop the program, implement one function at a time, and test that function. The provided comments provide hints as to what...

  • Code in JAVA You are asked to implement “Connect 4” which is a two player game....

    Code in JAVA You are asked to implement “Connect 4” which is a two player game. The game will be demonstrated in class. The game is played on a 6x7 grid, and is similar to tic-tac-toe, except that instead of getting three in a row, you must get four in a row. To take your turn, you choose a column, and slide a checker of your color into the column that you choose. The checker drops into the slot, falling...

  • (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe....

    (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe. The class contains a private 3-by-3 two-dimensional array. Use an enumeration to represent the value in each cell of the array. The enumeration’s constants should be named X, O and EMPTY (for a position that does not contain an X or an O). The constructor should initialize the board elements to EMPTY. Allow two human players. Wherever the first player moves, place an X...

  • PYTHON Exercise 2. Tic-Tac-Toe In this exercise we are going to create a Tic-Tac-Toe game. 1....

    PYTHON Exercise 2. Tic-Tac-Toe In this exercise we are going to create a Tic-Tac-Toe game. 1. Create the data structure – Nine slots that can each contain an X, an O, or a blank. – To represent the board with a dictionary, you can assign each slot a string-value key. – String values in the key-value pair to represent what’s in each slot on the board: ■ 'X' ■ 'O' ■ ‘ ‘ 2. Create a function to print the...

  • (Tic-Tac-Toe) Create class TicTacToe that will enable you to write a complete app to play the...

    (Tic-Tac-Toe) Create class TicTacToe that will enable you to write a complete app to play the game of Tic-Tac-Toe. The class contains a private 3-by-3 rectangular array of integers. The constructor should initialize the empty board to all 0s. Allow two human players. Wherever the first player moves, place a 1 in the specified square, and place a 2 wherever the second player moves. Each move must be to an empty square. After each move, determine whether the game has...

  • I need screenshots for this solution done in Flowgorithm. Thank you. Tic-Tac-Toe Game Design a program...

    I need screenshots for this solution done in Flowgorithm. Thank you. Tic-Tac-Toe Game Design a program that allows two players to play a game of tic-tac-toe. Use a two- dimensional String array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: a. Displays the contents of the board array. b. Allows player 1 to select a location...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT