Brent Schulze Brent Schulze - 6 months ago 10
Java Question

JAVA Servlet Tict Tac Toe w/Buttons

We were supposed to design a tic tac toe servlet, using buttons that will turn into x's or o's. This works using

href
, but not
submit
:

out.print("<input type=submit name=row + column >Play</a>");


out.print("<a href=\"TicTacToe?row=" + row + "&column=" + column + "\">Play</a>");


The
href
version when ran will display an 3x3 array of hyperlinks that will switch to x's and o's depending on player turn.

The
button
version does nothing... I've searched all over but am unsure how to make it work.

EDIT Here's the rest of the code I tried the changes Andreas mentioned no luck, but I did see how to do a few new things Scroll down until you see the asterisks across the page

package TicTacToe;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(
description = "Game request and response handler",
urlPatterns = {
"/TicTacToe"
})

public class TicTacToe extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;
private char[][] board; // 3 x 3 array
private final static char[] markers = {'O', 'X'};
private int currentPlayer; // 0 or 1
private int moveCount; // set to 9 when the game is over
private final Random random = new Random();

public TicTacToe() {
super();
reset();
}

private void generateCell(int row, int column, PrintWriter out) {
out.print("<td>");
if (board[row][column] == 0) {
if (moveCount < 9) {

****************************************************************************

out.print("<button type=\"button\" onclick=\"document.location='TicTacToe?row=" + row + "&column=" + column + "\">Play</button>");


****************************************************************************

} else {
// empty cell do nothing
}
} else {
out.print(board[row][column]);
}
out.print("</td>");
}

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("reset") != null) {
reset();
} else if (request.getParameter("computer") != null) {
computeMove();
} else if (request.getParameter("row") != null) {
int row = Integer.valueOf(request.getParameter("row"));
int column = Integer.valueOf(request.getParameter("column"));
if (board[row][column] == 0) {
board[row][column] = markers[currentPlayer];
currentPlayer = (currentPlayer + 1) % 2;
moveCount += 1;
}
}
PrintWriter out = response.getWriter();
String docType
= "<!doctype html public \"-//w3c//dtd html 4.0 "
+ "transitional//en\">\n";
out.println(docType
+ "<html>\n"
+ "<head><title>Tic Tac Toe</title></head>\n"
+ "<h1 align=\"center\">Tic Tac Toe</h1>\n"
+ "<table align=\"center\">\n");
String message = markers[currentPlayer] + " turn";
Character winner = checkWinner();
if (winner != null) {
message = winner + " wins";
moveCount = 9;
} else if (moveCount == 9) {
message = "No moves";
}
for (int row = 0; row < 3; ++row) {
out.print(" <tr>\n");
for (int column = 0; column < 3; ++column) {
generateCell(row, column, out);
}
out.println("</tr>");
}
out.println("</table>");
out.println(
"<h5 align=\"center\">" + message + "</h5>");
if (moveCount != 9) {
out.println("<h5 align=\"center\"><a href=\"TicTacToe?computer=1\">Computed move</a></h5>");
}
out.println("<a href=\"TicTacToe?reset=1\">Reset</a>"
+ "</body>\n"
+ "</html>");
}

private void reset() {
board = new char[3][3];
currentPlayer = 0;
moveCount = 0;
}

// return Character as opposed to char because it returns null when there is no winner
private Character checkWinner() {
// check rows
for (int row = 0; row < 3; ++row) {
if (board[row][0] != 0 && board[row][0] == board[row][1] && board[row][2] == board[row][1]) {
return board[row][0];
}
}
// check columns
for (int column = 0; column < 3; ++column) {
if (board[0][column] != 0 && board[0][column] == board[1][column] && board[2][column] == board[1][column]) {
return board[0][column];
}
}
// check diagonals
if (board[1][1] != 0 && board[0][0] == board[1][1] && board[2][2] == board[1][1]) {
return board[1][1];
}
if (board[1][1] != 0 && board[2][0] == board[1][1] && board[0][2] == board[1][1]) {
return board[1][1];
}
return null;
}

// play markerToPlay if markerToCheck can win
private boolean moveToWin(char markerToCheck, char markerToPlay) {
for (int row = 0; row < 3; ++row) {
for (int column = 0; column < 3; ++column) {
if (board[row][column] == 0) {
board[row][column] = markerToCheck;
if (checkWinner() != null) {
board[row][column]=markerToPlay;
return true;
} else {
board[row][column] = 0;
}
}
}
}
return false;
}

// naive strategy: occupy the center or a corner in the first move
// then find a winning move
// if it does exist block a winning move from opponent
// if there is no move from the previous line, just pick a move at random
private void computeMove() {
if (moveCount >= 9) { // should not happen, but checking anyway
return;
}
if (moveCount == 0) { // occupy center cell
board[1][1] = markers[currentPlayer];
} else if (moveCount == 1) {
if (board[1][1] == 0) {
board[1][1] = markers[currentPlayer];
} else { // occupy corner
board[0][0] = markers[currentPlayer];
}
} else {
// first check if there is a winning play
boolean played = moveToWin(markers[currentPlayer], markers[currentPlayer]);
// then move to block the one to win
if (!played) {
played = moveToWin(markers[(currentPlayer + 1) % 2], markers[currentPlayer]);
}
// if we did not get a move from above, we just pick a cell at random
while (!played) {
int row = random.nextInt(3);
int column = random.nextInt(3);
if (board[row][column] == 0) {
played = true;
board[row][column] = markers[currentPlayer];
}
}
}
currentPlayer = (currentPlayer + 1) % 2;
moveCount += 1;
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

}

Answer

A "submit" button only does something if it is inside a <form>, in which case it posts the form fields to the form action.

A standalone (non-form) button will work if you build the button like this:

// Using <input>
out.print("<input type=\"button\" onclick=\"document.location='TicTacToe?row=" + row + "&column=" + column + "\" value=\"Play\">");

// Using <button>
out.print("<button type=\"button\" onclick=\"document.location='TicTacToe?row=" + row + "&column=" + column + "\">Play</button>");

You can even use a <form> and <input type="hidden"> for row and column, but using onclick is easier.

Comments