Friday, April 11

8 Queens Chess Puzzle with Source [Java]

The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens attack each other.
Thus, a solution requires that no two queens share the same row, column, or diagonal.

In this program I have used AWT majorly and Swing (JOptionPane) a bit for displaying alert messages.
Below is the full working source code with comments included on what is done in it. There might be other optimal ways to do the same task which I have done but this the way I have done it.

import java.awt.*;      //For Buttons n Layout
import java.awt.event.*;    //For Mouse Click Events
import java.util.*;      //Rest of the stuff

import javax.swing.JOptionPane;   //For Alert Messages 

//Main Class
public class EightQueens extends Frame implements WindowListener, ActionListener
{
 //Buttons Array
 Button b[][]=new Button[8][8];

 //ArrayList Collection of the positions which are banned or the ones that have queens already placed!
 ArrayList<Point> bannedPositions =  new ArrayList<Point>();
 
 //Total number of Queens placed!
 int queensPlaced;

 //Default Constructor
 EightQueens()
 {
  //Activating Window Lister for Monitoring Close,Minimise Events
  addWindowListener(this);
  
  //Designing the Chess Board 8x8 and placing buttons on it using the array we created previously.
  setLayout(new GridLayout(8,8));
  for(int i=0;i<8;i++)
  {
   for(int j=0;j<8;j++)
   {
    b[i][j]=new Button();
    b[i][j].addActionListener(this); //Activating Action Listener to monitor mouse clicks on the buttons.
    
    if(((i%2)^(j%2))==0)
    {
     b[i][j].setBackground(Color.WHITE);
     b[i][j].setForeground(Color.RED);
     
    }
    else
    {
     b[i][j].setBackground(Color.BLACK);
     b[i][j].setForeground(Color.RED);
    }
   
    add(b[i][j]);
   }
  }
  
  //Welcome message to be displayed regarding how to play this game! 
  JOptionPane.showMessageDialog(null, "The eight queens puzzle is the problem of placing eight chess queens\n"
    + "on an 8x8 chessboard so that no two queens attack each other.\n"
    + "Thus, a solution requires that no two queens share the same row, column, or diagonal.");
 }

 //Main Method
 public static void main(String[] args) 
 {
  EightQueens c1=new EightQueens();     //Creating the Object
  c1.setVisible(true);        //Making it visible
  c1.setSize(600,600);        //Setting a fixed window size
  c1.setResizable(false);        //Disabling resize or maximize
  c1.setTitle("8 Queens Chess by Shaliwahan");  //Title for the Window
 }
 
 @Override
 public void windowActivated(WindowEvent arg0) {
  // Implementation of WindowListener interface
 }
 
 @Override
 public void windowClosed(WindowEvent arg0) {
  // Implementation of WindowListener interface
  
 }
 
 @Override
 public void windowClosing(WindowEvent arg0) 
 { 
  //Message to be displayed when the window is closed!
  JOptionPane.showMessageDialog(null, "Thank You for playing!!");
  System.exit(0);
 }
 
 @Override
 public void windowDeactivated(WindowEvent arg0) {
  // Implementation of WindowListener interface
  
 }
 
 @Override
 public void windowDeiconified(WindowEvent arg0) {
  // Implementation of WindowListener interface
  
 }
 
 @Override
 public void windowIconified(WindowEvent arg0) {
  // Implementation of WindowListener interface
  
 }
 
 @Override
 public void windowOpened(WindowEvent arg0) {
  // Implementation of WindowListener interface 
 }
 
 // Implementation of ActionListener interface
 @Override
 public void actionPerformed(ActionEvent ae)
 {
  for(int i=0;i<8;i++)
  {
   for(int j=0;j<8;j++)
   {
    if (ae.getSource()==b[i][j])  //Getting the source of the button clicked!
    {
     Point coOrd = new Point(i,j); //Storing the co-ordinates in a Point

     
     /* Verifying if the ArrayList Collection of the
      * positions which are banned or the ones that have queens already placed
      * contains the currently clicked position.
      */
     
     if(bannedPositions.contains(coOrd))
     {
      //If the position is not allowed then display this message.
      JOptionPane.showMessageDialog(null, "Cannot place a Queen on this position!!");
     }
     else
     {
      //Place a label on that Button
      b[i][j].setLabel("Queen");
      
      //Increment the total count of the Queens placed
      queensPlaced++;
      
      //Add Original clicked button position to the ArrayList
      bannedPositions.add(new Point((i),(j)));
      
      //Add all Horizontal-Right  Positions to the ArrayList
      int a = j;
      for(int hr = 0;hr<8;hr++)
      {
       bannedPositions.add(new Point((i),(a+1)));
       a++;
      }
      
      //Add all Horizontal-Left Positions to the ArrayList
      int b = j;
      for(int hl = 0;hl<8;hl++)
      {
       bannedPositions.add(new Point((i),(b-1)));
       b--;
      }
      
      //Add all Vertical-Top Positions to the ArrayList
      int c = i;
      for(int z = 0;z<8;z++)
      {
       bannedPositions.add(new Point((c+1),(j)));
       c++;
      }
      
      //Add all Vertical-Bottom Positions to the ArrayList
      int d = i;
      for(int z = 0; z<8;z++)
      {
       bannedPositions.add(new Point((d-1),(j)));
       d--;
      }
      
      //Add all Diagonal-Top-Right Positions to the ArrayList
      int e = i;
      int f = j;
      for(int z = 0; z<8;z++)
      {
       bannedPositions.add(new Point((e-1),(f+1)));
       e--;
       f++;
      }
      
      //Add all Diagonal-Top-Left Positions to the ArrayList
      int g = i;
      int h = j;
      for(int z = 0; z<8;z++)
      {
       bannedPositions.add(new Point((g-1),(h-1)));
       g--;
       h--;
       
      }
      
      //Add all Diagonal-Bottom-Right Positions to the ArrayList
      int k = i;
      int l = j;
      for(int z = 0; z<8;z++)
      {
       bannedPositions.add(new Point((k+1),(l+1)));
       k++;
       l++;
      }
      
      //Add all Diagonal-Bottom-Left Postions to the ArrayList
      int m = i;
      int n = j;
      for(int z = 0; z<8;z++)
      {
       bannedPositions.add(new Point((m+1),(n-1)));
       m++;
       n--;
       
      }
      
      //Check if the total placed Queens are exactly equal to 8
      if(queensPlaced == 8)
      {
       //Display winning message and close the window.
       JOptionPane.showMessageDialog(null, "Congratulations You Won!! The Game will now Close! Thank You for Playing!");
       System.exit(0);
       
      }
     }
    }
   }
  }
 }
}

You can also directly download the source code, class file (pretty useless for most) and/or a working runnable jar below.

Download

Hope this post helps all the newbie Java Programmers who are looking for this program. If you have any questions or suggestions please feel free to leave a comment.

No comments:

Post a Comment

Comment anything you want. Just be polite and give respect to others!
I am simply going to remove the comments which are offensive or are off topic.
And please don't spam your website links in comments. I don't, neither should you.