SlideShare a Scribd company logo
1 of 18
Download to read offline
create a Tic Tac Toe game using JSP Scripting elements and a JSP page.
Solution
//basically you need three files for this
//index.jsp
//play.jsp
//TicTacToe.java ..... i have put the contents and
//commented between program lines wherever neceasary..thankyou .....
//contents of index.jsp file
< %@ page import = "javax.servlet.*" %>
<%@ page import = "javax.servlet.http.*" %>
<%@ page import = "tictactoe.TicTacToe" %>
<%
HttpSession sess = request.getSession(true);
session.setAttribute("board", new TicTacToe());
%>
Who shall go first?
I'll go first!
The computer can go.
--------------
//contents of play.jsp file
---------:------::========
<%@ page import = "javax.servlet.*" %>
<%@ page import = "javax.servlet.http.*" %>
<%@ page import = "tictactoe.TicTacToe" %>
<%
HttpSession sess = request.getSession(true);
TicTacToe board = (TicTacToe)session.getAttribute("board");
String first = request.getParameterValues("first")[0];
String[] moves = request.getParameterValues("move");
if (moves != null)
{
String move = moves[0];
boolean moveResult = false;
try {
int actualMove = new Integer(move);
if (actualMove >= 1 && actualMove <= 9) {
moveResult = board.move(actualMove);
}
} catch (Exception e) {
out.println("well that didn't work.");
}
if (!moveResult) {
out.println("not quite. give it another go!");
}
if (moveResult)
out.println("<br>");
} else {
out.println("<br>");
}
if (first.equals("computer")) {
if (board.getTurn(true) == 'X') {
board.move(board.evaluateBestMove());
}
}
else {
if (board.getTurn(true) == 'O') {
board.move(board.evaluateBestMove());
}
}
%>
<%
out.println(board);
%>
<%
if (board.isGameOver()) {
out.println("The winner is: ");
if (board.getWinner() == ' ') {
out.println("a tie!");
} else {
out.println(board.getWinner());
}
} else {
%>
Enter a move:
1|2|3
-----
4|5|6
-----
7|8|9
<%
}
%>
new game
-----:::::::::---------
//contents of TicTacToe.java file
package tictactoe;
public class TicTacToe {
// 3x3 array of tic tac toe board
//
// 1|2|3
// -----
// 4|5|6
// -----
// 7|8|9
//
private char board[][];
// the current board "orientation", used to detect isomorphic boards
private int boardPosition;
// which turn are we on?
private int turn;
// Has the game ended?
private boolean gameOver = false;
// Turn on which we found a winner.
private int hasWinner = 0;
public boolean isGameOver() {
return gameOver;
}
public TicTacToe() {
// initialize empty board, empty spaces having ' ' character.
board = new char[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
// At the "0th", or non-rotated board position
boardPosition = 0;
// First person's turn!
turn = 0;
}
/**
* Places a piece on the board at the specificed position.
* Either an X or an O is played, depending on whose turn it is.
* X always goes first.
*
* @param p Place where we want to make our move; integer [1..9]
* @return true if move was successful, false if not (eg, tried to move to
* a spot already taken.)
*/
public boolean move(int p) {
if (gameOver) {
// the game is over, stop trying to make moves!
return false;
}
if (p == 0) {
return false;
}
// 0-based indexing is easier.
p--;
// Get x and y array coords of board position
int x = p%3;
int y = p/3;
// check for illegal move
if (board[y][x] != ' ')
{
return false;
}
// whose turn is it?
char token = getTurn(true);
// set the board
board[y][x] = token;
// set it to its un-isomorphic original state after making move
revertBoard();
// next player's turn!
turn++;
// filled up the board, game is over
if (turn == 9) {
gameOver = true;
}
// someone has won, game is over
if (hasWinner > 0) {
gameOver = true;
}
return true;
}
/**
* Determines the next optimal move for the current player.
* This basically uses the strategy outlined here:
* http://en.wikipedia.org/wiki/Tic-tac-toe#Strategy
*
* @return Board position of where the next move should be made.
* Returns 0 if no optimal move is found (which would be a bug.)
*/
public int evaluateBestMove() {
int move = 0;
// First try to win
move = playWin(true);
// Otherwise, block opponent's win
if (move == 0) {
move = playWin(false);
}
// Try to create a fork scenario, where we could win two ways
if (move == 0) {
move = playFork();
}
// If opponent is about to have a fork, block it!
if (move == 0) {
move = blockFork();
}
// Play the center, if we can
if (move == 0) {
if (getPos(5) == ' ') {
move = 5;
}
}
// Play a corner opposite opponent, if we can
if (move == 0) {
move = playOppositeCorner();
}
// Play just any corner
if (move == 0) {
move = playEmptyCorner();
}
// Or play a side
if (move == 0) {
move = playEmptySide();
}
return move; //bad if move == 0
}
/**
* Returns the token {X, O} of either the current player or the opponent.
*
* @param thisPlayer Whether we want the token of ourselves (true) or the
* opponent (false)
*/
public char getTurn(boolean thisPlayer) {
return ((turn%2 == 0) == thisPlayer) ? 'X' : 'O';
}
/**
* Attempt to find and play a "fork"
*
* @return The board position for an optimal fork move to make.
* returns 0 if none exists.
*/
public int playFork() {
int rc = 0;
// Look for different board positions which could give us a fork.
rc = lookForPattern(getTurn(true), new int[] {7, 2, 3}, true, false, true, false, false, false, false,
false, false);
if (rc == 0) {
rc = lookForPattern(getTurn(true), new int[] {5, 7, 9}, true, false, true, false, false, false, false,
false, false);
}
if (rc == 0) {
rc = lookForPattern(getTurn(true), new int[] {3, 7, 9}, true, false, false, false, true, false, false,
false, false);
}
if (rc == 0) {
rc = lookForPattern(getTurn(true), new int[] {3,2,7}, true, false, false, false, true, false, false,
false, false);
}
if (rc == 0) {
rc = lookForPattern(getTurn(true), new int[] {3, 2, 4}, true, false, false, false, false, false, false,
false, true);
}
return rc;
}
/**
* Attempt to find and play a corner opposite opponent
*
* @return The board position for an optimal fork move to make.
* returns 0 if none exists.
*/
public int playOppositeCorner() {
return lookForPattern(getTurn(false), 9, true, false, false, false, false, false, false, false, false);
}
/**
* Attempt to find and play any corner
*
* @return The board position for an optimal fork move to make.
* returns 0 if none exists.
*/
public int playEmptyCorner() {
return lookForPattern(getTurn(false), 1, false, false, false, false, false, false, false, false, false);
}
/**
* Attempt to find and play any side
*
* @return The board position for an optimal fork move to make.
* returns 0 if none exists.
*/
public int playEmptySide() {
return lookForPattern(getTurn(false), 2, false, false, false, false, false, false, false, false, false);
}
/**
* Attempt to find and and block an opportunity for opponent to create a fork
*
* @return The board position for an optimal fork move to make.
* returns 0 if none exists.
*/
public int blockFork() {
int rc = 0;
rc = lookForPattern(getTurn(false), 4, true, false, false, false, false, false, false, false, true);
if (rc == 0) {
rc = lookForPattern(getTurn(false), 3, true, false, false, false, true, false, false, false, false);
}
if (rc == 0) {
rc = lookForPattern(getTurn(false), 2, true, false, true, false, false, false, false, false, false);
}
if (rc == 0) {
rc = lookForPattern(getTurn(false), 3, false, true, false, false, false, true, false, false, false);
}
return rc;
}
/**
* Attempt to find and play in a position which would result in a win.
* used by both player and opponent to either win or block a win.
*
* @param iWin true if I am looking for a way to win. false if I seek to
* block the opponent from an impending win. The stragety to
* find the "winning" position is the same, the only question
* is whether we're looking for a win for ourselves or for
* the opponent.
*
* @return The board position for an optimal fork move to make.
* returns 0 if none exists.
*/
public int playWin(boolean iWin) {
int rc = 0;
rc = lookForPattern(getTurn(iWin), 3, true, true, false, false, false, false, false, false, false);
if (rc == 0) {
rc =
lookForPattern(getTurn(iWin), 9, true, false, false, false, true, false, false, false, false);
}
if (rc == 0) {
rc = lookForPattern(getTurn(iWin), 6, false, false, false, true, true, false, false, false, false);
}
if (rc == 0) {
rc =
lookForPattern(getTurn(iWin), 2, true, false, true, false, false, false, false, false, false);
}
if (rc == 0) {
rc =
lookForPattern(getTurn(iWin), 5, true, false, false, false, false, false, false, false, true);
}
if (rc == 0) {
rc =
lookForPattern(getTurn(iWin), 5, false, false, false, true, false, true, false, false, false);
}
if ((rc > 0) && (iWin)) {
hasWinner = turn;
}
return rc;
}
public char getWinner() {
if (hasWinner > 0) {
return (hasWinner%2 == 0) ? 'X' : 'O';
}
return ' ';
}
public int lookForPattern( char t,
int position,
boolean t1,
boolean t2,
boolean t3,
boolean t4,
boolean t5,
boolean t6,
boolean t7,
boolean t8,
boolean t9) {
int[] inputPosition = new int[1];
inputPosition[0] = position;
return lookForPattern(t,inputPosition, t1, t2, t3, t4, t5, t6, t7, t8, t9);
}
/**
* Looks for a particular pattern on the board and sees if a desired move
* is legal. If so, we return that board position. Otherwise we return 0.
* This code searches all isomorphic board variations for the given pattern.
*
* @param t Which token we're looking for with our pattern. Are we searching
* for X or O pieces with this pattern?
* @param position If we find this pattern, this is the position we want to
* play as a result. If that position is not available,
* then that "pattern" does not exist and we move to the
* next one.
* @param t1..t9 basically a "a bitmask of positions". Do we want a token
* to be in position 1? Then set t1 = true. Etc.
* @return Board position to place a token. 0 if our desired position is
* invalid (beacuse someone else has already moved there.)
*/
public int lookForPattern( char t,
int[] positions,
boolean t1,
boolean t2,
boolean t3,
boolean t4,
boolean t5,
boolean t6,
boolean t7,
boolean t8,
boolean t9) {
// Okay. We want to look for the given pattern. So we look 8 times:
// current layout, horiz flip, vert flip, 2 diagonal flips,
// and 3 rotations.
// To make this easier, we coerce both our current board and the pattern
// we're looking for into a bit mask. Then we can xor to see if there
// is a match. You can tell I'm a C guy at heart.
int pattern = 0;
pattern |= (1 & (t1 ? 1 : 0)) << 0;
pattern |= (1 & (t2 ? 1 : 0)) << 1;
pattern |= (1 & (t3 ? 1 : 0)) << 2;
pattern |= (1 & (t4 ? 1 : 0)) << 3;
pattern |= (1 & (t5 ? 1 : 0)) << 4;
pattern |= (1 & (t6 ? 1 : 0)) << 5;
pattern |= (1 & (t7 ? 1 : 0)) << 6;
pattern |= (1 & (t8 ? 1 : 0)) << 7;
pattern |= (1 & (t9 ? 1 : 0)) << 8;
// loop through each of the 8 isomorphic board configurations to search
// for our pattern
for (int i = 0; i < 8; i++) {
flipBoard(i);
boolean foundMatch = (pattern ^ (boardToBits(t)&pattern)) == 0;
if (foundMatch) {
for (int position : positions) {
if (getPos(position) != ' ') {
foundMatch = false;
revertBoard();
break;
}
}
if (foundMatch) {
return positions[0];
}
} else {
revertBoard();
}
if (foundMatch) {
break;
}
}
return 0;
}
/**
* Reverts board from "isomorphic" state to its original board state
*/
public void revertBoard() {
switch (this.boardPosition) {
case 0:
case 1:
case 2:
case 3:
case 4:
flipBoard(this.boardPosition);
break;
case 5:
// fall through to rotate 3 times
rotateClockwise(1);
case 6:
// fall through to rotate 2 times
rotateClockwise(1);
case 7:
// fall through to rotate once
rotateClockwise(1);
break;
}
this.boardPosition = 0;
}
/**
* Flips board to one of 8 isomorphic positions. We can search for
* different configurations by flipping the board around.
*/
public void flipBoard(int position) {
switch (position) {
case 0:
// just a placeholder for "don't modify board"
break;
case 1:
swapPositions(1, 3);
swapPositions(4, 6);
swapPositions(7, 9);
break;
case 2:
swapPositions(1, 7);
swapPositions(2, 8);
swapPositions(3, 9);
break;
case 3:
swapPositions(1, 9);
swapPositions(2, 6);
swapPositions(4, 8);
break;
case 4:
swapPositions(2, 4);
swapPositions(3, 7);
swapPositions(6, 8);
break;
case 5:
rotateClockwise(1);
break;
case 6:
rotateClockwise(2);
break;
case 7:
rotateClockwise(3);
break;
}
boardPosition = position;
}
/**
* Rotate tic-tac-toe board clockwise.
*
* @param numberRotations How many times we want to rotate the board
*/
public void rotateClockwise(int numberRotations) {
for (int rotation = 0; rotation < numberRotations; rotation++) {
char[][] newBoard = new char[3][3];
for (int i=2;i>=0;--i)
{
for (int j=0;j<3;++j)
{
newBoard[2-i][j] = board[j][i];
}
}
board = newBoard;
}
}
/**
* Swaps the positions of two tokens on the board
*/
public void swapPositions(int a, int b) {
a--;
b--;
int a_x = a%3;
int a_y = a/3;
int b_x = b%3;
int b_y = b/3;
char tmp = board[a_y][a_x];
board[a_y][a_x] = board[b_y][b_x];
board[b_y][b_x] = tmp;
}
/**
* Takes a game board and converts it to a bitmask, which
* makes searching for different configurations easy.
*
* @param p Bitmask of what kind of pieces - X or O?
* @return bitmask representing board state
*/
public int boardToBits(char p) {
//TODO: Make this function lossless for both X and O information.
int pattern = 0;
for (int i = 0; i < 9; i++) {
int x = i%3;
int y = i/3;
char token = board[y][x];
pattern |= (1 & (token == p ? 1 : 0)) << i;
}
return pattern;
}
/**
* Gets token on board at a given position
*
* @param p Position we want token of. Alternately, position of which we
* want the token, if you have a perscriptivist aversion to
* stranded prepositions.
*/
public char getPos(int p) {
p--;
int x = p%3;
int y = p/3;
return board[y][x];
}
public String toString() {
String s = ("%c|%c|%c " +
"----- " +
"%c|%c|%c " +
"----- " +
"%c|%c|%c   Turn: %d");
return String.format (s,
board[0][0],
board[0][1],
board[0][2],
board[1][0],
board[1][1],
board[1][2],
board[2][0],
board[2][1],
board[2][2],
this.turn
);
}
public static void main(String[] args) {
TicTacToe t = new TicTacToe();
t.move(6);
t.move(t.evaluateBestMove());
t.move(8);
t.move(t.evaluateBestMove());
t.move(1);
t.move(t.evaluateBestMove());
t.move(7);
t.move(t.evaluateBestMove());
t.move(2);
if (t.isGameOver()) {
System.out.print("Winner: ");
if (t.getWinner() == ' ')
System.out.println("Tie");
else
System.out.println(t.getWinner());
}
System.out.println(t);
}
}

More Related Content

Similar to create a Tic Tac Toe game using JSP Scripting elements and a JSP pag.pdf

What they don't tell you about JavaScript
What they don't tell you about JavaScriptWhat they don't tell you about JavaScript
What they don't tell you about JavaScriptRaphael Cruzeiro
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfJkPoppy
 
i have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfi have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfpoblettesedanoree498
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfaoneonlinestore1
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsBaruch Sadogursky
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdffonecomp
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 DevsJason Hanson
 
Write a class (BasketballTeam) encapsulating the concept of a tea.pdf
Write a class (BasketballTeam) encapsulating the concept of a tea.pdfWrite a class (BasketballTeam) encapsulating the concept of a tea.pdf
Write a class (BasketballTeam) encapsulating the concept of a tea.pdfrozakashif85
 
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdfC++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdfaromalcom
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxwhitneyleman54422
 
Ugly code
Ugly codeUgly code
Ugly codeOdd-e
 
Test driven game development silly, stupid or inspired?
Test driven game development   silly, stupid or inspired?Test driven game development   silly, stupid or inspired?
Test driven game development silly, stupid or inspired?Eric Smith
 

Similar to create a Tic Tac Toe game using JSP Scripting elements and a JSP pag.pdf (19)

What they don't tell you about JavaScript
What they don't tell you about JavaScriptWhat they don't tell you about JavaScript
What they don't tell you about JavaScript
 
Code em Poker
Code em PokerCode em Poker
Code em Poker
 
AI For Texam Hold'em poker
AI For Texam Hold'em pokerAI For Texam Hold'em poker
AI For Texam Hold'em poker
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdf
 
i have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdfi have a code that runs, but it only lets the player to guess where .pdf
i have a code that runs, but it only lets the player to guess where .pdf
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdf
 
ES6 generators
ES6 generatorsES6 generators
ES6 generators
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
 
Write a class (BasketballTeam) encapsulating the concept of a tea.pdf
Write a class (BasketballTeam) encapsulating the concept of a tea.pdfWrite a class (BasketballTeam) encapsulating the concept of a tea.pdf
Write a class (BasketballTeam) encapsulating the concept of a tea.pdf
 
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdfC++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
C++ Programming (Please help me!! Thank you!!)Problem A Win SimU.pdf
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
 
week-18x
week-18xweek-18x
week-18x
 
week-17x
week-17xweek-17x
week-17x
 
Ugly code
Ugly codeUgly code
Ugly code
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Test driven game development silly, stupid or inspired?
Test driven game development   silly, stupid or inspired?Test driven game development   silly, stupid or inspired?
Test driven game development silly, stupid or inspired?
 

More from duttakajal70

Explain the relevance of the rules against hearsay to digital eviden.pdf
Explain the relevance of the rules against hearsay to digital eviden.pdfExplain the relevance of the rules against hearsay to digital eviden.pdf
Explain the relevance of the rules against hearsay to digital eviden.pdfduttakajal70
 
Electric and magnetic fields in an electromagnetic wave are alway.pdf
Electric and magnetic fields in an electromagnetic wave are alway.pdfElectric and magnetic fields in an electromagnetic wave are alway.pdf
Electric and magnetic fields in an electromagnetic wave are alway.pdfduttakajal70
 
C# code pleaseWrite a program that creates a link list object of 1.pdf
C# code pleaseWrite a program that creates a link list object of 1.pdfC# code pleaseWrite a program that creates a link list object of 1.pdf
C# code pleaseWrite a program that creates a link list object of 1.pdfduttakajal70
 
During our laboratory exercise on cellular the Krebs cycle in.pdf
During our laboratory exercise on cellular the Krebs cycle in.pdfDuring our laboratory exercise on cellular the Krebs cycle in.pdf
During our laboratory exercise on cellular the Krebs cycle in.pdfduttakajal70
 
25. On January 3, Pippin Corporation purchased 1,900 shares of the c.pdf
25. On January 3, Pippin Corporation purchased 1,900 shares of the c.pdf25. On January 3, Pippin Corporation purchased 1,900 shares of the c.pdf
25. On January 3, Pippin Corporation purchased 1,900 shares of the c.pdfduttakajal70
 
Define filtration and active transport.SolutionFiltration is t.pdf
Define filtration and active transport.SolutionFiltration is t.pdfDefine filtration and active transport.SolutionFiltration is t.pdf
Define filtration and active transport.SolutionFiltration is t.pdfduttakajal70
 
Why wouldnt you want to post a payment against an invoice directly.pdf
Why wouldnt you want to post a payment against an invoice directly.pdfWhy wouldnt you want to post a payment against an invoice directly.pdf
Why wouldnt you want to post a payment against an invoice directly.pdfduttakajal70
 
Cisco routers and switches use two configuration files. Where is the.pdf
Cisco routers and switches use two configuration files. Where is the.pdfCisco routers and switches use two configuration files. Where is the.pdf
Cisco routers and switches use two configuration files. Where is the.pdfduttakajal70
 
Which of the following is a simple compressible system A mixtur.pdf
Which of the following is a simple compressible system  A mixtur.pdfWhich of the following is a simple compressible system  A mixtur.pdf
Which of the following is a simple compressible system A mixtur.pdfduttakajal70
 
Which of the following statements is (are) trueI Walls Street i.pdf
Which of the following statements is (are) trueI  Walls Street i.pdfWhich of the following statements is (are) trueI  Walls Street i.pdf
Which of the following statements is (are) trueI Walls Street i.pdfduttakajal70
 
What would be the most effective method of reducing the incidence of .pdf
What would be the most effective method of reducing the incidence of .pdfWhat would be the most effective method of reducing the incidence of .pdf
What would be the most effective method of reducing the incidence of .pdfduttakajal70
 
What is a micelle What is a vesicle How are these structures the s.pdf
What is a micelle What is a vesicle How are these structures the s.pdfWhat is a micelle What is a vesicle How are these structures the s.pdf
What is a micelle What is a vesicle How are these structures the s.pdfduttakajal70
 
To determine her breathing rate, Miranda divides up her day into thre.pdf
To determine her breathing rate, Miranda divides up her day into thre.pdfTo determine her breathing rate, Miranda divides up her day into thre.pdf
To determine her breathing rate, Miranda divides up her day into thre.pdfduttakajal70
 
On January 29th, 2014, the Royal Caribbean cruise ship Explorer of.pdf
On January 29th, 2014, the Royal Caribbean cruise ship Explorer of.pdfOn January 29th, 2014, the Royal Caribbean cruise ship Explorer of.pdf
On January 29th, 2014, the Royal Caribbean cruise ship Explorer of.pdfduttakajal70
 
Name and describe the six main types of lymphatic cells, discuss the.pdf
Name and describe the six main types of lymphatic cells, discuss the.pdfName and describe the six main types of lymphatic cells, discuss the.pdf
Name and describe the six main types of lymphatic cells, discuss the.pdfduttakajal70
 
Let X1, X2, . . . , Xn be n independent continuous random variables,.pdf
Let X1, X2, . . . , Xn be n independent continuous random variables,.pdfLet X1, X2, . . . , Xn be n independent continuous random variables,.pdf
Let X1, X2, . . . , Xn be n independent continuous random variables,.pdfduttakajal70
 
Java Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdfJava Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdfduttakajal70
 
In major league baseball, there are 5 teams in the Eastern division .pdf
In major league baseball, there are 5 teams in the Eastern division .pdfIn major league baseball, there are 5 teams in the Eastern division .pdf
In major league baseball, there are 5 teams in the Eastern division .pdfduttakajal70
 
Im off by a minus sign, can you find my error In a previous probl.pdf
Im off by a minus sign, can you find my error In a previous probl.pdfIm off by a minus sign, can you find my error In a previous probl.pdf
Im off by a minus sign, can you find my error In a previous probl.pdfduttakajal70
 
If the characteristic followed in the pedigree is X-linked recessiv.pdf
If the characteristic followed in the pedigree is X-linked recessiv.pdfIf the characteristic followed in the pedigree is X-linked recessiv.pdf
If the characteristic followed in the pedigree is X-linked recessiv.pdfduttakajal70
 

More from duttakajal70 (20)

Explain the relevance of the rules against hearsay to digital eviden.pdf
Explain the relevance of the rules against hearsay to digital eviden.pdfExplain the relevance of the rules against hearsay to digital eviden.pdf
Explain the relevance of the rules against hearsay to digital eviden.pdf
 
Electric and magnetic fields in an electromagnetic wave are alway.pdf
Electric and magnetic fields in an electromagnetic wave are alway.pdfElectric and magnetic fields in an electromagnetic wave are alway.pdf
Electric and magnetic fields in an electromagnetic wave are alway.pdf
 
C# code pleaseWrite a program that creates a link list object of 1.pdf
C# code pleaseWrite a program that creates a link list object of 1.pdfC# code pleaseWrite a program that creates a link list object of 1.pdf
C# code pleaseWrite a program that creates a link list object of 1.pdf
 
During our laboratory exercise on cellular the Krebs cycle in.pdf
During our laboratory exercise on cellular the Krebs cycle in.pdfDuring our laboratory exercise on cellular the Krebs cycle in.pdf
During our laboratory exercise on cellular the Krebs cycle in.pdf
 
25. On January 3, Pippin Corporation purchased 1,900 shares of the c.pdf
25. On January 3, Pippin Corporation purchased 1,900 shares of the c.pdf25. On January 3, Pippin Corporation purchased 1,900 shares of the c.pdf
25. On January 3, Pippin Corporation purchased 1,900 shares of the c.pdf
 
Define filtration and active transport.SolutionFiltration is t.pdf
Define filtration and active transport.SolutionFiltration is t.pdfDefine filtration and active transport.SolutionFiltration is t.pdf
Define filtration and active transport.SolutionFiltration is t.pdf
 
Why wouldnt you want to post a payment against an invoice directly.pdf
Why wouldnt you want to post a payment against an invoice directly.pdfWhy wouldnt you want to post a payment against an invoice directly.pdf
Why wouldnt you want to post a payment against an invoice directly.pdf
 
Cisco routers and switches use two configuration files. Where is the.pdf
Cisco routers and switches use two configuration files. Where is the.pdfCisco routers and switches use two configuration files. Where is the.pdf
Cisco routers and switches use two configuration files. Where is the.pdf
 
Which of the following is a simple compressible system A mixtur.pdf
Which of the following is a simple compressible system  A mixtur.pdfWhich of the following is a simple compressible system  A mixtur.pdf
Which of the following is a simple compressible system A mixtur.pdf
 
Which of the following statements is (are) trueI Walls Street i.pdf
Which of the following statements is (are) trueI  Walls Street i.pdfWhich of the following statements is (are) trueI  Walls Street i.pdf
Which of the following statements is (are) trueI Walls Street i.pdf
 
What would be the most effective method of reducing the incidence of .pdf
What would be the most effective method of reducing the incidence of .pdfWhat would be the most effective method of reducing the incidence of .pdf
What would be the most effective method of reducing the incidence of .pdf
 
What is a micelle What is a vesicle How are these structures the s.pdf
What is a micelle What is a vesicle How are these structures the s.pdfWhat is a micelle What is a vesicle How are these structures the s.pdf
What is a micelle What is a vesicle How are these structures the s.pdf
 
To determine her breathing rate, Miranda divides up her day into thre.pdf
To determine her breathing rate, Miranda divides up her day into thre.pdfTo determine her breathing rate, Miranda divides up her day into thre.pdf
To determine her breathing rate, Miranda divides up her day into thre.pdf
 
On January 29th, 2014, the Royal Caribbean cruise ship Explorer of.pdf
On January 29th, 2014, the Royal Caribbean cruise ship Explorer of.pdfOn January 29th, 2014, the Royal Caribbean cruise ship Explorer of.pdf
On January 29th, 2014, the Royal Caribbean cruise ship Explorer of.pdf
 
Name and describe the six main types of lymphatic cells, discuss the.pdf
Name and describe the six main types of lymphatic cells, discuss the.pdfName and describe the six main types of lymphatic cells, discuss the.pdf
Name and describe the six main types of lymphatic cells, discuss the.pdf
 
Let X1, X2, . . . , Xn be n independent continuous random variables,.pdf
Let X1, X2, . . . , Xn be n independent continuous random variables,.pdfLet X1, X2, . . . , Xn be n independent continuous random variables,.pdf
Let X1, X2, . . . , Xn be n independent continuous random variables,.pdf
 
Java Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdfJava Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdf
 
In major league baseball, there are 5 teams in the Eastern division .pdf
In major league baseball, there are 5 teams in the Eastern division .pdfIn major league baseball, there are 5 teams in the Eastern division .pdf
In major league baseball, there are 5 teams in the Eastern division .pdf
 
Im off by a minus sign, can you find my error In a previous probl.pdf
Im off by a minus sign, can you find my error In a previous probl.pdfIm off by a minus sign, can you find my error In a previous probl.pdf
Im off by a minus sign, can you find my error In a previous probl.pdf
 
If the characteristic followed in the pedigree is X-linked recessiv.pdf
If the characteristic followed in the pedigree is X-linked recessiv.pdfIf the characteristic followed in the pedigree is X-linked recessiv.pdf
If the characteristic followed in the pedigree is X-linked recessiv.pdf
 

Recently uploaded

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 

Recently uploaded (20)

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 

create a Tic Tac Toe game using JSP Scripting elements and a JSP pag.pdf

  • 1. create a Tic Tac Toe game using JSP Scripting elements and a JSP page. Solution //basically you need three files for this //index.jsp //play.jsp //TicTacToe.java ..... i have put the contents and //commented between program lines wherever neceasary..thankyou ..... //contents of index.jsp file < %@ page import = "javax.servlet.*" %> <%@ page import = "javax.servlet.http.*" %> <%@ page import = "tictactoe.TicTacToe" %> <% HttpSession sess = request.getSession(true); session.setAttribute("board", new TicTacToe()); %> Who shall go first? I'll go first! The computer can go. -------------- //contents of play.jsp file ---------:------::======== <%@ page import = "javax.servlet.*" %> <%@ page import = "javax.servlet.http.*" %> <%@ page import = "tictactoe.TicTacToe" %>
  • 2. <% HttpSession sess = request.getSession(true); TicTacToe board = (TicTacToe)session.getAttribute("board"); String first = request.getParameterValues("first")[0]; String[] moves = request.getParameterValues("move"); if (moves != null) { String move = moves[0]; boolean moveResult = false; try { int actualMove = new Integer(move); if (actualMove >= 1 && actualMove <= 9) { moveResult = board.move(actualMove); } } catch (Exception e) { out.println("well that didn't work."); } if (!moveResult) { out.println("not quite. give it another go!"); } if (moveResult) out.println("<br>"); } else { out.println("<br>"); } if (first.equals("computer")) { if (board.getTurn(true) == 'X') { board.move(board.evaluateBestMove()); } } else { if (board.getTurn(true) == 'O') { board.move(board.evaluateBestMove()); } } %>
  • 3. <% out.println(board); %> <% if (board.isGameOver()) { out.println("The winner is: "); if (board.getWinner() == ' ') { out.println("a tie!"); } else { out.println(board.getWinner()); } } else { %> Enter a move: 1|2|3 ----- 4|5|6 ----- 7|8|9 <% } %> new game -----:::::::::--------- //contents of TicTacToe.java file package tictactoe; public class TicTacToe { // 3x3 array of tic tac toe board
  • 4. // // 1|2|3 // ----- // 4|5|6 // ----- // 7|8|9 // private char board[][]; // the current board "orientation", used to detect isomorphic boards private int boardPosition; // which turn are we on? private int turn; // Has the game ended? private boolean gameOver = false; // Turn on which we found a winner. private int hasWinner = 0; public boolean isGameOver() { return gameOver; } public TicTacToe() { // initialize empty board, empty spaces having ' ' character. board = new char[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = ' '; } } // At the "0th", or non-rotated board position boardPosition = 0; // First person's turn! turn = 0; } /** * Places a piece on the board at the specificed position. * Either an X or an O is played, depending on whose turn it is. * X always goes first.
  • 5. * * @param p Place where we want to make our move; integer [1..9] * @return true if move was successful, false if not (eg, tried to move to * a spot already taken.) */ public boolean move(int p) { if (gameOver) { // the game is over, stop trying to make moves! return false; } if (p == 0) { return false; } // 0-based indexing is easier. p--; // Get x and y array coords of board position int x = p%3; int y = p/3; // check for illegal move if (board[y][x] != ' ') { return false; } // whose turn is it? char token = getTurn(true); // set the board board[y][x] = token; // set it to its un-isomorphic original state after making move revertBoard(); // next player's turn! turn++; // filled up the board, game is over if (turn == 9) { gameOver = true; } // someone has won, game is over
  • 6. if (hasWinner > 0) { gameOver = true; } return true; } /** * Determines the next optimal move for the current player. * This basically uses the strategy outlined here: * http://en.wikipedia.org/wiki/Tic-tac-toe#Strategy * * @return Board position of where the next move should be made. * Returns 0 if no optimal move is found (which would be a bug.) */ public int evaluateBestMove() { int move = 0; // First try to win move = playWin(true); // Otherwise, block opponent's win if (move == 0) { move = playWin(false); } // Try to create a fork scenario, where we could win two ways if (move == 0) { move = playFork(); } // If opponent is about to have a fork, block it! if (move == 0) { move = blockFork(); } // Play the center, if we can if (move == 0) { if (getPos(5) == ' ') { move = 5; } }
  • 7. // Play a corner opposite opponent, if we can if (move == 0) { move = playOppositeCorner(); } // Play just any corner if (move == 0) { move = playEmptyCorner(); } // Or play a side if (move == 0) { move = playEmptySide(); } return move; //bad if move == 0 } /** * Returns the token {X, O} of either the current player or the opponent. * * @param thisPlayer Whether we want the token of ourselves (true) or the * opponent (false) */ public char getTurn(boolean thisPlayer) { return ((turn%2 == 0) == thisPlayer) ? 'X' : 'O'; } /** * Attempt to find and play a "fork" * * @return The board position for an optimal fork move to make. * returns 0 if none exists. */ public int playFork() { int rc = 0; // Look for different board positions which could give us a fork. rc = lookForPattern(getTurn(true), new int[] {7, 2, 3}, true, false, true, false, false, false, false, false, false); if (rc == 0) {
  • 8. rc = lookForPattern(getTurn(true), new int[] {5, 7, 9}, true, false, true, false, false, false, false, false, false); } if (rc == 0) { rc = lookForPattern(getTurn(true), new int[] {3, 7, 9}, true, false, false, false, true, false, false, false, false); } if (rc == 0) { rc = lookForPattern(getTurn(true), new int[] {3,2,7}, true, false, false, false, true, false, false, false, false); } if (rc == 0) { rc = lookForPattern(getTurn(true), new int[] {3, 2, 4}, true, false, false, false, false, false, false, false, true); } return rc; } /** * Attempt to find and play a corner opposite opponent * * @return The board position for an optimal fork move to make. * returns 0 if none exists. */ public int playOppositeCorner() { return lookForPattern(getTurn(false), 9, true, false, false, false, false, false, false, false, false); } /** * Attempt to find and play any corner * * @return The board position for an optimal fork move to make. * returns 0 if none exists. */ public int playEmptyCorner() { return lookForPattern(getTurn(false), 1, false, false, false, false, false, false, false, false, false); }
  • 9. /** * Attempt to find and play any side * * @return The board position for an optimal fork move to make. * returns 0 if none exists. */ public int playEmptySide() { return lookForPattern(getTurn(false), 2, false, false, false, false, false, false, false, false, false); } /** * Attempt to find and and block an opportunity for opponent to create a fork * * @return The board position for an optimal fork move to make. * returns 0 if none exists. */ public int blockFork() { int rc = 0; rc = lookForPattern(getTurn(false), 4, true, false, false, false, false, false, false, false, true); if (rc == 0) { rc = lookForPattern(getTurn(false), 3, true, false, false, false, true, false, false, false, false); } if (rc == 0) { rc = lookForPattern(getTurn(false), 2, true, false, true, false, false, false, false, false, false); } if (rc == 0) { rc = lookForPattern(getTurn(false), 3, false, true, false, false, false, true, false, false, false); } return rc; } /** * Attempt to find and play in a position which would result in a win. * used by both player and opponent to either win or block a win. * * @param iWin true if I am looking for a way to win. false if I seek to * block the opponent from an impending win. The stragety to * find the "winning" position is the same, the only question
  • 10. * is whether we're looking for a win for ourselves or for * the opponent. * * @return The board position for an optimal fork move to make. * returns 0 if none exists. */ public int playWin(boolean iWin) { int rc = 0; rc = lookForPattern(getTurn(iWin), 3, true, true, false, false, false, false, false, false, false); if (rc == 0) { rc = lookForPattern(getTurn(iWin), 9, true, false, false, false, true, false, false, false, false); } if (rc == 0) { rc = lookForPattern(getTurn(iWin), 6, false, false, false, true, true, false, false, false, false); } if (rc == 0) { rc = lookForPattern(getTurn(iWin), 2, true, false, true, false, false, false, false, false, false); } if (rc == 0) { rc = lookForPattern(getTurn(iWin), 5, true, false, false, false, false, false, false, false, true); } if (rc == 0) { rc = lookForPattern(getTurn(iWin), 5, false, false, false, true, false, true, false, false, false); } if ((rc > 0) && (iWin)) { hasWinner = turn; } return rc; } public char getWinner() { if (hasWinner > 0) { return (hasWinner%2 == 0) ? 'X' : 'O';
  • 11. } return ' '; } public int lookForPattern( char t, int position, boolean t1, boolean t2, boolean t3, boolean t4, boolean t5, boolean t6, boolean t7, boolean t8, boolean t9) { int[] inputPosition = new int[1]; inputPosition[0] = position; return lookForPattern(t,inputPosition, t1, t2, t3, t4, t5, t6, t7, t8, t9); } /** * Looks for a particular pattern on the board and sees if a desired move * is legal. If so, we return that board position. Otherwise we return 0. * This code searches all isomorphic board variations for the given pattern. * * @param t Which token we're looking for with our pattern. Are we searching * for X or O pieces with this pattern? * @param position If we find this pattern, this is the position we want to * play as a result. If that position is not available, * then that "pattern" does not exist and we move to the * next one. * @param t1..t9 basically a "a bitmask of positions". Do we want a token * to be in position 1? Then set t1 = true. Etc. * @return Board position to place a token. 0 if our desired position is * invalid (beacuse someone else has already moved there.) */
  • 12. public int lookForPattern( char t, int[] positions, boolean t1, boolean t2, boolean t3, boolean t4, boolean t5, boolean t6, boolean t7, boolean t8, boolean t9) { // Okay. We want to look for the given pattern. So we look 8 times: // current layout, horiz flip, vert flip, 2 diagonal flips, // and 3 rotations. // To make this easier, we coerce both our current board and the pattern // we're looking for into a bit mask. Then we can xor to see if there // is a match. You can tell I'm a C guy at heart. int pattern = 0; pattern |= (1 & (t1 ? 1 : 0)) << 0; pattern |= (1 & (t2 ? 1 : 0)) << 1; pattern |= (1 & (t3 ? 1 : 0)) << 2; pattern |= (1 & (t4 ? 1 : 0)) << 3; pattern |= (1 & (t5 ? 1 : 0)) << 4; pattern |= (1 & (t6 ? 1 : 0)) << 5; pattern |= (1 & (t7 ? 1 : 0)) << 6; pattern |= (1 & (t8 ? 1 : 0)) << 7; pattern |= (1 & (t9 ? 1 : 0)) << 8; // loop through each of the 8 isomorphic board configurations to search // for our pattern for (int i = 0; i < 8; i++) { flipBoard(i); boolean foundMatch = (pattern ^ (boardToBits(t)&pattern)) == 0; if (foundMatch) { for (int position : positions) { if (getPos(position) != ' ') {
  • 13. foundMatch = false; revertBoard(); break; } } if (foundMatch) { return positions[0]; } } else { revertBoard(); } if (foundMatch) { break; } } return 0; } /** * Reverts board from "isomorphic" state to its original board state */ public void revertBoard() { switch (this.boardPosition) { case 0: case 1: case 2: case 3: case 4: flipBoard(this.boardPosition); break; case 5: // fall through to rotate 3 times rotateClockwise(1); case 6: // fall through to rotate 2 times rotateClockwise(1);
  • 14. case 7: // fall through to rotate once rotateClockwise(1); break; } this.boardPosition = 0; } /** * Flips board to one of 8 isomorphic positions. We can search for * different configurations by flipping the board around. */ public void flipBoard(int position) { switch (position) { case 0: // just a placeholder for "don't modify board" break; case 1: swapPositions(1, 3); swapPositions(4, 6); swapPositions(7, 9); break; case 2: swapPositions(1, 7); swapPositions(2, 8); swapPositions(3, 9); break; case 3: swapPositions(1, 9); swapPositions(2, 6); swapPositions(4, 8); break; case 4: swapPositions(2, 4); swapPositions(3, 7); swapPositions(6, 8); break;
  • 15. case 5: rotateClockwise(1); break; case 6: rotateClockwise(2); break; case 7: rotateClockwise(3); break; } boardPosition = position; } /** * Rotate tic-tac-toe board clockwise. * * @param numberRotations How many times we want to rotate the board */ public void rotateClockwise(int numberRotations) { for (int rotation = 0; rotation < numberRotations; rotation++) { char[][] newBoard = new char[3][3]; for (int i=2;i>=0;--i) { for (int j=0;j<3;++j) { newBoard[2-i][j] = board[j][i]; } } board = newBoard; } } /** * Swaps the positions of two tokens on the board */ public void swapPositions(int a, int b) { a--; b--;
  • 16. int a_x = a%3; int a_y = a/3; int b_x = b%3; int b_y = b/3; char tmp = board[a_y][a_x]; board[a_y][a_x] = board[b_y][b_x]; board[b_y][b_x] = tmp; } /** * Takes a game board and converts it to a bitmask, which * makes searching for different configurations easy. * * @param p Bitmask of what kind of pieces - X or O? * @return bitmask representing board state */ public int boardToBits(char p) { //TODO: Make this function lossless for both X and O information. int pattern = 0; for (int i = 0; i < 9; i++) { int x = i%3; int y = i/3; char token = board[y][x]; pattern |= (1 & (token == p ? 1 : 0)) << i; } return pattern; } /** * Gets token on board at a given position * * @param p Position we want token of. Alternately, position of which we * want the token, if you have a perscriptivist aversion to * stranded prepositions. */ public char getPos(int p) { p--; int x = p%3;
  • 17. int y = p/3; return board[y][x]; } public String toString() { String s = ("%c|%c|%c " + "----- " + "%c|%c|%c " + "----- " + "%c|%c|%c Turn: %d"); return String.format (s, board[0][0], board[0][1], board[0][2], board[1][0], board[1][1], board[1][2], board[2][0], board[2][1], board[2][2], this.turn ); } public static void main(String[] args) { TicTacToe t = new TicTacToe(); t.move(6); t.move(t.evaluateBestMove()); t.move(8); t.move(t.evaluateBestMove()); t.move(1); t.move(t.evaluateBestMove()); t.move(7); t.move(t.evaluateBestMove()); t.move(2); if (t.isGameOver()) {
  • 18. System.out.print("Winner: "); if (t.getWinner() == ' ') System.out.println("Tie"); else System.out.println(t.getWinner()); } System.out.println(t); } }