ITU PREFACE We are Media Technology and games students at IT University of Copenhagen. This is our first semester four week project on introductory programming written at IT University of Copenhagen, spring semester 2006. The writing and development work performed has been very much interesting, and provided us with a lot of challenge. At some times this challenge felt very interesting and motivating, and at other times we felt that we would have liked wider limits and more time, since the project could have been developed much further. In your hand you have the result of our work and we wish you an interesting and pleasant journey through this semester project report. We would like to thank the following persons for their valuable help during our project work: Associate Professor, Thomas T. Hildebrandt our supervisor at ITU, for guiding our journey with motivation, inspiration and providing helpful ideas and suggestions. We will also take the opportunity to thank our friends and colleagues who contributed directly or indirectly in designing the interface for our project and completing our project. _______________________________________________________________________ Ravikumar Kempaiah Xu Hui ravik@itu.dk Ravikumar & Xu Hui huixu@itu.dk Page 1 of 37 ITU Contents: ABSTRACT-------------------------------------------------------------------------------------------------------------- 3 CHAPTER 1. INTRODUCTION ------------------------------------------------------------------------------------ 3 1.1 PROBLEM DESCRIPTION --------------------------------------------------------------------------------------------- 4 1.2 SUDOKU ---------------------------------------------------------------------------------------------------------------- 4 1.2.1 History ------------------------------------------------------------------------------------------------------- 5 1.2.2 Rules --------------------------------------------------------------------------------------------------------- 6 1.2.3 Difficulty Ratings ------------------------------------------------------------------------------------------- 6 CHAPTER 2. SOFTWARE DESIGN AND IMPLEMENTATION ------------------------------------------ 7 2.1 SOLVER ----------------------------------------------------------------------------------------------------------------- 8 2.1.1 Scanning Techniques--------------------------------------------------------------------------------------- 8 2.1.2 Implementation of Solver --------------------------------------------------------------------------------- 10 2.1.3 IOFile class ------------------------------------------------------------------------------------------------ 12 2.1.4 UML class diagrams and Screen-shots ----------------------------------------------------------------- 13 2.2 GENERATOR --------------------------------------------------------------------------------------------------------- 14 2.3 USER INTERFACE (GUI) ------------------------------------------------------------------------------------------- 19 2.3.1 Swing Components ---------------------------------------------------------------------------------------- 19 2.3.2 Timer Thread ---------------------------------------------------------------------------------------------- 22 2.3.3 Menus ------------------------------------------------------------------------------------------------------- 23 2.3.4 UML Diagram --------------------------------------------------------------------------------------------- 29 2.3.5 User Interaction Design ---------------------------------------------------------------------------------- 30 CHAPTER 3. CONCLUSION -------------------------------------------------------------------------------------- 34 3.1 CONCLUSION -------------------------------------------------------------------------------------------------------- 34 3.2 SUGGESTIONS FOR FEATURE IMPROVEMENT-------------------------------------------------------------------- 34 4. REFERENCES ------------------------------------------------------------------------------------------------------ 35 5. APPENDIX ---------------------------------------------------------------------------------------------------------- 36 5.1 SUDOKU GLOSSARY ------------------------------------------------------------------------------------------------ 36 Ravikumar & Xu Hui Page 2 of 37 ITU Abstract In this report, we present the detailed development and implementation of simple Sudoku game. The Sudoku game consists of graphical user interface, solver and puzzle generator; implemented using java and java swings. The solver and generator is implemented using efficient algorithm. The solver finds the solution to the puzzles generated by the generator as well as to the puzzles entered by the user. Generator creates various number of different Sudoku puzzles. This project gives an insight in to the different aspects of java programming. Chapter 1. Introduction Sudoku, a Japanese number logic puzzle, has become extremely popular through out the world in the last year. These days Sudoku puzzles can be found in newspapers, books, magazines and in many websites. Software programmers now supply the different programs to fulfill the growing demand for unique Sudoku puzzles. The challenge to Sudoku programmers is how to program to create clever puzzles, which is also a popular game for beginners to exercise their programming skills. We became interested in Sudoku while traveling in Copenhagen. We used to see people solving Sudoku puzzles published in local free news papers, Urban and Metro Express. We then discussed with some of our friends to find out what kind puzzle is this and began doing some of the puzzles. Sudoku caught more interest as we started solving more puzzles. The introductory programming course complemented us to program a Sudoku by ourselves. This is not only a fun but also provides great exposure in programming by using different approaches to building and solving Sudoku puzzles. An effort has been made to develop a simple Sudoku game using Java. The main aim of the game is to create new Sudoku puzzles and able to find the solution for those puzzles. The Sudoku game asks the user to load new puzzle to give the user to play and be able to determine the right solution. The new game will be loaded either from a database or from Ravikumar & Xu Hui Page 3 of 37 ITU the one created from the puzzle generator. The user will be able to keep track of the time taken to complete a particular puzzle. It is possible to store the unfinished puzzles as a text files and retrieve back whenever needed. The Interface is designed to best suit the user needs involving users in the design process. This report is organized as follows. In the following section of this report the basic problem formulation is presented, followed by the brief introduction of the Sudoku game. In section 2 the software design is presented, and how the whole project is subdivided into different parts followed by the detailed explanation of individual parts and approach used. The final conclusions with suggestions for future work are summarized in the section 3. Appendix contains some online Sudoku links and definitions of different Sudoku terms. The accompanied CD contains the code written in Java, Java documentation created using Bluej and .jar file of the project. 1.1 Problem Description This 4 weeks project building on basic programming would typically aim at a java implementation that supports single player, a simple GUI as a stand alone function using java swings, and support for the basic rule set of Sudoku and with some extra features. Project includes generators and solvers for the one or more of the three Sudoku difficulty levels. Depending on the availability of time and expertise resources the game could be extended to include more supportive features. The main objective of this project would be to gain an understanding of game programming basics and get hands on experience in writing a larger computer program. 1.2 Sudoku Sudoku is the Japanese abbreviation of a phrase meaning the digits must remain single, also known as Number Place, where Su means number, doku which translates as single or bachelor. Sudoku is not a mathematical or arithmetical puzzle. It works just as well if Ravikumar & Xu Hui Page 4 of 37 ITU the numbers are substituted with letters or some other symbols, but numbers work best. The aim of the puzzle is to enter a numerical digit from 1 through 9 in each cell of a 9×9 grid made up of 3×3 subsquares or subgrids, starting with various digits given in some cells; each row, column, and subsquares region must contain each of the numbers 1 to 9 exactly once. Throughout this document we refer to the whole puzzle as the grid/game board, a 3x3 subgrid as a block and the individual grids that contains the number as a cell. Figure 1.1: Sample Sudoku game 1.2.1 History The first Sudoku puzzle was created in 1979. In New York City the Sudoku puzzle appear first, which was published by the specialist puzzle publisher Dell Magazines in their magazine Dell Pencil Puzzles and word Games. First it was printed under the name “number place”. Howard Garns, a retired architect and freelance puzzle constructor designed this first puzzle. This mathematical construction is inspired by the Latin square, invention of Leonhard Euler. Later the puzzle was introduced in Japan by Nikoli during 1984 as "Suji wa dokushin ni kagiru", which can be translated as "the numbers must be single" or "the numbers must occur only once", later it abbreviated as Sudoku. Ravikumar & Xu Hui Page 5 of 37 The ITU Sudoku puzzle can use symbols or colors instead of numerals. trademark owned by Nikoli. Sudoku is still a The the game's popularity really took off in 2005; it can now be found in many newspapers and magazines around the world. 1.2.2 Rules Solving a Sudoku puzzle can be rather tricky, but the rules of the game are quite simple. Solving a sudoku puzzle does not require knowledge of mathematics; simple logic suffices. The objective of sudoku is to enter a digit from 1 through 9 in each cell, in such a way that: Each horizontal row contains each digit exactly once Each vertical column contains each digit exactly once Each subgrid or region contains each digit exactly once In each sudoku puzzle, several digits will be already given, these may not be changed. The user’s job is to fill the remaining cells with the right digits considering the aboved metioned three constraints. 1.2.3 Difficulty Ratings Usually Sudoku puzzles published in newspapers are ranked in terms of different difficult levels; such as easy, medium and hard. The number of given hint digits in the puzzle is nothing to do with the difficulty of a puzzle. Sometimes a puzzle with minimum number of given digits may be very easy to solve, and a puzzle with more number of givens can still be difficult to solve. So the difficulty is based on the positioning of the number in the grids rather than the quantity of numbers given. The difficulty levels are estimated by the computer solvers depending on the number of different techniques or rules applied to find the right solution. A good Sudoku puzzle has only one solution but sometimes it’s also possible to have more than one solution1. 1 http://en.wikipedia.org/wiki/Sudoku Ravikumar & Xu Hui Page 6 of 37 ITU Chapter 2. Software Design and Implementation The Sudoku game is divided into 4 different components: such as the Sudoku game interface, the Solver, the generator, and the puzzle database. Sudoku game interface: This part of the Sudoku game comprises the stand-alone user interface implemented using java swings. It allows the user to select and solve new puzzle by only using mouse, it also allows the user to enter their own puzzle and find the right solution for the puzzle. The interface is provided with simple menu bar and time label to show the time taken to solve the puzzle. The interface is well integrated with solver, generator, database and efficiently handling the various events created by the different java swing components. Solver: This part of the Sudoku game system comprises the logic and rules of the game thereby able to decide the possible next steps to find the right values to the individual cells. The solver uses the scanning technique to find the best solution; the final answer will be the combined result of different rules. The solver can only handling with simple Sudoku puzzles. The solver also checks different conditions while creating new puzzle. Generator: This part of the Sudoku game system comprises the logic system to create new random puzzles. The system first creates the full board array with different permutations; the elements from the cells are then taken out randomly thereby creating a new puzzle. Then new puzzle is checked for solution against the solver by applying different rules. The generator is also being able to decide the difficulty ratings of the puzzle depending on the rules applied to obtain the final solution. Ravikumar & Xu Hui Page 7 of 37 ITU Puzzle Database: This part of the system comprises the collection of puzzles obtained from different sources in a text file. The system also allows the user to store and retrieve their unfinished puzzles. The block diagram of Sudoku game is shown in the figure 2. User Interface (GUI) Sudoku Game Puzzle Database Solver Creator Figure 2.1: Block diagram of Sudoku game 2.1 Solver This class mainly focuses on the way to find out the solution to the different Sudoku puzzles. Normally, the strategy of solving a Sudoku puzzle involves two parts: scanning and analyzing.2 In this work we just concentrate on scanning techniques. 2.1.1 Scanning Techniques The easiest way to start solving a Sudoku puzzle is by scanning all the rows, columns and each block area, eliminating all the impossible numbers and finding situations where only have one single number that can fit into that particular cell. The scanning technique is basic and efficient to solve normal puzzles all the way to the end. The scanning technique is also very useful for difficult puzzles up to the point where no further progress can be made and more advanced solving techniques are required. 2 http://en.wikipedia.org/wiki/Sudoku Ravikumar & Xu Hui Page 8 of 37 ITU a. Scanning in one direction In this example, let’s focus on block 2, which like any other block in Sudoku must contain the element 9. Looking at block 1 and block 3, we can see there are already 9s in Row 2 and in Row 3, which excludes the two bottom rows of block 2 from having 9. So the number 9 can only put in the cell e1. Figure 2.1.1: Illustration of scanning in 1 direction b. Scanning in two directions Using the same principle, we can only put the number 1 in the cell i3. Figure 2.1.2: Illustration of scanning in 2 directions c. Searching for Single Candidates Using the same principle, we can easily get all the single candidates by eliminating all the repeating numbers from rows, columns and blocks, step by step to find the final answer. Figure 2.1.3: Illustration of searching for single candidates. Ravikumar & Xu Hui Page 9 of 37 ITU In this case, we just use the same way to reduce the possible values (1-9) from each cell based on all the requirements. So it can only solve some simple puzzles. (Based on “Sudoku Players' Forums-Sudoku test list” 3 this Solver can only solve “singles only” puzzle such as “full house singles, hidden singles, and naked single4” kinds of puzzles) 2.1.2 Implementation of Solver Figure 2.1.4: UML Class Diagram (Solver Class) calcPossibilities(): First, declare “p” as a 3D array. This method calculates all the possibilities (number 1-9) of all the cells in a puzzle and stores it in the array p. for (int i = 0; i<arr.length; i++) { 3 4 http://www.sudoku.com/forums/viewtopic.php?t=3834 Glossary part of appendix Ravikumar & Xu Hui Page 10 of 37 ITU for (int j = 0; j<arr[i].length; j++) { // call the method "find" to get an array with all the possible numbers and put it to the 3D array p. p[i][j] = find(i, j); } } Then find method checks all the possible numbers in a cell, and returns the values array to the array p: if (!check(i, row, col) && arr[row][col] == 0) result[ctr++] = i; Then using check method to make sure which number is qualified. public static boolean check(int n, int row, int col) { if (checkRow(n, row) || checkCol(n, col)) return true; if (checkBox(n, row, col)) return true; return false; } Especially, when checking possible number in each block, make sure each time check method start from the beginning of each block and go through all the cells of the block. The method “resetBox (int, int)” is responsible for that function. detect(): After finishing with all the possibilities of each cell, start detecting is there any cell only contain one possible value (except zero) and put this value back to the puzzle array. Then using calcPossibilities method finds the possibilities for each cell again until all cells contain one correct value. If some of the cells not get qualified value, after several loops, then only unfinished array returns back as the final answer array. detect() { Check for each row, each column and each block for only occurrence of an element. If there is only one number left, then put this number back to the puzzle array. } Ravikumar & Xu Hui Page 11 of 37 ITU lastDigitsCell(): This is the one example how only one possibility in a cell is find out. o if only one number in a cell, put it back to the final array. lastDigitsCell() { ……………………………………. ……………………….. if (p[row][col][1] == 0 && p[row][col][0] != 0) put(row, col, p[row][col][0]); } put(int,int,int): Put the value in the array, and do the calcPossibilities method again to get the new possibility combinations. 2.1.3 IOFile class IOFile -datafile : String IOFile(String) +readFile(): void +writeFile(int[][]): void +pirntArray(int[][]): void +creatFile(): void +outputFile(): void Figure 2.1.5: UML Class Diagram (IOFile Class) In IOFile class, we put all the methods, which concerning about I/O operations under this class. We can use relative method to read an array from a text file and put an array into a text file. Also we can print an array in the screen with regular model. Combining with GUI, we can save a text file to the particular path direction. Iimportant methods are explained as follows. Ravikumar & Xu Hui Page 12 of 37 ITU readFile(): Read the elements from an array text file with exception handing (I/O exceptions). And keep it to the array. writeFile(int[][]) : Write the array numbers in a text file with exception handing. printArray(int[][]): Print an array on the Screen with regular model. Figure2.1.6: Print pattern 2.1.4 UML class diagrams and Screen-shots Figure 2.1.7: BlueJ diagram of solver Ravikumar & Xu Hui Page 13 of 37 ITU Figure 2.1.8: Snap shots a. basic output of the solver b. unsolvable problem from the solver 2.2 Generator The Generator is for creating qualified Sudoku arrays. Combining with the Solver, we could start to make our own Sudoku puzzles. The main technique in this algorithm is using permutations, based on one qualified pattern to enumerate qualified Sudoku arrays. Here, we only use Band permutations (3! times variations), Row permutations within a band (3! ³ times variations), Stack permutations (3! times variations), and Column permutations within a stack (3! ³ times variations) to get the arrays. Finally, put the qualified Sudoku array into a text file. (Ex: 3! =3*2*1= 6 ---123,132,213,231,312,321). Figure 2.2.1 illustrates the different types of permutations used in this work. Ravikumar & Xu Hui Page 14 of 37 ITU Figure2.2.1: Different types of permutations 2.2.1 The RandomArray class Figure 2.2.2: Random array class diagram Ravikumar & Xu Hui Page 15 of 37 ITU getRandomArray(): This method is using one qualified sudoku solution array as a pattern. By permuting different band, row with a band, stack, and column with a stack generate different qualified arrays. getRandomArray( ){ Set the number of loops to make major change between old and new array. Under these loops o Get each stack values using getBigColumn method. o Get each band values using getBigRow method. o Put the band values back randomly using setBigRow method. o Put the stach values back randomly using setBigColumn method. o Randomly choose one stack and keep column values in separate arrays within the stack using getSmallColumn method. o Put separated arrays back to the stack randomly. o Repeat the above steps to get the permutated row. } setTest() : Get Random array for changing each row/column within a band or stack. setBigRow() : Band permutation---Get the three bands values first, after doing random permutation, put the bands back to the array. setBigRow() { Get the random array using setTest method. Get the number from the random array. Do the band permutation according to the order of the number obtained. Put the value back to the band. } Ravikumar & Xu Hui Page 16 of 37 ITU setSmallRow(): Using the same way as doing row permutations within a band, then randomly put each row array back in to the band. generateArray(int[][]): After we got the qualified solution array, use random way to eliminate some elements from the array to create new puzzle array. Then use Solver method check if this puzzle array is qualified. o Get an unrepeated number array. int a[] = random(test); o Here we can set a different number for getting more or less zeros in the array. It is one kind way to set a difficulty. int length=rd.nextInt(2)+5; o Keep the different random array. int[] tmp=new int[length]; o Get the numbers array which needs to be eliminated from the random array. for(int i = 0;i <length ;i++) tmp[i]=a[i]; o set zero into the random cells, making a new puzzle array. array[m][tmp[n]]=0; random(int[]) : Get an unrepeated random array. o First get a random number. index = Math.abs(rd.nextInt()) % num; o Then interchanging the values between different cells. tmp[i] = src[index]; src[index] = src[num - 1]; o Then reduce the array size and repeat the above step. num--; Ravikumar & Xu Hui Page 17 of 37 ITU 2.2.1 UML class diagrams and Screen-shots Figure2.2.3: BlueJ diagram of Generator Figure2.2.4: Snap shot of the basic output of the Generator Ravikumar & Xu Hui Page 18 of 37 ITU 2.3 User Interface (GUI) 2.3.1 Swing Components The Sudoku game interface is designed with Java swing components. The block diagram of the various components used is shown below. User can interact with the various swing components only using mouse. The new game is loaded by selecting new game menu item in the menu bar. The solution elements are placed on the different cells by selecting the respective radio button and then by clicking on the right cell (button). This interface is designed according to user requirements involving the users in the interface design process using user interaction design technique, which is explained later in this section. Figure2.3.1: Block diagram of swing components used A simple menu bar with different menu items is created and added to the frame. 3 different panels are added to the frame applying borderlayout layout manager. A time label and a submit button is created and added to the first panel. Whenever user starts solving the puzzle the time label updates and shows the time taken to solve the puzzle. 9 Radio buttons are created to add to the Radio button group, this group is then added to the second panel. Action listener is added to each radio button. rdpanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Select the number to fill in"), BorderFactory.createEmptyBorder(3,3,3,3))); Ravikumar & Xu Hui Page 19 of 37 ITU A compound border is set around these radio buttons, which includes a titled border with information to the user and an empty border using the above lines of code. Arrays of 81 buttons are added to the 3rd panel. Each button is added with action listeners using the following code. for(int i=0;i<81;i++) { btn[i]=new JButton(" "); btn[i].setFocusPainted(false); btn[i].setForeground(Color.BLACK); paneone.add(btn[i]); btn[i].addActionListener(new BtnEvent(btn[i],i, tm)); } Blocks are made by drawing line between the buttons, this is done using graphics. Second panel consists of 9 radio buttons named 0-9. Puzzler needs to first select the respective radio button in order to place the right digit on the respective cell. The radio button selection is assigned to the variable and displayed on the button where user clicks. If user tries to place the number on a cell without selecting a radio button, a dialog message is displayed informing the user to first select a radio button. if (RadioListener.selt==null) { // if radio button is not selected JOptionPane.showMessageDialog(null, "you need to select a radio button to place the right number"); } ………………. ……………….. JButton bton =(JButton)eBut.getSource(); // Typecast to JButton type bton.setText(RadioListener.selt); // set the selection no.on button Puzzler can find the solution to their own problem by entering a problem on the board and then by pressing the submit button. The digits in the each cell is read and stored into an array and solution to this problem is calculated calling respective solver methods. Submit button is also used to check a completed game or unfinished puzzle to verify for the correct solution. Ravikumar & Xu Hui Page 20 of 37 ITU if(BtnPanel.btn[m].getText() != null && !BtnPanel.btn[m].getText().trim().equals("") ) { temp = Integer.parseInt(BtnPanel.btn[m].getText()); puzzle[k][l]=temp; // store the number on the cell to an array } // end of if else { puzzle[k][l]=0; } // if there is no entry on the cell store zero // end of else Submit Button: Submit button is placed next to the time label on the first panel. When the puzzle is solved it can be verified against the right solution by pressing the submit button. Even solution to a new puzzle or for an unfinished puzzle can be found by using this button. The event generated when the submit button is pressed is handled as follows. If the event generated from submit button, stop the timer and display the total time taken. Call the submitAction method submitAction(){ If the entries are only from the user inputs (No new game, no open file) Read the elements from each cell and store it in an array. Create solver class object to find the solution for that array. If solution finds the solution then load the solution on to the game board, else show the error message. If the new game loaded is created by the generator o Read the elements from each cell. If there is no entry on the cell, store the element as zero. Otherwise store the entered element on to the right index of array. Check for the wrong entries made. Find the solution to the puzzle calling solver methods. If the solution is correct, display the message indicating whether the user solved the puzzle. Ravikumar & Xu Hui Page 21 of 37 ITU If the solution is wrong, find the right solution using the original puzzle opened (say its gameArray) and shows the respective message. If the game opened is from the text file, just assign the opened puzzle to game array. Then repeat the above steps for the new game condition. } 2.3.2 Timer Thread Whenever a new game is started, a timer also starts keeping track of the time taken to solve that puzzle. Since both timer and game should run simultaneously, we separate the timer as independently running subtask (thread). Each thread runs by itself and has the CPU to it and is a single sequential flow of control within a process. A single process can thus have multiple concurrently executing threads5. Timer thread is implemented by inheriting from class Thread, which has all the wiring necessary to create and run threads. Public class Timer extends Thread { Public void run () { // important method for thread which must //override to make the thread do our task while(true) { // keep track of time for each second } } } While loop in the run() method continues until the thread is no longer necessary. So in order to stop timer, a condition is established on which to break out of this loop otherwise run() is cast in the form of an infinite loop. if(ticktime == false)return; // comes out of the loop Timer is started only when new game is loaded and as soon as user starts placing the numbers in a cell. The timer stops when the submit button is pressed or a new game is loaded in between or when the game is closed by terminating the thread. For each new game a new timer thread starts. 5 Thinking in Java, Bruce Eckel, prentice hall...ISBN: 0-13-027363-5 Ravikumar & Xu Hui Page 22 of 37 ITU if(firstclick == true && RadioListener.selt!=null && BtnPanel.newGame == true ){ // check for first click, radio button selection n new game ………………………………………………… Timer.ticktime = true; Timer timer = new Timer(); timer.start(); // start the timer }// end of if 2.3.3 Menus The different menus used and how they are arranged is shown in the following block diagram (Figure 2.3.2). Some of the menus are not implemented due to time restrictions, are shown gray in color. Figure2.3.2: Menu items design Menus are created in SimpleMenus class which is inheriting from the JMenuBar class. Menu items are then declared and assigned to different string variables. String editItems[] = new String [] {"Undo","Redo","Clear"}; char editShortcuts[] = {'U','R','l'}; // shortcuts char editAccelerators[] = {'Z','R','\u0000'}; // control keys Ravikumar & Xu Hui Page 23 of 37 ITU File, Edit and Help menus are created of type JMenu, respective menu items are assembled and action listener is added to them. for (int i=0;i<fileItems.length;i++) { JMenuItem item = new JMenuItem(fileItems[i], fileShortcuts[i]); item.addActionListener(printListener); fileMenu.add(item); } // end of for loop New game: This menu item allows a user to load new game either from the database or from generator. Whenever this menu is selected a new puzzle is created invoking the generator methods and loaded on to the game board, which is implemented in the Newgame method. Newgame () { Create an object of RandomArray class by passing the pre-defined array. Instantiate getRandomArray method and store the result in an array (solutionArray) of type int. Instantiate generateArray method by passing solutionArray as an argument to generate a new game and store it in the array called gameArray. Now check whether newly generated puzzle (gameArray) has the solution or not o Create Solver class object. o Instantiate calcPossibilities and detect methods. If the solver unable to find the solution for the new puzzle, repeat the above steps until a solvable puzzle is generated. Load the solvable puzzle on to the game board. } Open: This menu item allows a user to open the puzzles which are pre-saved as text files from a particular location in the system. Ravikumar & Xu Hui Page 24 of 37 ITU Open () { Create an object of type JFileChooser, set file selection mode. Add a file filter to allow user to open only text files. o File filter class contains accept method which checks whether the given file is accepted by the filter or not. And getDescription method, which gives the description of this filter. public boolean accept(File file) { String filename = file.getName(); return filename.endsWith(".txt"); } public String getDescription() { return "*.text files"; } If cancel button is pressed on the open dialog, return Get the selected file name Invoke readFile method to read the contents from the file. Load the file contents on to the game board. } Save: This menu item allows a user to save an unfinished game or a totally new game as text file, which can be further retrieved whenever needed. Solve () { Check for valid file name calling testSave method. If the file name is valid call outputToFile method to read the elements from the game board. Check for elements on the board and then write it to the file in a specified format. } testSave() { Create an object of type JFileChooser, set file selection mode and show the save dialog. Add a file filter to allow user to save files only in text formats. File filter is created as explained before. Ravikumar & Xu Hui Page 25 of 37 ITU If cancel button is pressed return. Get the entered file name. Check for valid file name. Write the filename. } createFile () { Read the elements which are to be saved from the game board, type cast to integer type and save it in an array. } outputToFile () { Call the createFile method to read the elements form the board. Check whether the array is empty of not Print the elements into a file in a specified format } Own puzzle: This menu item allows a user to enter their own puzzle to find the solution by clearing all the cells on the game board. Clear () { Clear all the elements on the game board by setting empty text on the buttons. Enable the buttons in order to accept new entries. Set the condition variable for the timer to stop. } Exit: Exits the game board. Quit () { System.exit (0); } Ravikumar & Xu Hui Page 26 of 37 ITU Rules: Rules menu item is a part of help menu. User can find out about the rules of the game by selecting this menu. First an image file is created showing the information as shown in Figure 2.3.3. The information is shown in a separate window, closing this window won’t affect the main window. This is implemented as a multiple frame. Whenever the menu is selected, the frame is made visible. Figure 2.3.3: Rules image This is done using the following code If (Rules menu is selected) { boolean rules = true; // to make frame visible String rls = "RULES"; // set the title of the frame new SudokuFrame(rules, rls); } Ravikumar & Xu Hui Page 27 of 37 ITU SudokuFrame(boolean rules, String selTitle) { Create a JFrame object Set the title of the frame as received string parameter Place the respective .gif image on the content pane. helpFrame.getContentPane().add(new rules()); Set the visible condition based on the boolean parameter received. } Setting the image icon on the panel is as follows rules() { ImageIcon rls = new ImageIcon("pics/Rules.gif"); add(new JLabel(rls)); // set the window size according to image size setPreferredSize(new imension(rls.getIconWidth(),rls.getIconHeight())); } About: This menu item is also a part of Help menu. This gives the information about the user interface and how to use it. This information is shown in a separate frame using the image shown in the Figure 2.3.4, implemented similar to Rules menu. It works just by changing the title of the frame and image name. Figure 2.3.4: Image showing the different components of GUI Ravikumar & Xu Hui Page 28 of 37 ITU 2.3.4 UML Diagram Different classes used to implement whole GUI can be seen in the Figure 2.3.5. This is the diagram generated by bluej. Figure2.3.5: BlueJ diagram of GUI Different classes: SudokuFrame: Creates multiple frames (main frame and frame for help menu) and adds different components into it. This also contains main method. SimpleMenus: Defines different menus and menu items with events handling. Contains open, save, testSave and quit methods. This also contains the MyFilter subclass, which defines the type of file filter. rules: Class to create different image icons for help menu. BtnPanel: Defines different panels needed for the game board, draws lines to distinguish different blocks using paint method. This class also contains Newgame and clear methods. BtnEvent: Event handling for buttons. Contains RadioListener subclass to handle events for radio buttons and ButtonListener subclass to handle event for submit button. loadSoln and submitAction methods are defined inside the ButtonListener subclass. Ravikumar & Xu Hui Page 29 of 37 ITU Timer: Extends thread and defines the timer logic inside the run method. IOFile: Different input output to the file is defined here. Contains readFile, writeFile, outputToFile and createFile methods. Snap shots: Snap shots of the GUI are presented in the figure 2.3.6. Figure2.3.6: Snap shot of the developed GUI 1. When started, 2. While solving puzzle 2.3.5 User Interaction Design User Interaction design is a process where users are placed at the center of the design process; it is a process that focuses on different factors such as perception, learning, problem solving etc., as people come into play during peoples interactions with things. As mentioned earlier the user interaction design process is employed in designing the Sudoku game interface. The whole design process is iterative process can be explained as a sequence of phases, the two iteration cycle is shown in the following diagram. The cycle implies that one phase strictly follows the other with interaction between the phases. The main idea of using this process is to make sure how relevance does the functions, information match what the user actually needs? Ravikumar & Xu Hui Page 30 of 37 ITU The cycle starts with analyzing the task and the users and specifying the requirements. The next phase is to establish the design based on the data collected during the analysis phase. Basic design is then verified against the user requirements and design is modified according to their needs. Next phase is to implement the design and preparing initial prototype. Once the prototype is done, it’s again verified with the users and final modification is done. Each user event is taken as drivers for the design process. Figure: User Interaction Process6 (Iterative process with user events as drivers) Here an effort has been made to follow the above mentioned method to design Sudoku game interface. Even though methodology is not followed step by step an overall approach is used to involve users in the design process. As shown in the above diagram the two cycle iterative process is followed. 6 Mads Clausen Institute for Product Innovation, University of Southern Denmark Ravikumar & Xu Hui Page 31 of 37 ITU Users: The people who regularly solve Sudoku puzzles are considered. In this case our colleagues and friends in the university, classmates at Danish language school and people who live together with us in kollegium. Environment: University campus, Danish language school (interaction during breaks in the resting area) and the common kitchen at kollegium. Time span: Out of 4 week schedule, first user interaction had done during first week and the second user interaction during the 4th week. The basic requirement was to create a simple Sudoku game, where user can able to get different puzzles, able to check and get solution for those puzzles, able to get solution for their own puzzles. Considering this requirement a simple 9x9 grid layout has been made and discussed with the users to find out what exactly they expect the user interface to be. Some of the questions which are raised during the discussion are. Layout Interaction either from mouse or keyboard Type of menus Resizable window or not Kind of help/support Timer Ravikumar & Xu Hui Page 32 of 37 ITU The interface presented in the previous section is the result of these inputs obtained from the users. Considering our skills and time constraints, all the feasible suggestions are implemented. During the 2nd and 3rd week implementation is done and a working prototype is created. Now the second interaction loop is performed by asking the users to use the Sudoku game developed and to check whether the developed game suits according to their needs and suggestions. In this interaction lot of suggestions are obtained for improvement. Due to time restriction only few minor changes were made to the original design and remaining suggestions are presented in the next section as suggestions for future work. Ravikumar & Xu Hui Page 33 of 37 ITU Chapter 3. Conclusion 3.1 Conclusion In this project we have carried out the design and implementation of the Sudoku game using java. In general, we have easily able to create and solve the different Sudoku puzzles. The user interface is developed according to the user requirements involving the users in the design process. Overall learning process gave an insight into game programming. Most of the concepts learnt during the Introductory programming course are been implemented. Satisfactory results are obtained when tested against the users to play this game. With the above considerations, in future the solver can be improved to solve all difficulty ratings and more user friendly features can be added. 3.2 Suggestions for feature improvement These are some of the main suggestions given by the user for improvement. Implementing the undeveloped menus Able to show the errors made by the user Able to select different difficulty levels Instant help by giving hints and users progress while playing. Extra features like number of elements remaining, music at different stages, different skin. Score system based on time and accuracy, and database to keep track of top ten scorers. Ravikumar & Xu Hui Page 34 of 37 ITU 4. References 1. Java software solutions: foundations of program design, William Loftus and John Lewis(L&L) ISBN: 0321312465 2. Thinking in Java, Bruce Eckel, prentice hall. ISBN: 0-13-027363-5 3. http://en.wikipedia.org/wiki/Sudoku 4. User centered design department, Mads Clausen Institute for Product Innovation, University of Southern Denmark. 5. http://java.sun.com/docs/books/tutorial/uiswing/ 6. http://www.sudocue.net/glossary.php Ravikumar & Xu Hui Page 35 of 37 ITU 5. Appendix 5.1 Sudoku Glossary7 This glossary can be used together with the Solving Guide. It contains an alphabetical list of Sudoku terms and solving techniques, with a link to the section of the manual that explains the concept. While the solving guide is being completed, so will this glossary. Block Alias used for Box Box 9 cells in a 3x3 square formation Buddy Alias used for Peer Candidate Digit that can be placed in an empty cell Cell Square in a Sudoku puzzle that can hold a digit Clues Alias used for Givens Column 9 cells in a single vertical line Cross-Hatching Technique that helps locate hidden singles Hatching Alias used for Cross-Hatching Constraint Alias used for House Digit A digit between 1 and 9, to be placed in the cells Disjoint Subset Alias used for Naked Subset Eliminate Remove a candidate using logic Forced Digit Alias used for Hidden Single Hidden Single Last candidate for a digit in a house. Basic solving technique Givens Cells containing a digit at the start of the puzzle Grid 81 cells organized in 9 rows and 9 columns Group Alias used for House Last Digit Final digit that completes a house. Basic solving technique 7 http://www.sudocue.net/glossary.php Ravikumar & Xu Hui Page 36 of 37 ITU Line-Box Interactions Alias used for Locked Candidates Locked Candidates Candidates locked in a line-box intersection. Medium solving technique Minigrid Alias used for Box Naked Pair 2 cells with 2 candidates in a house. Naked Subset of size 2 Naked Quad 4 cells with 4 candidates in a house. Naked Subset of size 4 Naked Single Single candidate in a cell. Basic solving technique Naked Subset N cells with N candidates in a house. Medium solving technique Naked Triple 3 cells with 3 candidates in a house. Naked Subset of size 3 Number Alias used for Digit Peer Cells in the same house. Each cell has 20 peers Pencilmark Visual representation of a candidate Pinned Digit Alias used for Naked Single Pointing Pairs Alias used for Locked Candidates Region Alias used for Box Row 9 cells in a single horizontal line Set Alias used for House Single Candidate Alias used for Naked Single Symbol Alias used for Digit Some Sudoku Links http://en.wikipedia.org/wiki/Sudoku http://www.sudoku.com/ http://sudoku.sourceforge.net/ http://www.scanraid.com/Sudoku.htm http://www.conceptispuzzles.com/products/sudoku/rules.htm http://www.setbb.com/phpbb/index.php?mforum=sudoku http://java.com/en/games/desktop/sudoku.jsp Ravikumar & Xu Hui Page 37 of 37