so I developed a code for a hangman game and what i need help in is basically simplifying, correcting and removing parts of the code that are not needed (or there is an easier way to do it). I think there are parts where i could have done it easier but i do not know where they are. I would appreciate any/ all help and will welcome all constructive criticism.
package hangman;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
@SuppressWarnings("serial")
public class HangManGUI extends JFrame implements ActionListener, KeyListener {
private final DrwPnl dPnl2 = new DrwPnl();
private final DrwPnl pnlBoard = new DrwPnl();
private final JPanel align = new JPanel();
private String playerOne = "Exikle";
private String playerTwo = "Computer";
private String puz = "";
private String categorySelected = "Easy";
private String[] allPuz;
private final JTextField customPuzzleField = new JTextField("Custom Puzzle");
private final JTextField txtName = new JTextField("Player");
private final JTextField txtOpponent = new JTextField("Opponent");
private final JLabel lblName = new JLabel();
private final JLabel lblOpponent = new JLabel();
private final JLabel wordlist = new JLabel();
private final HangmanButton[] lblWordList = new HangmanButton[8];
private final HangmanButton[] closeButton = new HangmanButton[3];
private final HangmanButton player1 = new HangmanButton();
private final HangmanButton player2 = new HangmanButton();
private final HangmanButton btnBack = new HangmanButton("Back");
private final HangmanButton btnStart = new HangmanButton("Start");
private final HangmanButton resetBtn = new HangmanButton("Reset Scores");
private final HangmanButton newGameBtn = new HangmanButton("New Game");
private final HangmanButton btnMain = new HangmanButton("Menu");
private int length;
private int count = 0;
private int linenum;
private int playersScore = 0;
private int opponentsScore = 0;
private int theSource = 1;
private int move = 0;
private int wrongAmount;
private int players = 1;
private final int[] wrLetter = new int[26];
private final int[] checked = new int[26];
private final Icon name = new ImageIcon("Name.png");
private final Icon opponent = new ImageIcon("Opponent.png");
private char[] puzzleSplit;
private char[] hid;
private final char[] letter = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z' };
private final char[] letter2 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z' };
private Boolean gameDone = false;
private final JFrame fr1 = new JFrame("");
private final JFrame fr2 = new JFrame("");
private final ClassLoader cl = HangManGUI.class.getClassLoader();
private final Image[] image = new Image[3];
private final URL[] imageURL = { cl.getResource("chalkBG.png"),
cl.getResource("hanger.png"), cl.getResource("alphaDock.png") };
private final Toolkit toolkit = Toolkit.getDefaultToolkit();
private HangManGUI() {
this.addKeyListener(this);
this.setFocusable(true);
for (int x = 0; x < 3; x++) {
closeButton[x] = new HangmanButton("closeButton");
closeButton[x].addActionListener(this);
closeButton[x].setBounds(275, 0, 25, 25);
}
DrwPnl dPnl1 = new DrwPnl();
dPnl1.add(closeButton[0]);// Add closeButton button to 1st Screen
dPnl2.add(closeButton[1]);// Add closeButton button to 2nd Screen
this.add(closeButton[2]);// Add closeButton button to Board
closeButton[2].setBounds(475, 0, 25, 25);
if (imageURL != null) {
for (int x = 0; x < 3; x++)
image[x] = toolkit.createImage(imageURL[x]);
}
// ////Chose Player Menu(1)==============>
dPnl1.setLayout(null);
// /Player 1 button initialize--------->
player1.setBounds(25, 125, 250, 50);
player1.addActionListener(this);
player1.setText("Player 1");
dPnl1.add(player1);
// /Player 2 button initialize--------->
player2.setBounds(25, 200, 250, 50);
player2.addActionListener(this);
player2.setText("Player 2");
dPnl1.add(player2);
// /End Player Button Initializing------->
fr1.add(dPnl1);
fr1.setUndecorated(true);// Take out preset border
Boolean undecorated = fr1.isUndecorated();
fr1.setVisible(true);
fr1.setSize(300, 300);
fr1.setLocation(300, 300);
// ////<========End Chose Player Menu(1)
// ////Chose Categories Menu(2)========>
dPnl2.setLayout(null);
// /Initialize WordList Icon\Label--->
dPnl2.add(wordlist);
wordlist.setBounds(100, 75, 150, 75);
Icon wList = new ImageIcon("WordList.png");
wordlist.setIcon(wList);
// /Initialize Go To 1st Menu Button---------->
dPnl2.add(btnBack);
btnBack.setBounds(0, 250, 75, 25);
btnBack.addActionListener(this);
// /Initialize Start Game/Go to Board---------->
dPnl2.add(btnStart);
btnStart.setBounds(225, 250, 75, 25);
btnStart.addActionListener(this);
// /Add Categories into grid------------->
align.setLayout(new GridLayout(4, 2));
for (int x = 0; x < 8; x++) {
String[] categories = { "Easy", "Food", "Standard", "Geography",
"Hard", "Holidays", "Animals", "Sports" };
lblWordList[x] = new HangmanButton(categories[x] + "");
lblWordList[x].addActionListener(this);
align.add(lblWordList[x]);
}
// /<-------------End Category Initializing and Layout Setting
fr2.add(dPnl2);
fr2.setSize(300, 300);
fr2.setLocation(300, 300);
fr2.setUndecorated(true);// Take out preset border
undecorated = fr2.isUndecorated();// Take out preset border
// ////<==================End Chose Player Menu(2)
// ////Create Playing Board================>
// Add Board to main form------------->
pnlBoard.setLayout(new GridLayout(1, 1));
JPanel pnl2 = new JPanel();
pnl2.setLayout(new BorderLayout());
pnl2.add(pnlBoard, BorderLayout.CENTER);
// <---------End Add Board to main form
JPanel pnl3 = new JPanel();
pnl3.setLayout(new GridLayout(1, 1));
pnl3.add(pnl2);
// Initialize New Game Button---------->
newGameBtn.addActionListener(this);
newGameBtn.setBorderPainted(false);
this.add(newGameBtn);
newGameBtn.setBounds(225, 0, 100, 25);
// Initialize Reset Scores Button---------->
resetBtn.addActionListener(this);
resetBtn.setBorderPainted(false);
this.add(resetBtn);
resetBtn.setBounds(100, 0, 125, 25);
// Initialize Go To Main Menu Button---------->
btnMain.addActionListener(this);
btnMain.setBorderPainted(false);
this.add(btnMain);
btnMain.setBounds(0, 0, 100, 25);
this.add(pnl3);
this.setUndecorated(true);// Take out preset border
undecorated = this.isUndecorated();// Take out preset border
this.setVisible(false);
this.setLocation(200, 200);
this.setSize(500, 325);
// ////<===========End Create Playing Board
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == player1) {
System.out.println("Player 1 was pressed");
fr1.setVisible(false);
fr2.setVisible(true);
theSource = 2;
players = 1;
lblWordList[1].setForeground(Color.BLUE);
dPnl2.add(align);
align.setBounds(25, 125, 250, 100);
align.setOpaque(false);
dPnl2.add(lblName);
lblName.setBounds(50, 50, 75, 25);
lblName.setIcon(name);
dPnl2.add(txtName);
txtName.setBounds(125, 50, 125, 25);
txtName.setOpaque(false);
txtName.setBorder(null);
dPnl2.add(wordlist);
wordlist.setBounds(100, 75, 150, 75);
dPnl2.remove(lblOpponent);
dPnl2.remove(txtOpponent);
dPnl2.remove(customPuzzleField);
} else if (e.getSource() == player2) {
System.out.println("Player 2 was pressed");
lblWordList[1].setForeground(Color.BLUE);
players = 2;
theSource = 2;
categorySelected = "Custom";
fr1.setVisible(false);
fr2.setVisible(true);
dPnl2.remove(align);
dPnl2.remove(wordlist);
dPnl2.add(lblOpponent);
lblOpponent.setBounds(75, 125, 100, 25);
lblOpponent.setIcon(opponent);
dPnl2.add(txtOpponent);
txtOpponent.setBounds(175, 125, 100, 25);
txtOpponent.setBorder(null);
dPnl2.add(customPuzzleField);
customPuzzleField.setBounds(100, 175, 100, 25);
dPnl2.add(lblName);
lblName.setBounds(75, 75, 75, 25);
lblName.setIcon(name);
dPnl2.add(txtName);
txtName.setBounds(150, 75, 125, 25);
txtName.setBorder(null);
}
if (e.getSource() == btnBack) {
theSource = 1;
System.out.println("Back was pressed");
fr2.setVisible(false);
fr1.setVisible(true);
}
for (int x = 0; x < 8; x++) {
lblWordList[x].setForeground(Color.BLACK);
if (e.getSource() == lblWordList[x]) {
if (players == 1) {
categorySelected = lblWordList[x].getText();
lblWordList[x].setForeground(Color.BLUE);
System.out.println(x);
} else
categorySelected = playerTwo + "'s Puzzle";
}
}
if (e.getSource() == btnStart) {
theSource = 3;
System.out.println("Start was pressed");
playerOne = txtName.getText();
if (players == 2)
playerTwo = txtOpponent.getText();
fr2.setVisible(false);
try {
if (players == 1)
getPuz();
createPuz();
} catch (Exception f) {
System.out.println("Problem Creating Puzzle");
}
this.setVisible(true);
}
for (int x = 0; x < 3; x++) {
if (e.getSource() == closeButton[x]) {
System.exit(0);
}
}
if (e.getSource() == resetBtn) {
opponentsScore = 0;
playersScore = 0;
repaint();
} else if (e.getSource() == newGameBtn) {
imageURL[1] = cl.getResource("hanger.png");
image[1] = toolkit.createImage(imageURL[1]);
move = 0;
count = 0;
gameDone = false;
for (int x = 0; x < 26; x++) {
checked[x] = 0;
wrLetter[x] = 0;
}
try {
getPuz();
createPuz();
} catch (Exception f) {
System.out.println("Problem Creating Puzzle");
}
repaint();
}
if (e.getSource() == btnMain) {
opponentsScore = 0;
playersScore = 0;
move = 0;
count = 0;
gameDone = false;
playerTwo = "Opponent";
playerOne = "Player";
for (int x = 0; x < 26; x++) {
checked[x] = 0;
wrLetter[x] = 0;
}
this.setVisible(false);
fr2.setVisible(true);
theSource = 2;
}
}
private class DrwPnl extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
if ((theSource == 1) || (theSource == 2)) {
g2.drawImage(image[0], 0, 0, 300, 300, 0, 0, 300, 300, this);
g2.setColor(Color.WHITE);
if (theSource == 1)
g2.drawString("Hang Man", 12, 100);
g2.setColor(Color.BLACK);
} else if (theSource == 3) {
g2.drawImage(image[0], 0, 0, 500, 275, 0, 0, 300, 300, this);
if ((move < 5) && (move >= 0))
g2.drawImage(image[1], 300 - 25 * move, 125,
350 - 25 * move, 200, 0, 0, 131, 300, this);
if ((move >= 5) && (move < 7))
g2.drawImage(image[1], 300 - 25 * move, 100,
350 - 25 * move, 175, 0, 0, 131, 300, this);
if ((move == 7) || (move >= 8)) {
g2.drawImage(image[1], 125, 50, 175, 150, 0, 0, 131, 300,
this);
if (move == 7) {
g2.setColor(Color.RED);
g2.fillRect(125, 150, 50, 25);
}
}
g2.setColor(Color.YELLOW);
g2.drawLine(365, 25, 365, 215);
g2.drawLine(25, 210, 375, 210);
g2.setColor(Color.RED);
g2.fillRect(50, 175, 125, 25);
g2.fillRect(75, 25, 25, 150);
g2.fillRect(100, 25, 75, 25);
g2.fillRect(175, 175, 25, 25);
g2.setStroke(new BasicStroke(10));
g2.drawLine(100, 75, 125, 50);
g2.setColor(Color.BLACK);
g2.drawImage(image[2], 0, 275, 500, 325, 0, 0, 320, 48, this);
for (int x = 0; x < 26; x++) {
if (wrLetter[x] == 0)
g2.setColor(Color.BLACK);
else if (wrLetter[x] == 1)
g2.setColor(Color.GREEN);
else if (wrLetter[x] == 2)
g2.setColor(Color.RED);
g2.drawString("" + letter[x], 5 + 19 * x, 305);
}
g2.setColor(Color.BLACK);
for (int x = 0; x < length; x++)
g2.drawString("" + hid[x], 25 + 35 * x, 250);
g2.setColor(Color.WHITE);
g2.drawString("Category:", 375, 50);
g2.drawString(playerOne, 375, 100);
g2.drawString(playerTwo, 375, 150);
g2.setColor(Color.BLACK);
g2.drawString(categorySelected, 375, 75);
g2.drawString("" + playersScore, 375, 125);
g2.drawString("" + opponentsScore, 375, 175);
}
}
}
void getPuz() {
BufferedReader in = null;
String line = "";
File f = new File("Word List/" + categorySelected + ".txt");
int num = 0;
LineNumberReader reader = null;
try {
reader = new LineNumberReader(new FileReader(f));
} catch (FileNotFoundException e2) {
System.out.println("File Not Found");
}
String lineRead = "";
try {
while ((lineRead = reader.readLine()) != null) {
}
} catch (IOException e1) {
System.out.println("Error 1");
}
linenum = reader.getLineNumber();
try {
reader.close();
} catch (IOException e1) {
System.out.println("Error 2");
}
try {
allPuz = new String[linenum];
in = new BufferedReader(new FileReader(f));
System.out.println("File Opening");
} catch (FileNotFoundException e) {
System.out.println("Problem opening File");
}
while (line != null) {
try {
line = in.readLine();
if (line != null) {
allPuz[num] = "" + line;
num++;
}
} catch (IOException e) {
System.out.println("Problem reading data from file");
}
}
}
void createPuz() {
int randomnum = (int) (Math.random() * linenum);
if (players == 1)
puz = "" + allPuz[randomnum];
else if (players == 2)
puz = customPuzzleField.getText();
System.out.println(puz);
length = puz.length();
puzzleSplit = new char[length];
hid = new char[length];
for (int x = 0; x < length; x++) {
puzzleSplit[x] = (puz.charAt(x));
if (puzzleSplit[x] == ' ') {
hid[x] = (' ');
count += 1;
} else
hid[x] = ('_');
}
}
public void keyTyped(KeyEvent f) {
if (!gameDone) {
String key = "" + f.getKeyChar();
Boolean rightletter = false;
Boolean wwrongAmount = true;
for (int x = 0; x < 26; x++) {
if (("" + letter[x]).equalsIgnoreCase(key)) {
if (checked[x] == 1) {
JOptionPane.showMessageDialog(this, "Already pressed "
+ letter[x] + ".");
for (int y = 0; y < length; y++) {
if ((letter[x] == puzzleSplit[y])
|| (letter2[x] == puzzleSplit[y])) {
hid[y] = puzzleSplit[y];
rightletter = true;
wrLetter[x] = 1;
wwrongAmount = false;
checked[x] = 1;
if (count == length) {
JOptionPane.showMessageDialog(this,
"You Win");
gameDone = true;
playersScore += 1;
}
}
}
} else if (checked[x] == 0) {
for (int y = 0; y < length; y++) {
if ((letter[x] == puzzleSplit[y])
|| (letter2[x] == puzzleSplit[y])) {
hid[y] = puzzleSplit[y];
rightletter = true;
wrLetter[x] = 1;
count += 1;
wwrongAmount = false;
checked[x] = 1;
if (count == length) {
JOptionPane.showMessageDialog(this,
"You Win");
gameDone = true;
playersScore += 1;
}
}
}
}
wrongAmount = x;
}
}
if (!rightletter) {
for (int x = 0; x < 26; x++) {
if (("" + letter[x]).equalsIgnoreCase(key)) {
move++;
wrLetter[x] = 2;
checked[x] = 1;
wrongAmount = x;
}
}
}
if (wwrongAmount)
wrLetter[wrongAmount] = 2;
wwrongAmount = true;
if (move == 7) {
imageURL[1] = cl.getResource("hanger2.png");
image[1] = toolkit.createImage(imageURL[1]);
} else if (move >= 8) {
imageURL[1] = cl.getResource("hanger3.png");
JOptionPane.showMessageDialog(this, "You Lose");
opponentsScore += 1;
gameDone = true;
pnlBoard.setEnabled(false);
resetBtn.setEnabled(true);
image[1] = toolkit.createImage(imageURL[1]);
for (int x = 0; x < 26; x++) {
for (int y = 0; y < length; y++) {
if ((letter[x] == puzzleSplit[y])
|| (letter2[x] == puzzleSplit[y])) {
hid[y] = puzzleSplit[y];
}
}
}
} else {
imageURL[1] = cl.getResource("hanger.png");
image[1] = toolkit.createImage(imageURL[1]);
}
repaint();
}
}
public void keyPressed(KeyEvent f) {
}
public void keyReleased(KeyEvent f) {
}
public static void main(String[] args) {
new HangManGUI();
}
}
EDIT: after modifying the code, i realized i could create a new class which extends a JButton and put the code for the buttons (the defaults and the font setting) in there to shorten and organize code.
package hangman;
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import javax.swing.DefaultButtonModel;
import javax.swing.Icon;
import javax.swing.JButton;
class HangmanButton extends JButton {
private static final Icon NO_ICON = null;
private static final String NO_STRING = null;
private Font dFont = null;
public HangmanButton() {
this(NO_STRING, NO_ICON);
}
public HangmanButton(String string) {
this(string, NO_ICON);
}
public HangmanButton(Icon icon) {
this(NO_STRING, icon);
}
private HangmanButton(String s, Icon i) {
setModel(new DefaultButtonModel());
init(s, i);
this.setOpaque(false);
this.setContentAreaFilled(false);
this.setBorderPainted(false);
try {
File f = new File("VTK.ttf");
FileInputStream in = new FileInputStream(f);
dFont = Font.createFont(Font.TRUETYPE_FONT, in);
this.setFont(dFont.deriveFont(10f));
} catch (Exception e) {
System.out.println("Problem Creating Font");
}
}
public void setFont(int num) {
this.setFont(dFont.deriveFont((float) num));
}
}
If any one wants to see the images/files and/or download them to use while checking, I uploaded this code to Github.
