4 Replies Latest reply on Apr 5, 2013 2:12 PM by rukbat

    Java help

    1001309
      Currently creating a noughts on crosses game can anyone help with the following
      1. How to fix the code so the player wins when he gets 3 in a row
      2. First need to provide persistent scores (a total of games won, drawn and lost for each player) and i dont no how.

      import java.awt.*; //
      import java.awt.event.*; //
      import javax.swing.*; //
      import java.io.*; //

      @SuppressWarnings("serial") // Checks for errors
      public class TTTGraphics2P extends JFrame { // Name of class so the game can be created


           
      // Grid Layout
      public static final int ROWS = 4;
      public static final int COLS = 4;


      // Constants for creating the board
      public static final int CELL_SIZE = 50; // cell width and height (square)
      public static final int CANVAS_WIDTH = CELL_SIZE * COLS; // Allows the canvas to be drawn
      public static final int CANVAS_HEIGHT = CELL_SIZE * ROWS;
      public static final int GRID_WIDTH = 6;
      public static final int GRID_WIDHT_HALF = GRID_WIDTH / 1;
      // Grid line's width

      public static final int CELL_PADDING = CELL_SIZE / 4; // Size of the padding the bigger the number bigger the O or X
      public static final int SYMBOL_SIZE = CELL_SIZE - CELL_PADDING * 2; // cell width/height
      public static final int SYMBOL_STROKE_WIDTH = 3; // width of the O and X


      public enum GameState {
      PLAYING, DRAW, CROSS_WON, NOUGHT_WON
      // Represents the value of which player won / lost
      }
      private GameState currentState; // the current game state

      // Use an enum to represent the seeds and cell contents
      public enum Seed {
      EMPTY, CROSS, NOUGHT
      }
      private Seed currentPlayer; // current player 1 or 2

      private Seed[][] board ; // Game board created
      private DrawCanvas canvas; // Drawing canvas for the game board
      private JLabel statusBar; // Status Bar

      /** Constructor to setup the game and the GUI components */
      public TTTGraphics2P() {
      canvas = new DrawCanvas(); // Construct a drawing canvas (a JPanel)
      canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));

      // Code used to create a mouse click so they can place a O or X in the square
      canvas.addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent e) { 
      int mouseX = e.getX();
      int mouseY = e.getY();

      int rowSelected = mouseY / CELL_SIZE;
      int colSelected = mouseX / CELL_SIZE;
      // Code above shows the row / colum selected


      if (currentState == GameState.PLAYING) {
      if (rowSelected >= 0 && rowSelected < ROWS && colSelected >= 0
      && colSelected < COLS && board[rowSelected][colSelected] == Seed.EMPTY) {
      board[rowSelected][colSelected] = currentPlayer; // Allows a move to be made
      updateGame(currentPlayer, rowSelected, colSelected); // update state

      currentPlayer = (currentPlayer == Seed.CROSS) ? Seed.NOUGHT : Seed.CROSS; // Code allows the player to switch and have there go
      }
      } else {       // game over
      initGame(); // restarts the game
      }
      // Refresh the canvas back to default
      repaint();
      }
      });


      statusBar = new JLabel(" ");
      statusBar.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 15));
      statusBar.setBorder(BorderFactory.createEmptyBorder(2, 5, 4, 5));
      // Message bar after the games finished

      Container cp = getContentPane();
      cp.setLayout(new BorderLayout());
      cp.add(canvas, BorderLayout.CENTER);
      cp.add(statusBar, BorderLayout.PAGE_END);

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      pack(); // pack all the components in this JFrame
      setTitle("Tic Tac Toe");
      setVisible(true); // show this JFrame

      board = new Seed[ROWS][COLS]; // sets up the rows / colums
      initGame(); // initialize the game board contents and game variables
      }

      /** Initialize the game-board contents and the status */
      public void initGame() {
      for (int row = 0; row < ROWS; row++) {
      for (int col = 0; col < COLS; col++) {
      board[row][col] = Seed.EMPTY; // Constructer should assign an empty board to all zeros
      }
      }
      currentState = GameState.PLAYING; // Game is up and ready to begin
      currentPlayer = Seed.NOUGHT; // Change this part of the coding to dedicate which player goes first
      }

      // Updates the current board check for win / draw
      public void updateGame(Seed theSeed, int rowSelected, int colSelected) {
      if (hasWon(theSeed, rowSelected, colSelected)) {
      currentState = (theSeed == Seed.CROSS) ? GameState.CROSS_WON : GameState.NOUGHT_WON;
      } else if (isDraw()) { 
      currentState = GameState.DRAW;
      }
      // Otherwise, no change to current state boolean false game still playing.
      }

      // boolean to true the move is a draw
      public boolean isDraw() {
      for (int row = 0; row < ROWS; row++) {
      for (int col = 0; col < COLS; col++) {
      if (board[row][col] == Seed.EMPTY) {
      return false; // an empty cell found, not draw, exit
      }
      }
      }
      return true; // no more empty cell, it's a draw
      }

      /** Return true if the player with "theSeed" has won after placing at
      (rowSelected, colSelected) */ //boolean represented
      public boolean hasWon(Seed theSeed, int rowSelected, int colSelected) {
      return (board[rowSelected][0] == theSeed // 4 in the row
      && board[rowSelected][1] == theSeed
      && board[rowSelected][2] == theSeed
      && board[rowSelected][3] == theSeed

      || board[0][colSelected] == theSeed // 4 in the column
      && board[1][colSelected] == theSeed
      && board[2][colSelected] == theSeed
      && board[3][colSelected] == theSeed


      || rowSelected == colSelected // 4 diagonal
      && board[0][0] == theSeed
      && board[1][1] == theSeed
      && board[2][2] == theSeed
      && board[3][3] == theSeed


      || rowSelected + colSelected == 2 // 4 in the other diagonal
      && board[0][2] == theSeed
      && board[1][1] == theSeed
      && board[2][0] == theSeed)
      && board[3][0] == theSeed;
      }


      class DrawCanvas extends JPanel {
      @Override
      public void paintComponent(Graphics g) {  // invoke via repaint()
      super.paintComponent(g); // fill background
      setBackground(Color.WHITE); // set its background color

      // Draw the grid-lines
      g.setColor(Color.LIGHT_GRAY);
      for (int row = 1; row < ROWS; row++) {
      g.fillRoundRect(0, CELL_SIZE * row - GRID_WIDHT_HALF,
      CANVAS_WIDTH-1, GRID_WIDTH, GRID_WIDTH, GRID_WIDTH);
      }
      for (int col = 1; col < COLS; col++) {
      g.fillRoundRect(CELL_SIZE * col - GRID_WIDHT_HALF, 0,
      GRID_WIDTH, CANVAS_HEIGHT-1, GRID_WIDTH, GRID_WIDTH);
      }

      // Draw the Seeds of all the cells if they are not empty
      // Use Graphics2D which allows us to set the pen's stroke
      Graphics2D g2d = (Graphics2D)g;
      g2d.setStroke(new BasicStroke(SYMBOL_STROKE_WIDTH, BasicStroke.CAP_ROUND,
      BasicStroke.JOIN_ROUND)); // Graphics2D only
      for (int row = 0; row < ROWS; row++) {
      for (int col = 0; col < COLS; col++) {
      int x1 = col * CELL_SIZE + CELL_PADDING;
      int y1 = row * CELL_SIZE + CELL_PADDING;
      if (board[row][col] == Seed.CROSS) {
      g2d.setColor(Color.RED);
      int x2 = (col + 1) * CELL_SIZE - CELL_PADDING;
      int y2 = (row + 1) * CELL_SIZE - CELL_PADDING;
      g2d.drawLine(x1, y1, x2, y2);
      g2d.drawLine(x2, y1, x1, y2);
      } else if (board[row][col] == Seed.NOUGHT) {
      g2d.setColor(Color.BLUE);
      g2d.drawOval(x1, y1, SYMBOL_SIZE, SYMBOL_SIZE);
      }
      }
      }


      System.out.println(" 1 2 3");
      System.out.println("A" + board[0][0] + "|" + board[0][1] + "|" + board[0][2]);
      System.out.println("-----");
      System.out.println("B" + board[1][0] + "|" + board[1][1] + "|" + board[1][2]);
      System.out.println("-----");
      System.out.println("C" + board[2][0] + "|" + board[2][1] + "|" + board[2][2]);


      if (currentState == GameState.PLAYING) {
      statusBar.setForeground(Color.BLACK);
      if (currentPlayer == Seed.CROSS) {
      statusBar.setText("X's Turn");
      } else {
      statusBar.setText("O's Turn");
      }
      } else if (currentState == GameState.DRAW) {
      statusBar.setForeground(Color.RED);
      statusBar.setText("It's a Draw! Click to play again.");
      } else if (currentState == GameState.CROSS_WON) {
      statusBar.setForeground(Color.RED);
      statusBar.setText("'X' Won! Click to play again.");
      } else if (currentState == GameState.NOUGHT_WON) {
      statusBar.setForeground(Color.RED);
      statusBar.setText("'O' Won! Click to play again.");
      // Prints the message of whos turn / won / play again
      }
      }
      }

      // Allows files to be read
           public static void main(String[] args) {
                try {
                FileWriter out = new FileWriter("lpt1");
                out.write("Hello world");
                out.write(0x0D); // CR
                out.close();
                }
                catch (IOException e) {
                e.printStackTrace();
                }
                
                
      SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
      new TTTGraphics2P(); // Let the constructor do the job
      }
      });
      }
      }