Word Scramble Game

Submitted by:David Villa

Date added:19 January, 2013

Category:Java

Word scramble game that was made in java by MountainDew

Tags: word scramble , java game

Code Snippet:

import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.io.*;

public class WordScramble extends JFrame implements ActionListener {

/**
* Word Scramble Game
* Coded by MountainDew
*/

public static void main(String[] args) {
new WordScramble();
}

private JButton wsButton1;
private JTextField wsTextField1;
private JLabel wsLabel1;
public String word;
public String wordlist[] = new String[100];
public int numwords = 0;

public WordScramble() {
try {
BufferedReader in = new BufferedReader(new FileReader("words.txt"));
String str;
while ((str = in.readLine()) != null) {
wordlist[numwords++] = str;
}
in.close();
} catch (IOException e) {
}
this.setSize(170,120);
this.setTitle("Word Scramble Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
JPanel wsPanel = new JPanel();
wsLabel1 = new JLabel();
wsPanel.add(wsLabel1);
wsTextField1 = new JTextField(13);
wsPanel.add(wsTextField1);
wsButton1 = new JButton("Guess!");
wsPanel.add(wsButton1);
wsButton1.addActionListener(this);
getnewword();
this.add(wsPanel);
this.setVisible(true);
wsTextField1.requestFocus();
}

public void actionPerformed(ActionEvent event) {
if (event.getSource() == wsButton1) {
String text = wsTextField1.getText();
if (text.length() == 0) {
JOptionPane.showMessageDialog(this,"Come on, guess something!");
}
else if (text.equals(word)) {
JOptionPane.showMessageDialog(this,"Correct!");
getnewword();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong!");
}
wsTextField1.setText("");
wsTextField1.requestFocus();
}
}

public void getnewword() {
int rndword;
Random randGen2 = new Random();
rndword = randGen2.nextInt(numwords);
word = wordlist[rndword];
wsLabel1.setText(scramble(word));
}

public static String scramble(String wordtoscramble) {
String newword = "";
int rndnum;
Random randGen = new Random();
boolean letter[] = new boolean[wordtoscramble.length()];
do {
rndnum = randGen.nextInt(wordtoscramble.length());
if (letter[rndnum] == false) {
newword = newword + wordtoscramble.charAt(rndnum);
letter[rndnum] = true;
}
} while (newword.length() < wordtoscramble.length());
return newword;
}
}
 
 

Comments