Chess Interface with Piece IMG implementation - java

I am currently making a Chess program as a project for my data structures class. We pretty much have most of the code complete but for some reason, I cannot figure out how to place the pieces onto any help would be Greatly Appreciated.
we are using JAVA and Swing
MAIN GOAL:
get piece IMG to go onto the board:
public abstract class UserInterface {
//FIELDS
protected Board board;
//The board that the UI will be used to interact with
//CONSTRUCTORS
public UserInterface(Board board) {
//Constructor for UserInterface implementers
this.board = board;
}
public UserInterface() {
}
//OTHER
public abstract Move promptMove();
public abstract PieceType promptPromotion();
public abstract void updateBoard();
public abstract void playGame(Interactable whiteUser, Interactable blackUser);
}
class CommandInterface extends UserInterface {
private GraphicInterface gui = null;
//CONSTRUCTORS
public CommandInterface(Board board) {
//Main constructor for the CommandInterface
super(board);
gui = new GraphicInterface(board, null);
gui.initializeGui();
}
//OTHER
public void playGame(Interactable whiteUser, Interactable blackUser) {
//Starts a game using the UI and the board.
//[TEST CODE] Probably will clean this up later
board.setUsers(whiteUser, blackUser);
updateBoard();
Scanner input = new Scanner(System.in);
boolean gameOver = false;
while(!gameOver) {
boolean illegalMove;
do {
try {
// System.out.println("Press enter to move");
// String s = input.nextLine();
board.doMove(board.getCurrentUser().getMove());
illegalMove = false;
} catch(IllegalArgumentException e) {
System.out.println(e.getMessage());
illegalMove = true;
}
if(board.getState() == BoardState.CHECKMATE) {
System.out.println("\n" + board.getTurn().toString() + " is now checkmated. Game over!");
gameOver = true;
illegalMove = false;
} else if(board.getState() == BoardState.CHECK) {
System.out.println("\n" + board.getTurn().toString() + " has been put in check!");
illegalMove = false;
} else if(board.getState() == BoardState.STALEMATE) {
System.out.println("\n" + board.getTurn().toString() + " is now stalemated. Game over!");
gameOver = true;
illegalMove = false;
}
} while(illegalMove);
updateBoard();
}
}
public Move promptMove() {
//Takes user input for a move and returns the Move object
Scanner input = new Scanner(System.in);
String move;
boolean again;
do {
System.out.print("Enter your move (? for help): ");
move = input.nextLine();
if(move.equals("?")) {
//If the user asks for help
System.out.printf("%nHELP: To move, you must type a move in the following format:"
+ "%n<STARTING TILE> <ENDING TILE>"
+ "%nThe starting tile is the tile of the piece you wish to move."
+ "%nThe ending tile is the tile you wish to move your piece to."
+ "%nEach tile is notated with \"<COLUMN><RANK>\", example: \"e5\""
+ "%n%nFull example move: \"a5 g5\"%n");
again = true;
} else if(move.equalsIgnoreCase("CASTLE")) {
System.out.print("Enter the movement of the King: ");
move = input.nextLine();
return new Move(board, move, true);
} else again = false;
} while(again);
//Reprompt if the user asks for help
return new Move(board, move);
//Returns a Move object made from the SMN string
}
public PieceType promptPromotion() {
Scanner input = new Scanner(System.in);
System.out.print("Pawn has promotion available.\nWhich piece to promote to? ");
while(true) {
String type = input.nextLine();
PieceType promotion = PieceType.NONE;
if (type.equalsIgnoreCase("PAWN")) promotion = PieceType.PAWN;
else if (type.equalsIgnoreCase("ROOK")) promotion = PieceType.ROOK;
else if (type.equalsIgnoreCase("KNIGHT")) promotion = PieceType.KNIGHT;
else if (type.equalsIgnoreCase("BISHOP")) promotion = PieceType.BISHOP;
else if (type.equalsIgnoreCase("QUEEN")) promotion = PieceType.QUEEN;
else if (type.equalsIgnoreCase("KING")) promotion = PieceType.KING;
else if (type.equalsIgnoreCase("EARL")) promotion = PieceType.EARL;
else if (type.equalsIgnoreCase("MONK")) promotion = PieceType.MONK;
if(promotion == PieceType.NONE) {
System.out.print("\nInvalid type, please try again: ");
continue;
}
return promotion;
}
}
public void updateBoard() {
//Prints the board in basic ASCII format.
gui.updateBoard();
drawCaptured(Color.WHITE);
System.out.println();
//Adds a line before the board starts printing
int squaresPrinted = 0;
//Keeps track of the total number of squares that has been printed
for(int y = board.getZeroSize(); y >= 0; y--) {
//Loop through y-values from top to bottom
if(y != board.getZeroSize()) System.out.println();
//If not on the first iteration of y-loop, go down a line (avoids leading line break)
System.out.print((y + 1) + " ");
//Print the rank number
for(int x = 0; x <= board.getZeroSize(); x++) {
//Loop through x-values from left to right
if(board.pieceAt(x, y) != null) {
//If there is a piece on the tile
if(squaresPrinted % 2 == 0) System.out.print("[" + board.pieceAt(x, y).getString() + "]");
//If squaresPrinted is even, print "[<pString>]"
else System.out.print("(" + board.pieceAt(x, y).getString() + ")");
//If squaresPrinted is odd, print "(<pString>)"
} else {
//If there is no piece on the tile
if(squaresPrinted % 2 == 0) System.out.print("[ ]");
//If squaresPrinted is even, print "[ ]"
else System.out.print("( )");
//If squaresPrinted is odd, print "( )"
}
squaresPrinted++;
//Increment squaresPrinted for each iteration of the x-loop
}
squaresPrinted++;
//Increment squaresPrinted for each iteration of the y-loop
}
System.out.println();
System.out.print(" ");
//Print an extra line and the leading whitespace for the column identifiers
for(int i = 0; i <= board.getZeroSize(); i++) {
//Repeat <size> times
System.out.print(" " + (char) (i + 97));
//Print the column identifier chars by casting from int
}
drawCaptured(Color.BLACK);
//Prints all black pieces that have been captured
System.out.println();
}
private void drawCaptured(Color color) {
//Prints captured pieces of either color.
System.out.println();
//Prints a blank line
ArrayList<String> capturedPieces = board.getCaptured(color);
if(capturedPieces == null) return;
for(String p : capturedPieces) {
System.out.print(p + " ");
//TODO: Remove trailing whitespace
}
}
}
#SuppressWarnings("ALL")
class GraphicInterface extends UserInterface implements MouseListener {
private JButton[][] chessBoardSquares = null;
private JButton buttonsAndLabels = new JButton();
private JLabel message = null;
private String columnNames = null;
private Board board = null;
private JFrame frame;
public ImageIcon BK;
public ImageIcon WP;
public ImageIcon WR;
public ImageIcon WN;
public ImageIcon WB;
public ImageIcon WQ;
public ImageIcon WK;
public ImageIcon BP;
public ImageIcon BR;
public ImageIcon BN;
public ImageIcon BB;
public ImageIcon BQ;
public ImageIcon blank;
private Object ImageIcon;
public GraphicInterface(Board board, GraphicInterface frame) {
super(board);
// super(board);
this.board = board;
try {
//remove later
String path = "src/chuss/icons/";
new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BK.gif")));
new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WP.gif")));
new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WR.gif")));
WN = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WN.gif")));
WB = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WB.gif")));
WQ = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WQ.gif")));
WK = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "WK.gif")));
BP = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BP.gif")));
BR = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BR.gif")));
BN = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BN.gif")));
BB = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BB.gif")));
BQ = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "BQ.gif")));
blank = new ImageIcon(javax.imageio.ImageIO.read(new File(path + "blank.png")));
buttonsAndLabels.addMouseListener((MouseListener) this);
buttonsAndLabels.add(buttonsAndLabels);
buttonsAndLabels.setSize(600, 600);
//buttonsAndLabels.getContentPane().setPreferredSize(new Dimension(800, 700));
} catch(IOException e) {
e.getCause();
e.printStackTrace();
}
buttonsAndLabels = new JButton((Action) new BorderLayout(3, 3));
chessBoardSquares = new JButton[8][8];
message = new JLabel("Chuss Champ is ready to play!");
columnNames = "ABCDEFGH";
initializeGui();
}
public GraphicInterface(JButton buttonsAndLabels) {
super();
}
public GraphicInterface(Board board) {
}
#Override
public Move promptMove() {
return null;
}
#Override
public PieceType promptPromotion() {
return null;
}
public final JButton initializeGui() {
// set up the main GUI
assert false;
buttonsAndLabels.setBorder(new EmptyBorder(5, 5, 5, 5));
JToolBar tools = new JToolBar();
tools.setFloatable(false);
buttonsAndLabels.add(tools, BorderLayout.PAGE_START);
tools.add(new JButton("New")); // TODO - add functionality!
tools.add(new JButton("Save")); // TODO - add functionality!
tools.add(new JButton("Restore")); // TODO - add functionality!
tools.addSeparator();
tools.add(new JButton("Resign")); // TODO - add functionality!
tools.addSeparator();
tools.add(message);
buttonsAndLabels.add(new JLabel("?"), BorderLayout.LINE_START);
// create the chess board squares
buttonsAndLabels = new JButton((Action) new GridLayout(0, 9));
buttonsAndLabels.setBorder(new LineBorder(java.awt.Color.BLACK));
buttonsAndLabels.add((Component) ImageIcon);
updateBoard();
Runnable r = () -> {
JFrame f = new JFrame("CHUSS");
f.add(getGui());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// ensures the minimum size is enforced.
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
assert false;
return null;
}
public void updateBoard() {
//Prints the board in graphical format.
buttonsAndLabels.removeAll();
Insets buttonMargin = new Insets(0,0,0,0);
for (int ii = 7; ii >= 0; ii--) {
for (int jj = 0; jj < chessBoardSquares.length; jj++) {
JButton b = new JButton();
b.setMargin(buttonMargin);
// our chess pieces are 64x64 px in size, so we'll
// 'fill this in' using a transparent icon..
Piece p = board.pieceAt(jj, ii);
ImageIcon icon = new ImageIcon();
if (p instanceof Pawn && p.getColor() == Color.WHITE) icon = WP;
else if (p instanceof Rook && p.getColor() == Color.WHITE) icon = WR;
else if (p instanceof Knight && p.getColor() == Color.WHITE) icon = WN;
else if (p instanceof Bishop && p.getColor() == Color.WHITE) icon = WB;
else if (p instanceof Queen && p.getColor() == Color.WHITE) icon = WQ;
else if (p instanceof King && p.getColor() == Color.WHITE) icon = WK;
else if (p instanceof Pawn && p.getColor() == Color.BLACK) icon = BP;
else if (p instanceof Rook && p.getColor() == Color.BLACK) icon = BR;
else if (p instanceof Knight && p.getColor() == Color.BLACK) icon = BN;
else if (p instanceof Bishop && p.getColor() == Color.BLACK) icon = BB;
else if (p instanceof Queen && p.getColor() == Color.BLACK) icon = BQ;
else if (p instanceof King && p.getColor() == Color.BLACK) icon = BK;
else if (p == null) icon = blank;
b.setIcon(icon);
if ((jj % 2 == 1 && ii % 2 == 1)
//) {
|| (jj % 2 == 0 && ii % 2 == 0)) {
b.setBackground(java.awt.Color.WHITE);
} else {
b.setBackground(java.awt.Color.GRAY);
}
chessBoardSquares[jj][ii] = b;
buttonsAndLabels.add(chessBoardSquares[jj][ii]);
}
}
initializeGui();
// fill the top row
for (int ii = 0; ii <= 7; ii++) {
buttonsAndLabels.add(
new JLabel(columnNames.substring(ii, ii + 1),
SwingConstants.CENTER));
}
// fill the black non-pawn piece row
for (int ii = 7; ii >= 0; ii--) {
for (int jj = 0; jj < 8; jj++) {
if (jj == 0) {
buttonsAndLabels.add(new JLabel("" + (ii + 1),
SwingConstants.CENTER));
}
buttonsAndLabels.add(chessBoardSquares[jj][ii]);
}
}
buttonsAndLabels.updateUI();
}
#Override
public void playGame(Interactable whiteUser, Interactable blackUser) {
GraphicInterface gui = new GraphicInterface(buttonsAndLabels);
gui.getChessBoard();
}
public JComponent getChessBoard() {
return buttonsAndLabels;
}
public JComponent getGui() {
return buttonsAndLabels;
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}

Related

I created a game, but the counter for wins, losses and draws isn't working

One would think that this would be the easiest thing (it should be right), but my JLabel values are not being updated to reflect that the game is a draw, loss or win. I initiate 3 variables (numLosses, numDraws, and numWins), and then I increment them each time there is a loss, win or draw. However my counter remains at 0? Why? Here is the code?
NewTicTacToe.java:
package newtictactoe;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NewTicTacToe
extends JFrame
{
public static void main(String [] args)
{
new NewTicTacToe();
}
private JButton btnA1, btnA2, btnA3, btnB1, btnB2, btnB3, btnC1, btnC2, btnC3;
private JLabel lblWins, lblLosses, lblDraws;
private TicTacToeBoard board;
private int numWins, numDraws, numLosses;
public NewTicTacToe()
{
// Set up the grid
this.numDraws = 0;
this.numWins = 0;
this.numLosses = 0;
this.setSize(800,450);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Tic-Tac-Toe");
JPanel panel1 = new JPanel();
panel1.setSize(650,450); //resolution of panel1 set to 650 by 325
panel1.setLayout(new GridLayout(3,3));
btnA1 = createButton("A1");
btnA2 = createButton("A2");
btnA3 = createButton("A3");
btnB1 = createButton("B1");
btnB2 = createButton("B2");
btnB3 = createButton("B3");
btnC1 = createButton("C1");
btnC2 = createButton("C2");
btnC3 = createButton("C3");
panel1.add(btnA1);
panel1.add(btnA2);
panel1.add(btnA3);
panel1.add(btnB1);
panel1.add(btnB2);
panel1.add(btnB3);
panel1.add(btnC1);
panel1.add(btnC2);
panel1.add(btnC3);
JPanel panel2 = new JPanel();
panel2.setLayout(new BorderLayout());
lblWins = new JLabel("Wins: " + numWins);
lblLosses = new JLabel("Losses: " + numLosses);
lblDraws = new JLabel("Draws: " + numDraws);
panel2.add(lblWins);
panel2.add(lblLosses);
panel2.add(lblDraws);
lblWins.setLocation(670, 20);
lblLosses.setLocation(670, 50);
lblDraws.setLocation(670, 80);
lblWins.setSize(100, 20);
lblLosses.setSize(100, 20);
lblDraws.setSize(100, 20);
panel2.setLayout(null);
this.add(panel1);
this.add(panel2);
this.setVisible(true);
// Start the game and create new instance of TicTacToeBoard
board = new TicTacToeBoard();
}
private JButton createButton(String square)
{
JButton btn = new JButton();
btn.setPreferredSize(new Dimension(50, 50));
Font f = new Font("Dialog", Font.PLAIN, 72);
btn.setFont(f);
btn.addActionListener(e -> btnClick(e, square));
return btn;
}
private void btnClick(ActionEvent e, String square)
{
if (board.getSquare(square) != 0)
return;
JButton btn = (JButton)e.getSource();
btn.setText("X");
board.playAt(square, 1);
if (board.isGameOver() == 3)
{
JOptionPane.showMessageDialog(null,
"It's a draw!", "Game Over",
JOptionPane.INFORMATION_MESSAGE);
numDraws++;
resetGame();
return;
}
if (board.isGameOver() == 1)
{
JOptionPane.showMessageDialog(null,
"You Win n00b!", "Game Over",
JOptionPane.INFORMATION_MESSAGE);
numWins++;
resetGame();
return;
}
String computerMove = board.getNextMove();
board.playAt(computerMove,2);
switch (computerMove)
{
case "A1":
btnA1.setText("O");
break;
case "A2":
btnA2.setText("O");
break;
case "A3":
btnA3.setText("O");
break;
case "B1":
btnB1.setText("O");
break;
case "B2":
btnB2.setText("O");
break;
case "B3":
btnB3.setText("O");
break;
case "C1":
btnC1.setText("O");
break;
case "C2":
btnC2.setText("O");
break;
case "C3":
btnC3.setText("O");
break;
}
if (board.isGameOver() == 2)
{
JOptionPane.showMessageDialog(null,
"Computer wins you big n00b!", "Game Over",
JOptionPane.INFORMATION_MESSAGE);
numLosses++;
resetGame();
return;
}
}
private void resetGame()
{
board.reset();
btnA1.setText("");
btnA2.setText("");
btnA3.setText("");
btnB1.setText("");
btnB2.setText("");
btnB3.setText("");
btnC1.setText("");
btnC2.setText("");
btnC3.setText("");
}
}
TicTacToeBoard.java:
package newtictactoe;
public class TicTacToeBoard
{
int numWins = 0;
int numLosses = 0;
int numDraws = 0;
private int board [];
private int vectors [] [] =
{
{0, 1, 2}, // Row 1
{3, 4, 5}, // Row 2
{6, 7, 8}, // Row 3
{0, 3, 6}, // Column 1
{1, 4, 7}, // Column 2
{2, 5, 8}, // Column 3
{0, 4, 8}, // Diagonal 1
{2, 4, 6} // Diagonal 2
};
public TicTacToeBoard()
{
this.reset();
}
public void reset()
{
board = new int[] {2, 2, 2, 2, 2, 2, 2, 2, 2};
}
private int getSquare(int index)
{
if (index < 0 | index > 8)
throw new IllegalArgumentException("index must be 0-9");
return board[index];
}
public int getSquare(String square)
{
int index = mapSquareToIndex(square);
if (index == -1)
throw new IllegalArgumentException("Invalid square");
switch (getSquare(index))
{
case 3:
return 1;
case 5:
return 2;
default:
return 0;
}
}
private int mapSquareToIndex(String square)
{
switch (square)
{
case "A1":
return 0;
case "A2":
return 1;
case "A3":
return 2;
case "B1":
return 3;
case "B2":
return 4;
case "B3":
return 5;
case "C1":
return 6;
case "C2":
return 7;
case "C3":
return 8;
default:
return -1;
}
}
private String mapIndexToSquare(int index)
{
switch (index)
{
case 0:
return "A1";
case 1:
return "A2";
case 2:
return "A3";
case 3:
return "B1";
case 4:
return "B2";
case 5:
return "B3";
case 6:
return "C1";
case 7:
return "C2";
case 8:
return "C3";
default:
return "";
}
}
public void playAt(String square, int player)
{
int index = mapSquareToIndex(square);
if (index == -1)
throw new IllegalArgumentException("Invalid square");
this.playAt(index, player);
}
private void playAt(int index, int player)
{
if (index < 0 | index > 8)
throw new IllegalArgumentException("Square must be 0-8");
if (player <1 | player > 2)
throw new IllegalArgumentException("Player must be 1 or 2");
if (board[index] != 2)
throw new IllegalArgumentException("Square is not empty.");
if (player == 1)
board[index] = 3;
else
board[index] = 5;
}
public int isGameOver()
{
// check for win
for (int v = 0; v < 8; v++)
{
int p = getVectorProduct(v);
if (p == 27) {
numWins++;
return 1;
} // Player 1 has won
if (p == 125) {
numLosses++;
return 2;
// Player 2 has won
}
}
// check for draw
int blankCount = 0;
for (int i = 0; i < 9; i++)
if (board[i] == 2)
blankCount++;
if (blankCount == 0) {
numDraws++;
return 3; // Game is a draw
}
return 0; // Game is not over
}
public String canPlayerWin(int player)
{
if (player <1 | player > 2)
throw new IllegalArgumentException("player must be 1 or 2");
boolean playerCanWin = false;
for (int v = 0; v < 8; v++)
{
int p = getVectorProduct(v);
if ( (player == 1 & p == 18)
| (player == 2 & p == 50) )
{
if (board[vectors[v][0]] == 2)
return mapIndexToSquare(vectors[v][0]);
if (board[vectors[v][1]] == 2)
return mapIndexToSquare(vectors[v][1]);
if (board[vectors[v][2]] == 2)
return mapIndexToSquare(vectors[v][2]);
}
}
return "";
}
private int getVectorProduct(int vector)
{
return board[vectors[vector][0]] *
board[vectors[vector][1]] *
board[vectors[vector][2]];
}
public String getNextMove()
{
String bestMove;
// Win if possible
bestMove = this.canPlayerWin(2);
if (bestMove != "")
return bestMove;
// Block if necessary
bestMove = this.canPlayerWin(1);
if (bestMove != "")
return bestMove;
// Center if it is open
if (board[4] == 2)
return "B2";
// First open corner
if (board[0] == 2)
return "A1";
if (board[2] == 2)
return "A3";
if (board[6] == 2)
return "C1";
if (board[8] == 2)
return "C3";
// First open edge
if (board[1] == 2)
return "A2";
if (board[3] == 2)
return "B1";
if (board[5] == 2)
return "B3";
if (board[7] == 2)
return "C2";
return ""; // The board is full
}
public String toString()
{
return " " +
getMark(board[0]) + " | " +
getMark(board[1]) + " | " +
getMark(board[2]) +
"\n-----------\n" +
" " +
getMark(board[3]) + " | " +
getMark(board[4]) + " | " +
getMark(board[5]) +
"\n-----------\n" +
" " +
getMark(board[6]) + " | " +
getMark(board[7]) + " | " +
getMark(board[8]);
}
private String getMark(int status)
{
if (status == 3)
return "X";
if (status == 5)
return "O";
return " ";
}
}
In the file newTicTacToe.java, after every game you are updating the count in the variables numWins, numDraws and numLosses.
You need to update the JLabels lblWins, lblDraws and lblLosses too.
In your reset function, also add:
lblWins.setText("Wins: " + numWins);
lblLosses.setText("Losses: " + numLosses);
lblDraws.setText("Draws: " + numDraws);
That should solve your problem.
You are never updating the JLabels after you update numLosses, numDraws, and numWins. Do this by using
lblWins.setText(Integer.toString(numWins));
lblLosses.setText(Integer.toString(numLosses));
lblDraws.setText(Integer.toString(numDraws));
at the appropriate places
I see that you are only updating the int variables, numWins, numDraws, numLosses.
Changing the value of a variable does not change your labels' texts. How can the computer know that your labels are "linked" with the variables?
The solution is easy, just as you said. You just need to set the text of the labels whenever you change the value of the variables.
numWins++;
lblWins.setText(Integer.toString(numWins));
"But I will forget to do this sometimes!" you shouted. That's why you should add "setter" methods like this one:
private void setNumWins(int value) {
numWins = value;
lblWins.setText(Integer.toString(value));
}
Now, you can just call setNumWins and the label will update as well:
setNumWins(numWins + 1);
Isn't this just wonderful?

Messed up my code terribly with throwing/catching exceptions and try...catch blocks

Alright, I know I messed up bad with catching and throwing exceptions, but I can't figure them out for the life of me. I think I'm mixing several different ways to do them. Can anyone guide me in the right direction (not looking for complete answer, just what the code is supposed to resemble)? It gets stuck on the "throw new ();" lines, and the catch blocks. Everything else seems to not have any issues. It's supposed to be an improvement on a previous project, http://pastebin.com/sjR0BZBY. you can run this if you'd like to see what the program is supposed to do if that helps.
public class Project6 extends JFrame
{
// Declaring variables
private JLabel enterLabel, resultsLabel, errorLabel;
private JTextField queryField, errorField;
private JButton goB, clearB;
private JTextArea textArea;
private Container c;
private JPanel panel;
// main method
public static void main(String[] args)
{
Project6 p6 = new Project6();
p6.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p6.setSize(new Dimension(455, 550));
p6.setVisible(true);
}
// creating JFrame
public Project6()
{
c = getContentPane();
c.setLayout(new FlowLayout());
setTitle("");
c.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
ButtonHandler handler = new ButtonHandler();
enterLabel = new JLabel("Enter query here:");
c.add(enterLabel);
queryField = new JTextField(35);
c.add(queryField);
goB = new JButton("GO!");
c.add(goB);
goB.addActionListener(handler);
resultsLabel = new JLabel("Results:");
c.add(resultsLabel);
textArea = new JTextArea(20, 30);
c.add(textArea);
errorLabel = new JLabel("-------------Error messages:");
c.add(errorLabel);
errorField = new JTextField(35);
c.add(errorField);
clearB = new JButton("Clear");
c.add(clearB);
clearB.addActionListener(handler);
}
// ActionListener for buttons
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
// Go! button
if (e.getSource() == goB){
String str = queryField.getText();
StringTokenizer tokens = new StringTokenizer(str, ", ");
int numToks = tokens.countTokens();
String[] tokenArray = new String[numToks];
int i = 0;
// creating all tokenizing, validations, and the works. Try and bear with it, it works but it's a rough trip
while (tokens.hasMoreTokens()){
// while loop to create tokens
while (tokens.hasMoreTokens()){
str = tokens.nextToken();
tokenArray[i] = str;
System.out.println(tokenArray[i]);
i++; }
// start if verifications, everything else
String query = tokenArray[3];
String optok = tokenArray[4];
String index = tokenArray[5];
String qField = queryField.getText();
try {
if (qField.equals(""))
throw new MissingInputException();
else {
if (numToks != 6)
throw new IncorrectFormatException();
else {
if (tokenArray[0].equalsIgnoreCase("Report"))
{
if (tokenArray[1].equalsIgnoreCase("all"))
{
if (tokenArray[2].equals("where"))
{
if (tokenArray[3].equals("basePrice") || tokenArray[3].equals("quality") || tokenArray[3].equals("numInStock"))
{
if (tokenArray[4].equals("<") || tokenArray[4].equals(">") || tokenArray[4].equals(">=")||tokenArray[4].equals("<=")||tokenArray[4].equals("=="))
{
if (query.equals("basePrice"))
{ BasePriceM(query, index, optok); }
else if (query.equals("quality"))
{ QualityM(query, index, optok); }
else if (query.equals("numInStock"))
{ NumInStockM(query, index, optok); }
}
else
throw new InvalidOperatorException();
}
else
throw new InvalidLValueException();
}
else
throw new InvalidQualifierException();
}
else
throw new InvalidSelectorException();
}
else
throw new IllegalStartOfQueryException();
}
}
} // end try
catch(MissingInputException aa)
{
errorField.setText("Enter an expression");
queryField.setText("");
}
catch(IncorrectFormatException ab)
{
errorField.setText("Error, field too large or small");
queryField.setText("");
}
catch(IllegalStartOfQueryException ac)
{
errorField.setText("Error, report expected");
queryField.setText("");
}
catch(InvalidSelectorException ad)
{
errorField.setText("Error, all expected");
queryField.setText("");
}
catch(InvalidQualifierException ae)
{
errorField.setText("Error, where expected");
queryField.setText("");
}
catch(InvalidLValueException af)
{
errorField.setText("Error, basePrice, Quality, numInStock expected");
queryField.setText("");
}
catch(InvalidOperatorException ag)
{
errorField.setText("Error, < > >= <= == expected");
queryField.setText("");
}
catch(NumberFormatException af)
{
}
}// end of while loop
} // end go button
// clear all button
if (e.getSource() == clearB)
{
queryField.setText("");
textArea.setText("");
errorField.setText("");
}
}
} // end buttons
// methods for printing
public void BasePriceM(String query, String index, String optok)
{
int pos = 0;
int index1 = index.indexOf(".", pos);
if (index1 > -1)
{
double b = Double.parseDouble(index);
if (b > 0.05 && b < 5400.0)
{printBasePrice(query, optok, b);}
else{
errorField.setText("Invalid query, must be between 0.05 and 5400.0");
queryField.setText(""); }}
}
public void QualityM(String query, String index, String optok)
{
int pos2 = 0;
int index2 = index.indexOf(".", pos2);
if (index2 == -1)
{
int n = Integer.parseInt(index);
if (n > 0)
{
printBasePrice(query, optok, n);
}
else{
errorField.setText("Invalid query, must be greater than 0");
queryField.setText(""); }}
}
public void NumInStock(String query, String index, String optok)
{
int pos2 = 0;
int index2 = index.indexOf(".", pos2);
if (index2 == -1)
{
int n = Integer.parseInt(index);
if (n > 0)
{
printBasePrice(query, optok, n);
}
else{
errorField.setText("Invalid query, must be greater than 0");
queryField.setText("");} }
}
public void printQuality(String query, String optok, int p)
{
textArea.append("Search for " + query +" "+ optok +" "+ p + "\n");
}
public void printBasePrice(String query, String optok, double b)
{
textArea.append("Search for " + query +" "+ optok +" "+ b + "\n");
}
public void printNumInStock(String query, String optok, int n)
{
textArea.append("Search for " + query +" "+ optok +" "+ n + "\n");
}
} // end program`enter code here`

Tic Tac Toe: All states get returned as best moves

I am working on building the game of Tic Tac Toe. Please find below the description of the classes used.
Game:: The main class. This class will initiate the multiplayer mode.
Board: This class sets the board configurations.
Computer: This class comprises of the minimax algorithm.
BoardState: This class comprises of the Board Object, along with the last x and y coordinates which were used to generate the board
configuration.
State: This class comprises of the score and the x and y coordinates that that will lead to that score in the game.
Context
Working on DFS here.
Exploring the whole tree works fine.
The game is set in such a way that the user is prompted to play first.
The user will put x and y co ordinates in the game.Coordinates are between 0 to 2. The Play of the player is marked as 1
The response from the computer is 2, which the algorithm decides. Th algorithm will determine the best possible coordinates to play and then play 2 on the position.
One of the winning configurations for Player is :
Player wins through diagonal
121
112
221
One of the winning configuration for AI is:
222
121
211
AI wins Horizontal
Problem
All the states give the max score.
Essentially, when you start the game in your system, you will find that since all states are given the max score, the computer looks to play sequentially.
As in if you put at (00), the computer plays at (01) and if you play at (02), the computer will play at (10)
I have been trying to debug it for a long time now. I believe, I may be messing up something with the scoring function. Or there could be a bug in the base recursion steps. Moreover, I don't think immutability among classes could cause problems as I have been recreating/creating new objects everywhere.
I understand, this might not be the best context I could give, but it would be a great help if you guys could help me figure out where exactly is it going wrong and what could I do to fix it. Answers through code/logic used would be highly appreciated. Thanks!
Game Class
import java.io.Console;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Game {
static int player1 = 1;
static int player2 = 2;
public static void main(String[] args) {
// TODO Auto-generated method stub
//
//PLays Game
playGame();
/* Test Use Case
ArrayList<Board> ar = new ArrayList<Board>();
Board b = new Board();
b.setVal(0,0,1);
b.setVal(0,1,1);
b.setVal(0,2,2);
b.setVal(1,0,2);
b.setVal(1,1,2);
b.setVal(2,0,1);
b.setVal(2,1,1);
b.display();
Computer comp = new Computer();
State x = comp.getMoves(b, 2);
*/
}
private static void playGame() {
// TODO Auto-generated method stub
Board b = new Board();
Computer comp = new Computer();
while(true)
{
if(b.isBoardFull())
{
System.out.println("Game Drawn");
break;
}
b.display();
int[] pmove = getPlayerMove(b);
b.setVal(pmove[0],pmove[1], player1);
if(b.isVictoriousConfig(player1))
{
System.out.println("Player 1 Wins");
break;
}
if(b.isBoardFull())
{
System.out.println("Game Drawn");
break;
}
b.display();
System.out.println("Computer Moves");
/*For Random Play
* int[] cmove = comp.computeMove(b);
*/
Computer compu = new Computer();
State s = compu.getMoves(b, 2);
int[] cmove = new int[2];
cmove[0] = s.x;
cmove[1] = s.y;
b.setVal(cmove[0],cmove[1], player2);
if(b.isVictoriousConfig(player2))
{
System.out.println("Computer Wins");
break;
}
}
System.out.println("Game Over");
}
//Gets Player Move. Basic Checks on whether the move is a valud move or not.
private static int[] getPlayerMove(Board b) {
// TODO Auto-generated method stub
int[] playerMove = new int[2];
System.out.println("You Play");
while(true)
{
#SuppressWarnings("resource")
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter X Position: ");
while(true)
{
playerMove[0] = reader.nextInt(); // Scans the next token of the input as an int.
if(playerMove[0] >2)
{
System.out.println("Incorrect Position");
}
else
{
break;
}
}
System.out.println("Enter Y Position: ");
while(true)
{
playerMove[1] = reader.nextInt(); // Scans the next token of the input as an int.
if(playerMove[1] >2)
{
System.out.println("Incorrect Position");
}
else
{
break;
}
}
System.out.println("You entered positions: X is " + playerMove[0] + " and Y is " + playerMove[1] );
if(!b.isPosOccupied(playerMove[0], playerMove[1]))
{
break;
}
System.out.println("Incorrect Move. PLease try again");
}
return playerMove;
}
}
Board Class
import java.util.Arrays;
public class Board {
// Defines Board Configuration
private final int[][] data ;
public Board()
{
data = new int[3][3];
for(int i=0;i<data.length;i++ )
{
for(int j=0;j<data.length;j++ )
{
data[i][j] = 0;
}
}
}
//Displays Current State of the board
public void display()
{
System.out.println("Board");
for(int i = 0; i< data.length;i++)
{
for(int j = 0; j< data.length;j++)
{
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
// Gets the Value on a specific board configuration
public int getVal(int i, int j)
{
return data[i][j];
}
//Sets the value to a particular board location
public void setVal(int i, int j,int val)
{
data[i][j] = val;
}
public boolean isBoardFull()
{
for(int i=0;i< data.length ; i++)
{
for(int j=0;j< data.length ;j++)
{
if(data[i][j] == 0)
return false;
}
}
return true;
}
public boolean isVictoriousConfig(int player)
{
//Noting down victory rules
//Horizontal Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [0][1]) && (data[0][1] == data [0][2]) && (data[0][2] == player)))
return true;
if ((data[1][0] != 0) && ((data[1][0] == data [1][1]) && (data[1][1] == data [1][2]) && (data[1][2] == player)))
return true;
if ((data[2][0] != 0) && ((data[2][0] == data [2][1]) && (data[2][1] == data [2][2]) && (data[2][2] == player)))
return true;
//Vertical Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [1][0]) && (data[1][0] == data [2][0]) && (data[2][0] == player)))
return true;
if ((data[0][1] != 0) && ((data[0][1] == data [1][1]) && (data[1][1] == data [2][1]) && (data[2][1] == player)))
return true;
if ((data[0][2] != 0) && ((data[0][2] == data [1][2]) && (data[1][2] == data [2][2]) && (data[2][2] == player)))
return true;
//Diagonal Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [1][1]) && (data[1][1] == data [2][2]) && (data[2][2] == player)))
return true;
if ( (data[0][2] != 0) && ((data[0][2] == data [1][1]) && (data[1][1] == data [2][0]) && (data[2][0] == player)))
return true;
//If none of the victory rules are met. No one has won just yet ;)
return false;
}
public boolean isPosOccupied(int i, int j)
{
if(data[i][j] != 0)
{
return true;
}
return false;
}
public Board(int[][] x)
{
this.data = Arrays.copyOf(x, x.length);
}
}
Board State
public class BoardState {
final Board br;
final int x ;
final int y;
public BoardState(Board b, int posX, int posY)
{
br = b;
x = posX;
y = posY;
}
}
State
public class State {
final int s;
final int x;
final int y;
public State(int score, int posX, int posY)
{
s = score;
x = posX;
y = posY;
}
}
Computer
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class Computer {
int[] pos = new int[2];
static int player2 = 2;
static int player1 = 1;
ArrayList<Board> win =new ArrayList<Board>();
ArrayList<Board> loose =new ArrayList<Board>();
ArrayList<Board> draw =new ArrayList<Board>();
public Computer()
{
}
public int[] computeMove(Board b)
{
while(true)
{
Random randX = new Random();
Random randY = new Random();
pos[0] = randX.nextInt(3);
pos[1] = randY.nextInt(3);
if(!b.isPosOccupied(pos[0], pos[1]))
{
return pos;
}
}
}
public State getMoves(Board b,int p)
{
//System.out.println("test2");
int x = 0;
int y = 0;
BoardState bs = new BoardState(b,0,0);
//System.out.println("test");
State s = computeMoveAI(bs,p);
//System.out.println("Sore : X : Y" + s.s + s.x + s.y);
return s;
}
private State computeMoveAI(BoardState b, int p) {
// TODO Auto-generated method stub
//System.out.println("Hello");
int[][]sArray = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
sArray[i1][j1] = b.br.getVal(i1, j1);
}
}
Board d = new Board(sArray);
//System.out.println("d is ");
//d.display();
//System.out.println("p is "+ p);
int xvalue= b.x;
int yvalue = b.y;
BoardState bs = new BoardState(d,xvalue,yvalue);
if(getConfigScore(d,p) == 1)
{
//System.out.println("Winning Config");
//System.out.println("X is " + b.x + " Y is " + b.y);
// b.br.display();
State s = new State(-1,bs.x,bs.y);
return s;
}
else if (getConfigScore(d,p) == -1)
{
//System.out.println("LooseConfig");
State s = new State(1,bs.x,bs.y);
//System.out.println("Coordinates are "+bs.x + bs.y+ " for " + p);
return s;
}
else if(bs.br.isBoardFull())
{
//System.out.println("Board is full");
State s = new State(0,bs.x,bs.y);
//System.out.println("score " + s.s + "x "+ s.x + "y "+ s.y);
return s;
}
else
{
//Get Turn
//System.out.println("In else condiyion");
int turn;
if(p == 2)
{
turn = 1;
}else
{
turn = 2;
}
ArrayList<BoardState> brr = new ArrayList<BoardState>();
ArrayList<State> st = new ArrayList<State>();
brr = getAllStates(d,p);
for(int k=0;k<brr.size();k++)
{
//System.out.println("Goes in " + "turn " + turn);
//brr.get(k).br.display();
int xxxxx = computeMoveAI(brr.get(k),turn).s;
State temp = new State(xxxxx,brr.get(k).x,brr.get(k).y);
st.add(temp);
}
//Find all Nodes.
//Go to First Node and proceed with recursion.
//System.out.println("Displaying boards");
for(int i=0;i<brr.size();i++)
{
//brr.get(i).br.display();
//System.out.println(brr.get(i).x + " " + brr.get(i).y);
}
//System.out.println("Board configs are");
for(int i=0;i<st.size();i++)
{
//System.out.println(st.get(i).x + " " + st.get(i).y + " and score " + st.get(i).s);
}
//System.out.println("xvalue" + xvalue);
//System.out.println("yvalue" + yvalue);
//System.out.println("Board was");
//d.display();
//System.out.println("Coming to scores");
//System.out.println(" p is "+ p);
if(p == 2)
{
//System.out.println("Size of first response" + st.size());
//System.out.println("Returns Max");
return max(st);
}
else
{
//System.out.println("The last");
return min(st);
}
}
}
private State min(ArrayList<State> st) {
// TODO Auto-generated method stub
ArrayList<State> st1= new ArrayList<State>();
st1= st;
int min = st.get(0).s;
//System.out.println("Min score is " + min);
for(int i=1;i<st1.size();i++)
{
if(min > st1.get(i).s)
{
min = st1.get(i).s;
//System.out.println("Min is");
//System.out.println(min);
//System.out.println("Min" + min);
State s = new State(min,st1.get(i).x,st1.get(i).y);
return s;
}
}
State s = new State(st1.get(0).s,st1.get(0).x,st1.get(0).y);
//System.out.println("Max" + st1.get(0).s);
//System.out.println("Exits Min");
//System.out.println("Min Score" + st1.get(0).s + " x" + st1.get(0).x + "y " + st1.get(0).y);
return s;
}
private State max(ArrayList<State> st) {
// TODO Auto-generated method stub
//System.out.println("Size of first response in funciton is " + st.size());
ArrayList<State> st1= new ArrayList<State>();
st1 = st;
int max = st1.get(0).s;
for(int i=0;i<st1.size();i++)
{
// System.out.println(i+1 + " config is: " + "X:" + st1.get(i).x + "Y:" + st1.get(i).y + " with score " + st1.get(i).s);
}
for(int i=1;i<st1.size();i++)
{
//.out.println("Next Item " + i + st.get(i).s + "Coordinates X"+ st.get(i).x +"Coordinates Y"+ st.get(i).y );
if(max < st1.get(i).s)
{
max = st1.get(i).s;
//System.out.println("Max" + max);
//System.out.println("Max is");
//System.out.println(max);
State s = new State(max,st1.get(i).x,st1.get(i).y);
//System.out.println("Max Score returned" + s.s);
//System.out.println("Returned");
return s;
}
}
State s = new State(st1.get(0).s,st1.get(0).x,st1.get(0).y);
//System.out.println("Max" + st1.get(0).s);
//System.out.println("Max is outer");
//System.out.println(st.get(0).s);
return s;
}
//Basic brain Behind Min Max algorithm
public int getConfigScore(Board b,int p)
{
int score;
int turn ;
int opponent;
if(p == player1)
{
turn = p;
opponent = player2;
}
else
{
turn = player2;
opponent = player1;
}
int[][]sArray = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
sArray[i1][j1] = b.getVal(i1, j1);
}
}
Board d = new Board(sArray);
//System.out.println("s arrasy is ");
//d.display();
//System.out.println("turn is " + turn);
if(d.isVictoriousConfig(turn))
{
score = 1;
}
else if(d.isVictoriousConfig(opponent))
{
score = -1;
}
else
{
score = 0;
}
return score;
}
public static ArrayList<BoardState> getAllStates(Board b, int player)
{
ArrayList<BoardState> arr = new ArrayList<BoardState>();
int[][]s1 = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
s1[i1][j1] = b.getVal(i1, j1);
}
}
Board d = new Board(s1);
for(int i = 0;i <3; i ++)
{
for (int j=0;j<3;j++)
{
if(!d.isPosOccupied(i, j))
{
int previousState = d.getVal(i, j);
int[][]s = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
s[i1][j1] = d.getVal(i1, j1);
}
}
s[i][j] = player;
Board d1 = new Board(s);
BoardState bs = new BoardState(d1,i,j);
arr.add(bs);
}
}
}
return arr;
}
}
This is the output of the test case in the Game class:
Board
1 1 2
2 2 0
1 1 0
Score : X : Y -> 1: 1: 2
The solution here is score:1 for x:1, y:2. It looks correct.
But again, you could say since it is moving sequentially, and since position (1,2) will come before (2,2), it gets the right coordinate.
I understand that this may be huge lines of code to figure out the problem. But
computemoveAI(), getConfigScore() could be the functions to look out for. Also I do not want to bias your thoughts with where I think the problem could as sometimes, we look somewhere , but the problem lies elsewhere.!!

Tic Tac Toe game in Java

Ok guys...I'm stumped again.
I managed to get the game working. However, now I'm down to the point of trying to code the win conditions. I'm thinking of using a boolean array for each of the buttons, but can't figure out how to cross reference the buttons[] to the gameSquares[] to set the elements of gameSquares[] to true/false flags.
Any pointers? (Code is copied below).
** A few other interesting bugs I feel worth mentioning:
1) Start and Reset don't seem to work correctly
2) When the computer tries multiple attempts in invalid squares, the squares seem to jump or dance around. It's really weird.
package tictactoegame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
class TicTacToeBoard extends JFrame implements ActionListener
{
JButton[] buttons = new JButton[10];
boolean player1 = false, player2 = false;
boolean[] gameSquares = {false, false, false,
false, false, false,
false, false, false};
boolean startPlayer = false;
int turnCount = 0;
public TicTacToeBoard()
{
JFrame gameWindow = new JFrame();
gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
gameWindow.setSize(300,400);
gameWindow.setVisible(true);
JPanel gamePanel = new JPanel();
gamePanel.setSize(300,400);
GridLayout grid = new GridLayout(4,3);
gamePanel.setLayout(grid);
for(int i = 0; i < 9; i++)
{
buttons[i] = new JButton("");
buttons[i].addActionListener(this);
gamePanel.add(buttons[i]);
}
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this);
JButton helpButton = new JButton("Help");
helpButton.addActionListener(this);
gamePanel.add(startButton);
gamePanel.add(helpButton);
gamePanel.add(resetButton);
gameWindow.add(gamePanel);
gameWindow.pack();
while (turnCount < 9)
{
gamePlay();
}
}
public void gamePlay()
{
while(!startPlayer)
{
int random = randomGenerator();
if (random%2 == 0)
{
player1 = true;
JOptionPane.showMessageDialog(null, "Player is first.");
startPlayer = true;
}
else if (random%2 == 1)
{
player2 = true;
JOptionPane.showMessageDialog(null, "Computer is first.");
startPlayer = true;
}
}
if (player2)
{
int index;
Random randomGenerator = new Random();
index = randomGenerator.nextInt(9);
buttons[index].doClick();
player2 = false;
player1 = true;
}
}
public int randomGenerator()
{
int randomNum;
Random randomGenerator = new Random();
randomNum = randomGenerator.nextInt(100);
return randomNum;
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source instanceof JButton)
{
JButton button = (JButton) source;
if (button.getText() == "Start")
{
startPlayer = false;
player1 = false;
player2 = false;
gamePlay();
}
else if (button.getText() == "Reset")
{
for(int i = 0; i < 9; i++)
{
buttons[i].setText("");
}
startPlayer = false;
player1 = false;
player2 = false;
gamePlay();
}
else if (button.getText() == "Help")
{
JOptionPane.showMessageDialog(null, "Help:\n\n" +
"How to play-\n" +
"Select an empty square. The square will be filled with"
+ "with your symbole, either X or O.\n" +
"The game is won when either player gets three X's or"
+ "O's in a row horizontally,\n vertically, or diagonally.");
}
if (button.getText() == "" && player1)
{
button.setText("X");
turnCount += 1;
player1 = false;
player2 = true;
}
else if (button.getText() == "" && player2)
{
button.setText("O");
turnCount+=1;
player2 = false;
player1 = true;
}
else if (button.getText() == "X" || button.getText() == "O")
{
if(player2 == true)
{
gamePlay();
}
else
{
JOptionPane.showMessageDialog(null, "Invalid choice. Select"
+ " another square.");
}
}
}
}
}
Check this TicTacToe Full code using the Applets...:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
<applet code="TicTacToe.class" width="300" height="300">
</applet>
*/
public class TicTacToe extends Applet implements ActionListener {
Button[] btnarray = new Button[9];
private final static String PLAYER1 = "PLAYER1";
private final static String PLAYER2 = "PLAYER2";
private static String CURRENT_PLAYER = null;
Label lbl = new Label();
public void init() {
CURRENT_PLAYER = PLAYER1;
lbl.setText(CURRENT_PLAYER + " Turn!");
setLayout(new BorderLayout());
Panel p = new Panel();
GridLayout gl = new GridLayout(3, 3);
p.setLayout(gl);
setBackground(Color.BLACK);
setForeground(Color.WHITE);
setSize(300, 300);
Font myFont = new Font("TimesRoman", Font.BOLD, 80);
for (int i = 0; i < 9; i++) {
btnarray[i] = new Button(null);
btnarray[i].setActionCommand("" + i);
btnarray[i].addActionListener(this);
btnarray[i].setFont(myFont);
btnarray[i].setBackground(Color.white);
p.add(btnarray[i]);
}
add(BorderLayout.CENTER, p);
add(BorderLayout.NORTH, lbl);
add(BorderLayout.SOUTH, new Label("Player 1 => X , Player 2 => 0"));
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int index = Integer.parseInt(e.getActionCommand());
btnarray[index].disable();
if (CURRENT_PLAYER == PLAYER1) {
btnarray[index].setLabel("X");
CURRENT_PLAYER = PLAYER2;
} else {
btnarray[index].setLabel("0");
CURRENT_PLAYER = PLAYER1;
}
lbl.setText(CURRENT_PLAYER + " Turn!");
check();
}
void check() {
String[] pattern = new String[8];
pattern[0] = btnarray[0].getLabel() + btnarray[1].getLabel()
+ btnarray[2].getLabel();
pattern[1] = btnarray[3].getLabel() + btnarray[4].getLabel()
+ btnarray[5].getLabel();
pattern[2] = btnarray[6].getLabel() + btnarray[7].getLabel()
+ btnarray[8].getLabel();
pattern[3] = btnarray[0].getLabel() + btnarray[3].getLabel()
+ btnarray[6].getLabel();
pattern[4] = btnarray[1].getLabel() + btnarray[4].getLabel()
+ btnarray[7].getLabel();
pattern[5] = btnarray[2].getLabel() + btnarray[5].getLabel()
+ btnarray[8].getLabel();
pattern[6] = btnarray[0].getLabel() + btnarray[4].getLabel()
+ btnarray[8].getLabel();
pattern[7] = btnarray[2].getLabel() + btnarray[4].getLabel()
+ btnarray[6].getLabel();
int j = 0;
while (j < 8) {
char[] array = pattern[j].toCharArray();
if (array[0] == 'X' && array[1] == 'X' && array[2] == 'X') {
lbl.setText(PLAYER1 + " Wins!");
} else if (array[0] == '0' && array[1] == '0' && array[2] == '0') {
lbl.setText(PLAYER2 + " Wins!");
}
j++;
}
}
}

Reacting to a specific char - TCP and char[][] issue

I'm creating a TCP game of Battleship in Java, and as I've made some functions work, methods that used to work no longer work.
Here's what's happening when it's a users turn. A bomb being dropped on 2 diffrent char[][], where clientGrid is the actual grid where the client has his ships. It's on this grid where the dropBomb method is being printed, and tells us whether a bomb has hit or not. clientDamage is just an overview for the server to see where he has previously dropped bombs.
if (inFromServer.ready()) {
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, clientGrid));
dropBomb(x, y, clientDamage);
outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
System.out.println(printBoard(clientDamage));
}
Here's the drop bomb method. It's proved to work before, however I have made some small changes to it. However I can't see why it wouldn't work. + indicates that there is a ship, x indicates that the target already has been bombed, and the else is ~, which is water. The method always returns "Nothing was hit on this coordinate...", and I can't seem to figure out why?
public static String dropBomb(int row, int col, char[][] board) {
if (row < gridSize && col < gridSize) {
if (board[row][col] == '+') {
board[row][col] = 'x';
return "Ship has been hit!";
} else if (board[row][col] == 'x') {
return "Already bombed.";
} else {
board[row][col] = 'x';
return "Nothing was hit on this coordinate...";
}
} else {
return "No such coordinate.";
}
}
Here is the full code... can someone please point out what I'm missing?
//server = player 1
//client = player 2
public class BattleshipGame {
public static ArrayList<Ship> fleet;
public static InetAddress clientAddress;
public static BattleshipGame battleship;
private final static int gridSize = 11;
public final static int numberOfShips = 3;
public static char[][] serverGrid;
public static char[][] clientGrid;
public static char[][] serverDamage;
public static char[][] clientDamage;
private int whosTurn;
private int whoStarts;
public static int count;
public static int bombCount;
public BattleshipGame() {
whoStarts = 0;
start();
showShipList();
}
public static String printBoard(char[][] board) {
String out = "";
for (int i = 1; i < board.length; i++) {
for (int j = 1; j < board.length; j++) {
out += board[j][i];
}
out += '\n';
}
return out;
}
public void start() {
Random rand = new Random();
if (rand.nextBoolean()) {
whoStarts = 1;
whosTurn = 1;
} else {
whoStarts = 2;
whosTurn = 2;
}
whoStarts = 1;
whosTurn = 1;
System.out.println("Player " + whoStarts + " starts\n");
}
public void initializeGrid(int playerNo) {
serverGrid = new char[gridSize][gridSize];
for (int i = 0; i < serverGrid.length; i++) {
for (int j = 0; j < serverGrid.length; j++) {
serverGrid[i][j] = '~';
}
}
serverDamage = new char[gridSize][gridSize];
for (int i = 0; i < serverDamage.length; i++) {
for (int j = 0; j < serverDamage.length; j++) {
serverDamage[i][j] = '~';
}
}
clientGrid = new char[gridSize][gridSize];
for (int i = 0; i < clientGrid.length; i++) {
for (int j = 0; j < clientGrid.length; j++) {
clientGrid[i][j] = '~';
}
}
clientDamage = new char[gridSize][gridSize];
for (int i = 0; i < clientDamage.length; i++) {
for (int j = 0; j < clientDamage.length; j++) {
clientDamage[i][j] = '~';
}
}
if (playerNo == 1) {
System.out.println("\nYour grid (player 1):\n"
+ printBoard(serverGrid));
} else if (playerNo == 2) {
System.out.println("\nYour grid (player 2):\n"
+ printBoard(clientGrid));
} else {
System.out.println("No such player.");
}
}
public static void deployShip(char[][] board, Ship ship, char direction,
int x, int y) {
if (direction == 'H') {
if (x < gridSize && y < gridSize) {
for (int i = 0; i < ship.getSize(); i++) {
board[x + i][y] = '+';
}
System.out
.println("Ship has been placed horizontally on coordinates "
+ x + ", " + y + ".");
} else {
System.out.println("Unable to place ship in this coordinate.");
}
} else if (direction == 'V') {
if (x < gridSize && y < gridSize) {
for (int i = 0; i < ship.getSize(); i++) {
board[x][y + i] = '+';
}
System.out
.println("Ship has been placed vertically on coordinates "
+ x + ", " + y + ".");
} else {
System.out.println("Unable to place ship in this coordinate.");
}
}
}
public static String dropBomb(int row, int col, char[][] board) {
if (row < gridSize && col < gridSize) {
if (board[row][col] == '+') {
System.out.println(board[row][col]);
board[row][col] = 'x';
bombCount++;
return "Ship has been hit!";
}
if (board[row][col] == 'x') {
System.out.println(board[row][col]);
bombCount++;
return "Already bombed.";
}
if (board[row][col] == '~') {
System.out.println(board[row][col]);
board[row][col] = 'x';
bombCount++;
return "Nothing was hit on this coordinate...";
}
} else {
return "No such coordinate.";
}
return "";
}
public void showShipList() {
System.out
.println("Choose ships to add to your fleet from the following list ("
+ numberOfShips + " ships allowed):");
ArrayList<Ship> overview = new ArrayList<Ship>();
Ship ac = new Ship("Aircraft carrier", 5, false);
Ship bs = new Ship("Battleship", 4, false);
Ship sm = new Ship("Submarine", 3, false);
Ship ds = new Ship("Destroyer", 3, false);
Ship sp = new Ship("Patrol Boat", 2, false);
overview.add(ac);
overview.add(bs);
overview.add(sm);
overview.add(ds);
overview.add(sp);
for (int i = 0; i < overview.size(); i++) {
System.out.println(i + 1 + ". " + overview.get(i));
}
}
public static ArrayList<Ship> createFleet(ArrayList<Ship> fleet, int choice) {
if (count < numberOfShips && choice > 0 && choice < 6) {
if (choice == 1) {
Ship ac = new Ship("Aircraft carrier", 5, false);
fleet.add(ac);
count++;
System.out.println("Aircraft carrier has been added to fleet.");
} else if (choice == 2) {
Ship bs = new Ship("Battleship", 4, false);
fleet.add(bs);
count++;
System.out.println("Battleship has been added to fleet.");
} else if (choice == 3) {
Ship sm = new Ship("Submarine", 3, false);
fleet.add(sm);
count++;
System.out.println("Submarine has been added to fleet.");
} else if (choice == 4) {
Ship ds = new Ship("Destroyer", 3, false);
fleet.add(ds);
count++;
System.out.println("Destroyer has been added to fleet.");
} else if (choice == 5) {
Ship sp = new Ship("Patrol Boat", 2, false);
fleet.add(sp);
count++;
System.out.println("Patrol boat has been added to fleet.");
}
} else {
System.out.println("Not an option.");
}
System.out.println("\nYour fleet now contains:");
for (Ship s : fleet) {
System.out.println(s);
}
return fleet;
}
}
public class TCPServer extends BattleshipGame {
private static final int playerNo = 1;
public static void main(String[] args) {
System.out.println("You are player: " + playerNo);
battleship = new BattleshipGame();
try {
InetAddress.getLocalHost().getHostAddress();
ServerSocket serverSocket = new ServerSocket(6780);
Socket socket = serverSocket.accept();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
Scanner scan = new Scanner(System.in);
while (true) {
if (inFromServer.ready()) {
setup(scan, playerNo);
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, clientGrid));
System.out.println(printBoard(clientGrid));
dropBomb(x, y, clientDamage);
outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
printBoard(clientDamage);
}
if (inFromClient.ready()) {
System.out.println(inFromClient.readLine());
System.out.println(printBoard(serverGrid));
}
}
// socket.close();
// serverSocet.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setup(Scanner inFromUser, int playerNo) {
fleet = new ArrayList<Ship>();
while (count < numberOfShips) {
createFleet(fleet, inFromUser.nextInt());
}
battleship.initializeGrid(playerNo);
for (int i = 0; i < fleet.size(); i++) {
System.out.println(fleet.get(i));
System.out.println("Define direction (V/H) plus coordinates");
deployShip(serverGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
}
System.out.println("Placements:\n" + printBoard(serverGrid));
System.out.println("Fleet has been deployed. Press enter to continue.\n");
}
}
public class TCPClient extends BattleshipGame {
private static final int playerNo = 2;
public static void main(String[] args) {
System.out.println("You are player: " + playerNo);
battleship = new BattleshipGame();
try {
InetAddress.getLocalHost().getHostAddress();
Socket socket = new Socket(InetAddress.getLocalHost()
.getHostAddress(), 6780);
DataOutputStream dataOutputStream = new DataOutputStream(
socket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(System.in));
Scanner scan = new Scanner(System.in);
setup(scan, playerNo);
while (true) {
if (inFromClient.ready()) {
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, serverGrid));
dropBomb(x, y, serverDamage);
dataOutputStream.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
System.out.println(printBoard(serverDamage));
}
if (inFromServer.ready()) { // modtag data fra server
System.out.println(inFromServer.readLine());
System.out.println(printBoard(clientGrid));
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setup(Scanner inFromUser, int playerNo) {
fleet = new ArrayList<Ship>();
while (count < numberOfShips) {
createFleet(fleet, inFromUser.nextInt());
}
battleship.initializeGrid(playerNo);
for (int i = 0; i < fleet.size(); i++) {
System.out.println(fleet.get(i));
System.out.println("Define direction (V/H) plus coordinates");
deployShip(clientGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
}
System.out.println("Placements:\n" + printBoard(clientGrid));
System.out.println("Fleet has been deployed. Press enter to continue.\n");
}
}
package Battleships;
public class Ship {
private String name;
private int size;
private boolean isDestroyed;
public Ship(String n, int s, boolean d) {
this.name = n;
this.size = s;
this.isDestroyed = d;
}
public String getName() {
String output = "";
output = "[" + name + "]";
return output;
}
public int getSize() {
return size;
}
public String toString() {
String output = "";
output = "[" + name + ", " + size + ", " + isDestroyed + "]";
return output;
}
}

Categories

Resources