<%@ page import="java.text.*,Puzzle" %> <%// process page
String action = request.getParameter("action"); String nString = null;
Puzzle puzzle = null;
int n = -1;boolean hasError = false;
String message = null;if (action == null)
{
}
else
{if (action.equals("New Puzzle")) { nString = request.getParameter("n"); try { n = Integer.valueOf(nString).intValue(); } catch (NumberFormatException nfe) { hasError = true; message = "Enter an integer >= 3 for <i>n</i>!"; } if (n < 3) { hasError = true; message = "Enter an integer >= 3 for <i>n</i>!"; } } else { puzzle = (Puzzle)session.getAttribute("puzzle"); n = puzzle.getSize(); nString = n+""; }}
// print page
%>
<html>
<head><title>Puzzle</title></head>
<body bgcolor="white">
<font size=3>
Enter <i>n</i> and click <i>New Puzzle</i> below to generate an (n^2 - 1) puzzle. Click the cells to arrange them in the natural order. <p>
<form method=POST action=Puzzle.jsp>
<%if (nString == null || nString.equals("")) {
%>
<i>n</i> <input text=text name=n size=2 maxlength=2> <%}
else
{
%>
<i>n</i> <input text=text name=n value=<%= nString %> size=2 maxlength=2> <%}
%>
<p>
<i>
<input type=submit name=action value="New Puzzle"> </i>
<p>
<%if (action == null)
{
}
else if (hasError)
{
%>
<%= message %>
<%}
else
{if (action.equals("New Puzzle")) { puzzle = new Puzzle(n); puzzle.startTimer(); } else { puzzle = (Puzzle)session.getAttribute("puzzle"); n = puzzle.getSize(); int index = ((Integer)session.getAttribute(action)).intValue(); if (puzzle.isCellMovable(index)) puzzle.move(index); } if (puzzle.isDone()) {%>
Congrats! You finished the puzzle in <%= puzzle.getMoves() %> moves and <%= puzzle.getElapseTime() %>. <%} else { if (action.equals("New Puzzle")) {%>
You used 0 moves and spent 0' 0'' so far. <%} else {%>
You used <%= puzzle.getMoves() %> moves and spent <%= puzzle.getElapseTime() %> so far. <%}
%>
<p>
<i>
<table border=1 cellspacing=0 cellpadding=0> <%for (int row=0; row<n; row++) {%>
<tr align=center>
<%for (int col=0; col<n; col++) { if (puzzle.getMissingCellRow()==row && puzzle.getMissingCellCol()==col) {%>
<td>
<%} else { NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumIntegerDigits(4); nf.setGroupingUsed(false); String valueString = nf.format(puzzle.getCell(row, col));%>
<td><input type=submit name=action value="<%= valueString %>"> <%session.setAttribute(valueString, new Integer(row*n+col)); } } }%>
</table>
</i>
<%session.setAttribute("puzzle", puzzle); }}
%>
</form>
</font>
<hr>
<a href="http://www.computing-wisdom.com"><i>Computing Wisdom Inc. Home Page</i></a> </body>
</html>