PLEASE HELP with this program. I am in computer science one so nothing thats to
ID: 3556151 • Letter: P
Question
PLEASE HELP with this program. I am in computer science one so nothing thats to complexed is required. Correct answer will get five stars and I will repost it so you get double the points.
Please I need it by Friday. Thanks
This program will give you more experience creating GUI applications, and provide a some practice for
working with 2D arrays. In the assignment, you will create a GUI version of the game Mini Sudoku.
Mini Sudoku is a game played on a 6 x 6 grid of squares. At the beginning of the game, some of the
squares are filled in with numbers, and the rest are blank. The object of the game is to place the
numbers 1 to 6 on the board such that the following conditions hold
Each row has the numbers 1 to 6
Each column has the numbers 1 to 6
Each group of 2 rows by 3 columns also has the numbers 1 to 6.
For example, a beginning configuration and solution to a Mini Sudoku board is as follows:
Beginning configuration
4 6 - 3 2 5
2 - 3 - - 6
6 2 4 5 - 1
3 - 5 4 - -
1 4 2 6 - -
- 3 - 2 1 -
Solution
4 6 1 3 2 5
2 5 3 1 4 6
6 2 4 5 3 1
3 1 5 4 6 2
1 4 2 6 5 3
5 3 6 2 1 4
Your goal is to write a program that will allow the user to try and solve mini-sudoku puzzles where the
initial configuration is specified in a text file.
Directions
1. Write an application using Swing that will allow a player to play mini-sudoku.
2. Your program must present the players with a graphical representation of the board of some
kind, perhaps using JTextFields.
3. Your program must gracefully handle the case when a player tries to add a non-number to a
square, or add a number that violates the Sudoku rules. It should prevent illegal moves without
crashing.
4. When the game is over, the game must indicate that the game has been won.
5. The program must provide a menu to allow the user to load a file with an initial game
configuration.
6. The program must provide a menu option to quit the program.
Explanation / Answer
DO rate if satified. checkout http://pastebin.com/czGQxcXQ for code with indentation.
create a SudokuConfig.txt with ur beginning configuratio or else load manually
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
@SuppressWarnings("serial")
public class Sudoku extends JFrame implements ActionListener, FocusListener {
private JPanel contentPane;
/**
* All 36 TextField are stored in this
*/
private JTextField tf[][];
/**
* The Integer values of the textFields are stored in this. This is for easy access rather than
* using Integer.parseInt(tf[][].getText()).
* 1-6 indicates the textField values. 0 - indicates empty textField.
*/
private int curValues[][];
/**
* Show the status of the last action.
*/
JLabel statusLabel;
private JMenuItem menuQuit;
private JMenuItem menuLoadFile;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
Sudoku frame = new Sudoku();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame contents all add the action listeners to the components
*/
public Sudoku() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 400, 400);
setResizable(false);
setTitle("Mini Sudoku");
/*
* Menu bar and Stuff
*/
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
menuLoadFile = new JMenuItem("Load File");
menuLoadFile.addActionListener(this);
fileMenu.add(menuLoadFile);
menuQuit = new JMenuItem("Quit");
menuQuit.addActionListener(this);
fileMenu.add(menuQuit);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(panel, BorderLayout.NORTH);
statusLabel = new JLabel("Status :");
panel.add(statusLabel);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.CENTER);
panel_1.setLayout(new GridLayout(6, 6, 2, 2));
/*
* Generate and add all the text fields
*/
tf = new JTextField[6][6];
for (int i = 0; i < 6; i++)
for (int j = 0; j < 6; j++) {
JTextField jtf = new javax.swing.JTextField(3);
jtf.setHorizontalAlignment(SwingConstants.CENTER);
jtf.addActionListener(this);
jtf.addFocusListener(this);
panel_1.add(jtf);
tf[i][j] = jtf;
}
curValues = new int[6][6];
//Load an initial config
loadFile( new java.io.File(".\SudokuConfig.txt"));
}
@Override
/*
* This handles all events from textFields and menu components. Loading a file too.
* if event from Loadfile menu - then load a file config
* event form Quit menu - then quit
* rest of events come from text fields only. so take corresponding action
*/
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if (arg0.getSource() == menuLoadFile) {
/*
* Create a file chooser and load the corresponding file
*/
JFileChooser jf = new javax.swing.JFileChooser();
if (jf.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
loadFile( jf.getSelectedFile() );
} else if (arg0.getSource() == menuQuit)
System.exit(0);
else // rest of actions come form text fields only
takeAction((JTextField) arg0.getSource());
}
/*
* focusLost lisenter callback. This is for textfields only
*/
@Override
public void focusLost(FocusEvent e) {
takeAction((JTextField) e.getSource());
}
/**
* Load a sudoku puzzle from the file
* @param f File to be loaded
*/
private void loadFile(File f){
Scanner sc;
try {
sc = new Scanner(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
this.setError("File " + f.toString() + " not found.");
return;
}
for (int i = 0; i < 6; i++)
for (int j = 0; j < 6; j++) {
// Reset cell value
curValues[i][j] = 0;
tf[i][j].setBackground(Color.WHITE);
tf[i][j].setText("");
tf[i][j].setEnabled(true);
/*
* Read and load the value if it is valid
* '-' indicates empty field
*/
if (sc.hasNext()) {
String val = sc.next();
if (val.equals("-"))
curValues[i][j] = 0;
else {
int value = 0;
try {
value = Integer.parseInt(val);
if (value < 1 || value > 6) {
setError("Invalid value reading file.");
sc.close();
return;
}
} catch (NumberFormatException ne) {
setError("Invalid value reading file.");
sc.close();
return;
}
curValues[i][j] = value;
tf[i][j].setBackground(Color.YELLOW);
tf[i][j].setText(Integer.toString(value));
tf[i][j].setEnabled(false);
}
}
}
statusLabel.setText("Status: File " + f.toString() + " successfully Loaded");
sc.close();
}
/**
* This function is used to check if an correct value is inputted in text field and if the
* sudoku is solved. This is called when 'enter' is pressed in text field or focus is lost to
* another texfield.
*
* If text is entered or out of range values are entered then status message is updated
* accordingly and value is reset to previous value.
* If a value that violates the sudoku is entered then message is displayed but value is not
* reset to previous value
*
* @param jtf The Textfield on which event took place.
*/
private void takeAction(JTextField jtf) {
String text = jtf.getText();
if (text.equals("")) // if no text is entered then return.
return;
//Initialize statusLabel
statusLabel.setForeground(Color.BLACK);
statusLabel.setText("Status: OK");
//Get the x, y position of the textfield
int ci, cj = 0;
outerloop: for (ci = 0; ci < 6; ci++)
for (cj = 0; cj < 6; cj++)
if (jtf == tf[ci][cj])
break outerloop;
//Read the value entered in textbox
int value = 0;
//Invalid text checking
try {
value = Integer.parseInt(text);
} catch (NumberFormatException ne) {
setError("Invalid value", ci, cj, "Value restored");
//Restore the TextFieldvalue to previous value
if (curValues[ci][cj] == 0)
jtf.setText("");
else
jtf.setText(Integer.toString(curValues[ci][cj]));
return;
}
//Out of Range checking
if (value < 0 || value > 6) {
setError("Value Out of Range", ci, cj, "Value restored");
//Restore the TextFieldvalue to previous value
if (curValues[ci][cj] == 0)
jtf.setText("");
else
jtf.setText(Integer.toString(curValues[ci][cj]));
return;
}
//If value entered is same as previous value, then no need of any action
if (curValues[ci][cj] == value)
return;
/*
* Group Numbering
* |0 |1 | --> represent two groupds not cells
* |2 |3 |
* |4 |5 |
*/
//Starting indices of the group in which the value is entered. Used for checking.
int brow = ci / 2 * 2;
int bcol = cj / 3 * 3;
//For each of six elements in row/column/group check for violations of sudoku
//If any violation then message is displayed but the value is not changed. Once
// a error is found no more checking is done.
for (int i = 0; i < 6; i++) {
//Check for Row conflict
if (curValues[ci][i] == value) {
setError("Row Conflict", ci, i, "Make necessary changes");
curValues[ci][cj] = value;
return;
}
//Check for Column conflict
if (curValues[i][cj] == value) {
setError("Column Conflict", i, cj, "Make necessary changes");
curValues[ci][cj] = value;
return;
}
//Check for Group Conflict
//The below two lines give indices to each element in a group.
int row = brow + i / 3;
int col = bcol + i % 3;
if (curValues[row][col] == value) {
setError("Block Conflict", row, col, "Make necessary changes");
curValues[ci][cj] = value;
return;
}
}
//if no Conflict then we
curValues[ci][cj] = value;
if (checkSudoku()) {
statusLabel.setForeground(Color.GREEN);
statusLabel.setText("Status: YOU WON!!!!");
//Disable all fields after Winnning
for (int i = 0; i < 6; i++)
for (int j = 0; j < 6; j++)
tf[i][j].setEnabled(false);
}
}
/**
* Used to set error(sudoku violations) in status label in red color indicating position
* @param msg
* @param x
* @param y
*/
private void setError(String msg, int x, int y, String msg2) {
statusLabel.setForeground(Color.RED);
statusLabel.setText("Status: " + msg + " with [" + (x + 1) + ", " + (y + 1) + "]. " + msg2);
}
/**
* Used to set general errors in status label
* @param msg
*/
private void setError(String msg) {
statusLabel.setForeground(Color.RED);
statusLabel.setText("Status: " + msg);
}
/**
* Checks if Sudoku is complete without all conditions
* @return True if sudoku is complete false otherwise
*/
private boolean checkSudoku() {
//Check for empty fields. If any then sudoku is not complete. So return false.
for (int i = 0; i < 6; i++)
for (int j = 0; j < 6; j++)
if (curValues[i][j] == 0)
return false;
/*
* Sudoku says there should be each of 1-6 values in each row, column and group. We check for
* that.
*
* For e.g. take a row.
* We take 6 boolean flags corresponding to values 1-6. We scan the row for each value and
* for each value found we set corresponding flag. For e.g. if 3 is found we set b[2] = true
* (array indices range is 0-5). if 1 is found, we set b[0] = true.
*
* After scanning a entire row, we check if all boolean flags are true or not. If any flag
* is false, then it indicates the corresponding value is not found and it violates sudoku
* and so we return false.
*
* This Same check is performed for every row, column and group.
*/
//For each of 6 rows/column/group
for (int i = 0; i < 6; i++) {
// ROW Check
boolean b[] = new boolean[6];
for (int j = 0; j < 6; j++)
b[curValues[i][j] - 1] = true;
for (int j = 1; j < 6; j++)
if (b[j] == false)
return false;
//Column Check
b = new boolean[6];
for (int j = 0; j < 6; j++)
b[curValues[i][j] - 1] = true;
for (int j = 0; j < 6; j++)
if (b[j] == false)
return false;
//Group check
b = new boolean[6];
int brow = i / 2 * 2;
int bcol = i % 2 * 3;
for (int j = 0; j < 6; j++) {
int row = brow + j / 3;
int col = bcol + j % 3;
b[curValues[row][col] - 1] = true;
}
for (int j = 0; j < 6; j++)
if (b[j] == false)
return false;
}
return true;
}
/*
* (non-Javadoc)
*
* @see java.awt.event.FocusListener#focusGained(java.awt.event.FocusEvent)
*/
@Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.