Home > Source Code > Source code of Sudoku Game in Java

Source code of Sudoku Game in Java

Before starting you should know this project is now older version. Updated version is here.

Sudoku is my first java project. this is developed by java, using  J-Creator IDE also developed using  NetBeans IDE and Eclipse IDE. This game has some few options:

  • User can set label of this game there are three label
    1. Beginner
    2. Inter mediator
    3. Expert
  • There is an new Game option to start new game.
  • If user finished the game user should select submit option to check the result.
  • Exit option will help the user to quit the game.
 Here is the Screen shot of this game:
 

there is two .java files

  1. Logic.java and
  2. GraphicallyRepresentation.java
Logic.java contains all the gaming logic to create a game state. the source code is given bellow:

Logic.java :

import java.util.*; //for random number

class Logic
 {
 int[][] blockS={{4, 3, 5, 8, 7, 6, 1, 2, 9},{8, 7, 6, 2, 1, 9, 3, 4, 5},{2, 1, 9, 4, 3, 5, 7, 8, 6},
 {5, 2, 3, 6, 4, 7, 8,9, 1},{9, 8, 1, 5, 2, 3, 4, 6, 7},{6, 4, 7, 9, 8, 1, 2, 5,3},{7, 5, 4, 1, 6,8, 9, 3, 2},
 {3, 9, 2, 7, 5, 4, 6, 1, 8},{1, 6, 8, 3, 9 ,2, 5, 7, 4}};

Random R_num=new Random(); //random numbers to exchange rows
 Random Grid_R_num=new Random();//random numbers to exchange GRIDS
 Random R_exnum=new Random();
 Random H_Rnum=new Random();

int firstrow,secondrow,firstcol,secondcol,firstgrid,secondgrid,gc=0;
 int carry[]=new int[9];
 int blockh[][]=new int[9][9];
 int blockc[][]=new int [9][9];

int[][] generate()
 { ////switching the rows
 //randomly choosing one of the tow rows to be changed
 int x=10+R_num.nextInt(10);
 for(int y=0;y<x;y++)
 {
 for(int a=0;a<3;a++)
 {
 //System.out.println("a="+a);

if(a==0)
 {
 firstrow=R_num.nextInt(3);
 secondrow=R_num.nextInt(3);
 }

else if(a==1)
 {
 firstrow=3+R_num.nextInt(3);
 secondrow=3+R_num.nextInt(3);
 }

else if(a==2)
 {
 firstrow=6+R_num.nextInt(3);
 secondrow=6+R_num.nextInt(3);
 }

for(int i=0;i<9;i++)
 {
 carry[i]=blockS[firstrow][i];
 blockS[firstrow][i]=blockS[secondrow][i];
 blockS[secondrow][i]=carry[i];
 }
 }
 //switching the rows complete

//Switchicng the column
 for(int a=0;a<3;a++)
 {
 if(a==0)
 {
 firstcol=R_num.nextInt(3);
 secondcol=R_num.nextInt(3);
 }

else if(a==1)
 {
 firstcol=3+R_num.nextInt(3);
 secondcol=3+R_num.nextInt(3);
 }

else if(a==2)
 {
 firstcol=6+R_num.nextInt(3);
 secondcol=6+R_num.nextInt(3);
 }

for(int i=0;i<9;i++)
 {
 carry[i]=blockS[i][firstcol];
 blockS[i][firstcol]=blockS[i][secondcol];
 blockS[i][secondcol]=carry[i];
 }
 }
 }
 //Switchicng the column complet
 //Switchicng the grids
 firstgrid=1+Grid_R_num.nextInt(3);
 secondgrid=1+Grid_R_num.nextInt(3);

if((firstgrid==1&&secondgrid==2)||(firstgrid==2&&secondgrid==1))
 {
 for(int i=0;i<3;i++)
 for(int j=0;j<9;j++)
 {
 carry[j]=blockS[i][j];
 blockS[i][j]=blockS[i+3][j];
 blockS[i+3][j]=carry[j];
 }
 }
 else if((firstgrid==2&&secondgrid==3)||(firstgrid==3&&secondgrid==2))
 {
 for(int i=3;i<6;i++)
 for(int j=0;j<9;j++)
 {
 carry[j]=blockS[i][j];
 blockS[i][j]=blockS[i+3][j];
 blockS[i+3][j]=carry[j];
 }
 }
 else if((firstgrid==1&&secondgrid==3)||(firstgrid==3&&secondgrid==1))
 {
 for(int i=0;i<3;i++)
 for(int j=0;j<9;j++)
 {
 carry[j]=blockS[i][j];
 blockS[i][j]=blockS[i+6][j];
 blockS[i+6][j]=carry[j];
 }
 }
 //Swithing complete of tow grids

//suffling the puzzle
 int firstnum,secondnum,shuffle;

shuffle=3+R_num.nextInt(6);

for(int k=0;k<shuffle;k++)
 {
 firstnum=1+R_exnum.nextInt(9);
 secondnum=1+R_exnum.nextInt(9);

for(int i=0;i<9;i++)
 for(int j=0;j<9;j++)
 {
 if(blockS[i][j]==firstnum)
 {
 blockS[i][j]=secondnum;
 continue;
 }

if(blockS[i][j]==secondnum)
 blockS[i][j]=firstnum;
 }
 }
 return blockS;
 }
 //will save the complet puzzle
 int[][] save()
 {
 if(gc==0)
 blockc=generate();

gc=1;

return blockc;
 }

//will hide number of puzzle

int[][] hide()
 {
 for(int i=0;i<9;i++)
 for(int j=0;j<9;j++)
 blockh[i][j]=blockc[i][j];

int row,column,hidingnum;

hidingnum=50+R_num.nextInt(10);

for(int i=0;i<hidingnum;i++)
 {
 row=H_Rnum.nextInt(9);
 column=H_Rnum.nextInt(9);
 blockh[row][column]=0;
 }
 return blockh;
 }

//will show main puzzle

/*void show()
 {
 for(int i=0;i<9;i++)
 {
 System.out.println();
 for(int j=0;j<9;j++)
 System.out.print(" "+blockS[i][j]);
 }
 System.out.println("\n");
 System.out.println("\n");
 blockS=save();
 for(int i=0;i<9;i++)
 {
 System.out.println();
 for(int j=0;j<9;j++)
 System.out.print(" "+blockS[i][j]);
 }
 System.out.println("\n");
 System.out.println("\n");
 blockS=hide();
 for(int i=0;i<9;i++)
 {
 System.out.println();
 for(int j=0;j<9;j++)
 System.out.print(" "+blockS[i][j]);
 }
 }*/
 /*public static void main (String[] args) {

Logic ob=new Logic();
 //ob.generate();
 ob.show();
 //System.out.println();
 //ob.save();
 //ob.show();
 //ob.hide();
 //ob.show();
 }*/
 }

GraphicallyRepresentation.java provides user interface which interact with the Logic.java. Game start from this file because it contains the main() method. The source code is :

GraphicallyRepresentation.java :

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

class GraphicallyRepresentation extends JFrame implements ActionListener
 {
 Container con;
 JButton b[][]=new JButton[9][9];
 TextField t[]=new TextField[61];
 JMenuBar mbar;
 JMenu file,help,option,setting;
 JMenuItem submit,exit,about,Reset;

int[][] cp=new int[9][9];
 int[][] ip=new int[9][9];

GraphicallyRepresentation()
 {
 super("Play Sudoku .............(Created by farsim & hasib)");
 setSize(500,500);
 //setresizeable(false);

con=getContentPane();
 con.setLayout(new GridLayout(9,9));

Mylogic ob1=new Mylogic();
 ob1.complet_puzzle();
 ob1.puzzle();

int c=0;
 for(int i=0;i<9;i++)
 for(int j=0;j<9;j++)
 {
 b[i][j]=new JButton(""+ip[i][j]);
 b[i][j].setFont(new Font("ARIALBD",Font.BOLD,20));
 b[i][j].setForeground(Color.BLUE);
 if(ip[i][j]==0)
 {
 //b[i][j]=new JButton("");
 b[i][j].setText("");
 b[i][j].setBackground(Color.WHITE);
 b[i][j].addActionListener(this);

}

con.add(b[i][j]);

if(i==3 || i==4 || i==5 || j==3 || j==4 || j==5)
 {
 if(2<i></i> {
 b[i][j].setBackground(Color.CYAN);
 continue;
 }
 b[i][j].setBackground(Color.pink);

}

else
 b[i][j].setBackground(Color.CYAN);
 }

mbar=new JMenuBar();
 setJMenuBar(mbar);

file=new JMenu("File");
 option=new JMenu("Option");
 setting=new JMenu("Setting");
 help=new JMenu("Help");

about=new JMenuItem("About");
 Reset=new JMenuItem("reset");
 submit=new JMenuItem("Submit");
 exit=new JMenuItem("Exit");

submit.addActionListener(
 new ActionListener(){
 public void actionPerformed(ActionEvent e)
 {
 int r=0;

for(int i=0;i<9;i++)
 for(int j=0;j<9;j++)
 if(cp[i][j]!=Integer.parseInt(b[i][j].getText()))
 {r=1;
 break;}

for(int i=0;i<9;i++)
 {
 System.out.println();
 for(int j=0;j<9;j++)
 {
 System.out.print(cp[i][j]);
 System.out.print(Integer.parseInt(b[i][j].getText())+" ");
 }}
 System.out.print("\n"+r);
 if(r==0)
 JOptionPane.showMessageDialog(GraphicallyRepresentation.this,"You won the Game");
 //System.out.println("You won the Game");
 else
 //System.out.println("You lose the Game");
 JOptionPane.showMessageDialog(GraphicallyRepresentation.this,"You lose the Game"); }

});
 exit.addActionListener(
 new ActionListener(){
 public void actionPerformed(ActionEvent e)
 {
 System.exit(0);
 }

});

about.addActionListener(
 new ActionListener(){
 public void actionPerformed(ActionEvent e)
 {
 JOptionPane.showMessageDialog( GraphicallyRepresentation.this,
 "FARSiM & HASiB JIgni Dost! SUST CSE 15batch PRODUCT....Our first project of java language ",
 "About", JOptionPane.PLAIN_MESSAGE );
 }
 }
 );
 Reset.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent e)
 {
 //recall();
 }
 });

file.add(Reset);
 file.add(submit);
 file.addSeparator();
 file.add(exit);
 mbar.add(file);
 mbar.add(option);
 mbar.add(setting);
 mbar.add(help);
 mbar.add(about);

show();

//ob1.complet_puzzle();

MyWindowAdapter mwa=new MyWindowAdapter();
 addWindowListener(mwa);

}

class Mylogic extends Logic
 {
 void complet_puzzle()
 {
 cp=save();

/*for(int i=0;i<9;i++)
 {
 for(int j=0;j<9;j++)
 System.out.print(cp[i][j]+" ");
 System.out.println();
 }*/
 }
 void puzzle()
 {
 ip=hide();
 /*System.out.print("\n\n\n"+"nhiding puzzle :\n");
 for(int i=0;i<9;i++)
 {
 for(int j=0;j<9;j++)
 System.out.print(ip[i][j]+" ");
 System.out.println();
 }*/
 }

}

class MyWindowAdapter extends WindowAdapter
 {
 public void windowClosing(WindowEvent e)
 {
 System.exit(0);
 }
 }

public void actionPerformed(ActionEvent e)
 {
 for(int i=0;i<9;i++)
 for(int j=0;j<9;j++)
 {
 if(e.getSource()==b[i][j])
 {
 String s=JOptionPane.showInputDialog("enter your number");
 int c=Integer.parseInt(s);
 if(0c)
 {
 b[i][j].setText(s);
 //b[i][j].setBackground(Color.GRAY);
 b[i][j].setFont(new Font("ARIALBD",Font.BOLD,25));
 b[i][j].setForeground(Color.RED);
 }

break;
 }
 }
 }
 void recall()
 {
 GraphicallyRepresentation rs=new GraphicallyRepresentation();
 }

public static void main (String[] args) {
 GraphicallyRepresentation ob=new GraphicallyRepresentation();

}
 }

Source code is here:

How to Run :

To run in NetBeans IDE  just open this project in NetBeans.

To run in Eclipse IDE  just open this project in Eclipse.

To run this project in J-Creator IDE just follow this steps :

  1. Put Logic.java and GraphicallyRepresentation.java in the same folder.
  2. Run GraphicallyRepresentation.java.

Now enjoy it.
Categories: Source Code
  1. myindianweddingbtm116
    May 31, 2012 at 6:14 pm

    I couldn’t Run it Eclipse. It shows me errors on line 5,147,148, 214 in the GraphicallyRepresentation.java. Could you help me out please?

  2. chhaya
    December 19, 2012 at 3:58 pm

    hey Hasib can u plz help me…..
    i need the source code for sudoku game
    in core java…in which one problem of soduko sholud be present.n user will try to solve it…and it will show that , is it right or not…?

    • December 20, 2012 at 4:08 am

      Hi chhaya,
      There is an 2D integer array name cp in GraphicallyRepresentation.java file at line no:25. This array is populated by calling logic.save() method at line no:226. This array contains the answer of the puzzle. So if an user will enter an input your program should compare the input with the answer array cp. For example if an user input in [3][4] block, then the condition is: if(input[3][4] == cp[3][4]) {do something …}. May be you have got your solution.

      • chhaya
        January 11, 2013 at 5:29 pm

        thnx hasib….
        nw i can resolve my prblm………….

  3. Vishwajit
    February 1, 2013 at 1:14 pm

    Hello Hasib,
    I have programmed a Sudoku code by myself for 9*9 Sudoku in Java. In this Sudoku program I am assigning random values to grid[][] array (9*9, 2 dimensional array) then I find the repeat occurrence (first column wise) then I store repeated values in another 2 dimensional array called repeat[][]. Further, I am comparing both array values, if i found same values on same array index it mean the particular value is repeated. Then again, I assign random value to this index and check particular column and row for no any repeat occurrence in particular row and in column. By this way I am trying to solve the Sudoku. But, Its not executing, It stops at particular position (If i remove for(;;)loop in solveGrid() method, it gets executed).
    Please look in my code and help me to solve the Sudoku through my way!

    /* Sudoku.java */

    class Sudoku
    {
    int[] count;
    int[][] grid;
    int[][] repeat;
    int randomNo;
    Sudoku()
    {
    count = new int[9];
    grid = new int[9][9];
    repeat = new int[9][9];
    }
    public void findRepeatedValuesVertically()
    {
    for(int i=0; i<9; i++)
    {
    count = new int[9];
    for(int j=0; j<9; j++)
    {
    switch(grid[j][i])
    {
    case 1:
    count[0] += 1;//System.out.println("Case 1: Count: "+count[0]+" "+grid[j][i]);
    break;
    case 2:
    count[1] += 1;//System.out.println("Case 2: Count: "+count[1]+" "+grid[j][i]);
    break;
    case 3:
    count[2] += 1;//System.out.println("Case 3: Count: "+count[2]+" "+grid[j][i]);
    break;
    case 4:
    count[3] += 1;//System.out.println("Case 4: Count: "+count[3]+" "+grid[j][i]);
    break;
    case 5:
    count[4] += 1;//System.out.println("Case 5: Count: "+count[4]+" "+grid[j][i]);
    break;
    case 6:
    count[5] += 1;//System.out.println("Case 6: Count: "+count[5]+" "+grid[j][i]);
    break;
    case 7:
    count[6] += 1;//System.out.println("Case 7: Count: "+count[6]+" "+grid[j][i]);
    break;
    case 8:
    count[7] += 1;//System.out.println("Case 8: Count: "+count[7]+" "+grid[j][i]);
    break;
    case 9:
    count[8] += 1;//System.out.println("Case 9: Count: "+count[8]+" "+grid[j][i]);
    break;
    default: break;
    }
    for(int r=0; r1)
    {

    storeRepeatedValue(j,i,grid[j][i]);
    count[r]=1;
    }
    }

    }
    }
    System.out.println();
    }
    public void storeRepeatedValue(int j, int i, int r)
    {
    repeat[j][i] = r;
    }
    public void solveHorizontally()
    {
    }
    public void solveGrid()
    {
    for(int i=0; i<grid.length; i++)
    {
    for(int j=0; j1)
    {
    if(checkColumn(i, j, randomNo) && checkRow(i, j, randomNo))
    {
    grid[i][j] = randomNo;
    //System.out.println(“Here, Solving Grid for value: ” + grid[i][j]);
    break;
    }
    }
    }

    }
    }
    }
    public boolean checkColumn(int row, int col, int randomNo)
    {
    for(int i=0; i<9; i++)
    {
    if(grid[row][i] == grid[row][col])
    return false;
    }
    return true;
    }
    public boolean checkRow(int row, int col, int randomNo)
    {
    for(int i=0; i<9; i++)
    {
    if(grid[i][col] == grid[row][col])
    return false;
    }
    return true;
    }
    public void printGrid(int grid[][])
    {
    for(int i=0; i<9; i++)
    {
    System.out.println();
    if(i%3==0)
    System.out.println();
    for(int j=0; j<9; j++)
    {
    if(j%3==0)
    System.out.print(" ");
    System.out.print(grid[i][j]+" ");
    }
    }
    System.out.println();
    }
    public void fillGrid()
    {
    for(int i=0; i<9; i++)
    {
    for(int j = 0; j0)
    {
    grid[i][j] = randomNo;
    break;
    }

    }
    }
    }
    }
    public static void main(String[] args)
    {
    Sudoku sdk = new Sudoku();
    sdk.fillGrid();
    sdk.printGrid(sdk.grid);
    sdk.findRepeatedValuesVertically();
    sdk.printGrid(sdk.repeat);
    sdk.solveGrid();
    sdk.solveHorizontally();
    sdk.printGrid(sdk.grid);
    }
    }

    • February 3, 2013 at 4:35 pm

      According to your logical description i think your logic has high complexity. You can calculate your complexity of this logic. May be you should change your logic.

  4. derrick
    February 12, 2013 at 1:30 pm

    good day hasib…..im kind of having problem in developing soduku game, basically i dnt know where to start, i’ve collected many code from the website but non of the is working>>>im using netbeans and jcreator…can you please humbly send me some code on my email(seanegosassy@gmail.com) plz….i need to know the code because i have an job opportunity on my plate if i manage that..plz

  5. Faz
    February 17, 2013 at 8:52 am

    When i compile GraphicallyRepresentation.java in JCreator LE 5.00.007, there is a caution came out.

    “Note: C:\Java\GraphicallyRepresentation.java uses or overrides a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.”

    I do not have problem with Logic.java. My knowledge about Java not too high and i don’t understand to solve it.

    One more thing, there is some minor problem when i run the project which is Option button, Setting button, Help button is not working.

    Please help me. Thank you brother.

    • February 18, 2013 at 6:45 am

      “C:\Java\GraphicallyRepresentation.java uses or overrides a deprecated API.”
      This problem seems to using of latest JDK version. I developed it long time ago approximately 5 years. So which API or classes I have used that might be deprecated. For that reason that problem can be occurred. This project is full of bugs so please ignore minor problems but it can provide basic development knowledge.

      • Faz
        February 19, 2013 at 7:12 am

        Thank you Hasib for that information. I think it only have problem with Jcreator. When i use Netbeans IDE, all the buttons working perfectly. What I need to change in the source code for Jcreator?

  6. Malay
    February 22, 2013 at 6:59 pm

    hey man thanks for the code but
    what about the reset function it creates new game…
    how to reset the game….

    • February 26, 2013 at 7:05 am

      Sorry to say “Reset” feature is unavailable.

  7. Srinivasan
    March 15, 2013 at 10:21 am

    Nice code

  8. June 7, 2013 at 3:51 pm

    could you send me the code for running this in eclipse? for some reason Mediafire isn’t working for me. My email is imrory@aol.com

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: