DAFTAR PUSTAKA Anis Cherid, 2010. Model Kuliah Algoritma dan

advertisement
DAFTAR PUSTAKA
Anis Cherid, 2010. Model Kuliah Algoritma dan Pemrograman. Prodi Teknik
Informatika, Tidak Dipublikasikan.
Isak Rickyanto. Dasar Pemrograman Berorientasi Objek Dengan Java 2 (JDK
1.4). Yogyakarta: Andi. 2003.
Munawar. Pemodelan Visual Dengan UML. Yogyakarta : Graha Ilmu. 2005.
Sudarmawan dan Ariyus. Interaksi Manusia dan Komputer. Yogyakarta : Andi.
2007.
Tia Astiyah Hasan. Aplikasi Permainan Tebak Kata Bahasa Inggris Dengan
Menggunakan Kamus Online di Internet. Skripsi Prodi Teknik Informatika
Universitas Mercu Buana. 2011.
Yulikuspartono. Pengantar Logika dan Algoritma. Yogyakarta : Andi. 2004.
http://masnugh.blogspot.com/2012/10/gridlayout-pada-pemrograman-java.html di
akses tanggal 23 april 2014
http://direngreyfrian.blogspot.com/2012/12/tugas-modul-5-pemrogramandesktop.html di akses tanggal 23 april 2014
http://sina-mind.blogspot.com/2011/03/mengenal-thread-pada-java.html di akses
tanggal 23 april 2014
http://wahyuganteng72.blogspot.com/2011/02/jaringan-network-dalampemrograman.html di akses tanggal 23 april 2014
http://java.lyracc.com/ di akses tanggal 23 april 2014
http://en.wikipedia.org/wiki/Google_Translate di akses tanggal 23 april 2014
http://masbadar.com/bahasa-inggris-definisi-dan-sejarahnya/ di akses tanggal 23
april 2014
http://elgrid.wordpress.com/2011/12/26/pengertian-kalimat-2/ di akses tanggal 23
april 2014
LAMPIRAN
Form 1
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import java.awt.Dialog.ModalExclusionType;
import javax.swing.JLabel;
public class Form1 {
private static JFrame frmBasicWordsHangman;
private JPanel panelButton;
private GridLayout grid;
private JScrollPane scrollButton;
private JTextField textStatus;
public static boolean debug = false;
public static void setVisibleToTrue(){
frmBasicWordsHangman.setVisible(true);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Form1 window = new Form1();
window.frmBasicWordsHangman.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Form1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmBasicWordsHangman = new JFrame();
frmBasicWordsHangman.setResizable(false);
frmBasicWordsHangman.setModalExclusionType(ModalExclusionType.APP
LICATION_EXCLUDE);
frmBasicWordsHangman.setTitle("Basic Words Hangman");
frmBasicWordsHangman.setBounds(10, 10, 680, 580);
frmBasicWordsHangman.setDefaultCloseOperation(JFrame.EXIT_ON_CLO
SE);
frmBasicWordsHangman.getContentPane().setLayout(null);
scrollButton = new JScrollPane();
scrollButton.setBounds(12, 46, 647, 455);
frmBasicWordsHangman.getContentPane().add(scrollButton);
panelButton = new JPanel();
scrollButton.setViewportView(panelButton);
grid = new GridLayout(10,3,10,10);
panelButton.setLayout(grid);
textStatus = new JTextField();
textStatus.setText("...");
textStatus.setBounds(0, 528, 674, 20);
frmBasicWordsHangman.getContentPane().add(textStatus);
textStatus.setColumns(10);
JLabel lblBasicWordsList = new JLabel("Basic Words List");
lblBasicWordsList.setFont(new Font("Trebuchet MS", Font.BOLD,
14));
lblBasicWordsList.setBounds(12, 11, 122, 24);
frmBasicWordsHangman.getContentPane().add(lblBasicWordsList);
new Thread(){
@Override
public void run(){
WebSiteManager
.executeGetPage(textStatus,
"basicwords.txt",
"http://simple.m." +
"wiktionary.org/wiki/" +
"Wiktionary:Extended_Basic_English_alphabetical_wordlist");
waitForStatus();
createWordListButton();
}
}.start();
}
private void waitForStatus(){
while (!(textStatus.getText().contains("Success")||
textStatus.getText().contains("Error"))){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void createWordListButton(){
String basicWords="";
Pattern htmlTag = Pattern.compile(
"<a\\shref\\=\"/wiki/([a-z]+)\"\\s+title\\=\"\\1\">");
Matcher tagMatch = htmlTag.matcher(
WebSiteManager
.htmlText);
while (tagMatch.find()) {
basicWords += tagMatch.group(1) + " ";
}
if (basicWords.split(" ").length>10){
textStatus.setText("Success");
} else {
textStatus.setText("Error: word download fail");
}
if (textStatus.getText().equals("Success")) {
String[] words = basicWords
.split(" ");
int numberOfWord = 0;
File file = null;
FileReader fr = null;
boolean fileNotFound;
int debugMaxLoop = 14;
for (String word : words) {
if (debug && --debugMaxLoop<=0) break;
JButton b = new JButton(word);
b.setFont(new Font("Calibri", Font.BOLD, 22));
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0)
{
final String word = ((JButton) arg0
.getSource()).getText();
textStatus.setText("Downloading
definition...");
new Thread(){
@Override
public void run(){
textStatus.setText("Connecting to Wiktionary.org...");
WebSiteManager
.executeGetPage(textStatus,
word
+
".html",
"http://simple.m." +
"wiktionary.org/wiki/" +
word);
waitForStatus();
if (textStatus.getText()
.contains("Success") &&
!WebSiteManager.htmlText
.contains("there is no text on this page")){
frmBasicWordsHangman.setVisible(false);
Form2.selectedWord = word;
Form2.main(null);
} else {
textStatus.setText("There is no " +
"simple English definition " +
"for the word. Please try other words.");
}
}
}.start();
}
});
fileNotFound = false;
try {
file = new File(word + ".html");
fr = new FileReader(file);
fr.close();
} catch (FileNotFoundException e) {
fileNotFound = true;
} catch (IOException e) {
e.printStackTrace();
}
if (fileNotFound) {
b.setForeground(new Color(50, 50, 175));
}
panelButton.add(b);
textStatus.setText("Adding words: "
+ numberOfWord++);
}
grid = new GridLayout (
panelButton.getComponentCount()/3,
3,10,10);
panelButton.setLayout(grid);
panelButton.revalidate();
panelButton.repaint();
frmBasicWordsHangman.validate();
frmBasicWordsHangman.repaint();
numberOfWord=0;
while (scrollButton.getHorizontalScrollBar()
.isShowing()) {
grid = new GridLayout(grid.getRows() + 1, 3,
10, 10);
panelButton.setLayout(grid);
panelButton.revalidate();
panelButton.repaint();
frmBasicWordsHangman.validate();
frmBasicWordsHangman.repaint();
textStatus.setText("Adjusting layout: "
+ numberOfWord++);
}
textStatus.setText("Finish");
} else {
textStatus.setText("Retrying...");
JOptionPane.showMessageDialog(null,
"Please make sure you have " +
"Internect connection and " +
"then click the OK button to " +
"try downloading the word list again");
new Thread(){
@Override
public void run(){
textStatus.setText("Connecting
Wiktionary.org...");
WebSiteManager
.executeGetPage(textStatus,
"basicwords.txt",
"http://simple.m." +
"wiktionary.org/wiki/" +
"Wiktionary:Extended_Basic_English_alphabetical_wordlist");
waitForStatus();
createWordListButton();
}
}.start();
}
}
}
Form 2
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
public class Form2 {
public static String selectedWord;
to
private static JFrame frmBasicWordsDefinition;
private JTextPane textHTMLDefinition;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Form2 window = new Form2();
window.frmBasicWordsDefinition.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Form2() {
initialize();
}
public static void setVisibleToTrue(){
frmBasicWordsDefinition.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmBasicWordsDefinition = new JFrame();
frmBasicWordsDefinition.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosed(WindowEvent arg0) {
Form1.setVisibleToTrue();
}
});
frmBasicWordsDefinition.setDefaultCloseOperation(JFrame.DISPOSE_ON_
CLOSE);
frmBasicWordsDefinition.setFont(new
Font("Trebuchet
MS",
Font.BOLD, 14));
frmBasicWordsDefinition.setTitle("Basic Words Definition");
frmBasicWordsDefinition.setBounds(10, 10, 680, 580);
frmBasicWordsDefinition.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 652, 491);
frmBasicWordsDefinition.getContentPane().add(scrollPane);
textHTMLDefinition = new JTextPane();
textHTMLDefinition.setFont(new Font("Tahoma", Font.PLAIN, 11));
textHTMLDefinition.setEditable(false);
scrollPane.setViewportView(textHTMLDefinition);
JButton btnBackToWord = new JButton("Back to Word List Page");
btnBackToWord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frmBasicWordsDefinition.dispose();
}
});
btnBackToWord.setFont(new Font("Trebuchet MS", Font.BOLD,
14));
btnBackToWord.setBounds(460, 513, 202, 23);
frmBasicWordsDefinition.getContentPane().add(btnBackToWord);
JButton btnPracticeHangman = new JButton("Practice Hangman");
btnPracticeHangman.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frmBasicWordsDefinition.setVisible(false);
Form3.selectedWord = selectedWord;
Form3.main(null);
}
});
btnPracticeHangman.setFont(new Font("Trebuchet MS", Font.BOLD,
14));
btnPracticeHangman.setBounds(10, 513, 202, 23);
frmBasicWordsDefinition.getContentPane().add(btnPracticeHangman);
Thread thread = new Thread(){
@Override
public void run(){
File file = new File(selectedWord + ".html");
try {
textHTMLDefinition.setPage(
file.toURI().toURL());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
thread.setPriority(1);
thread.setDaemon(true);
thread.start();
}
}
Form 3
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Font;
import java.awt.Dialog.ModalExclusionType;
import java.awt.TextArea;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Form3 {
private JFrame frmHangmanPractice;
private JTextField textTryLeft;
private JTextArea textProblem;
private JPanel panelButton;
private JScrollPane scrollButton;
private GridLayout grid;
private String[] arrayWord;
public static String selectedWord;
private HangmanManager hangman;
private boolean isHandlingClick;
private JTextField textStatus;
private JTextArea textHint;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Form3 window = new Form3();
window.frmHangmanPractice.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Form3() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHangmanPractice = new JFrame();
frmHangmanPractice.setResizable(false);
frmHangmanPractice.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent arg0) {
Form2.setVisibleToTrue();
}
});
frmHangmanPractice.getContentPane().setFont(new Font("Trebuchet
MS", Font.BOLD, 14));
frmHangmanPractice.setFont(new Font("Trebuchet MS", Font.BOLD,
14));
frmHangmanPractice.setTitle("Hangman Practice");
frmHangmanPractice.setBounds(10, 10, 680, 580);
frmHangmanPractice.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLO
SE);
frmHangmanPractice.getContentPane().setLayout(null);
JScrollPane scrollProblem = new JScrollPane();
scrollProblem.setBounds(10, 29, 647, 84);
frmHangmanPractice.getContentPane().add(scrollProblem);
textProblem = new JTextArea();
textProblem.setWrapStyleWord(true);
textProblem.setLineWrap(true);
textProblem.setFont(new Font("Trebuchet MS", Font.BOLD, 18));
scrollProblem.setViewportView(textProblem);
scrollButton = new JScrollPane();
scrollButton.setBounds(10, 252, 647, 216);
frmHangmanPractice.getContentPane().add(scrollButton);
panelButton = new JPanel();
scrollButton.setViewportView(panelButton);
panelButton.setLayout(new GridLayout(10, 3, 10, 10));
JScrollPane scrollHint = new JScrollPane();
scrollHint.setBounds(12, 139, 645, 82);
frmHangmanPractice.getContentPane().add(scrollHint);
textHint = new JTextArea();
textHint.setWrapStyleWord(true);
textHint.setLineWrap(true);
scrollHint.setViewportView(textHint);
textHint.setFont(new Font("Trebuchet MS", Font.BOLD, 18));
JLabel lblProblem = new JLabel("Problem to solve:");
lblProblem.setFont(new Font("Trebuchet MS", Font.BOLD, 14));
lblProblem.setBounds(10, 11, 131, 14);
frmHangmanPractice.getContentPane().add(lblProblem);
JLabel lblChoices = new JLabel("Choices:");
lblChoices.setFont(new Font("Trebuchet MS", Font.BOLD, 14));
lblChoices.setBounds(10, 232, 131, 14);
frmHangmanPractice.getContentPane().add(lblChoices);
JButton btnBackToDefinition = new JButton("Back to Definition
Page");
btnBackToDefinition.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frmHangmanPractice.dispose();
}
});
btnBackToDefinition.setFont(new Font("Trebuchet MS", Font.BOLD,
14));
btnBackToDefinition.setBounds(455, 481, 202, 23);
frmHangmanPractice.getContentPane().add(btnBackToDefinition);
textTryLeft = new JTextField();
textTryLeft.setFont(new Font("Trebuchet MS", Font.BOLD, 14));
textTryLeft.setBounds(177, 480, 39, 23);
frmHangmanPractice.getContentPane().add(textTryLeft);
textTryLeft.setColumns(10);
JLabel lblNumberOfTries = new JLabel("Number of Tries Left:");
lblNumberOfTries.setFont(new Font("Trebuchet MS", Font.BOLD,
14));
lblNumberOfTries.setBounds(10, 480, 157, 23);
frmHangmanPractice.getContentPane().add(lblNumberOfTries);
JLabel lblHintpoweredBy = new JLabel("Hint (powered by Google
Translate)");
lblHintpoweredBy.setFont(new Font("Trebuchet MS", Font.BOLD,
14));
lblHintpoweredBy.setBounds(11, 120, 231, 14);
frmHangmanPractice.getContentPane().add(lblHintpoweredBy);
JButton btnNewProblem = new JButton("New Problem");
btnNewProblem.setFont(new Font("Trebuchet MS", Font.BOLD,
14));
btnNewProblem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new Thread(){
@Override
public void run(){
createGameButton();
String textInEnglish =
hangman.getOriginalLine().replaceAll
("\\s", "+");
textStatus.setText("Connecting
to
Google Translate...");
textHint.setText("Getting
translation
from Google Translate...");
WebSiteManager.translateUsingGoogle(textStatus,
textInEnglish,
"https://translate.google.com/translate_a/t?client=j&text=" +
textInEnglish +
"&hl=en&sl=en&tl=id");
waitForStatus();
if (!textStatus.getText()
.contains("Error")){
String translatedSentence ="";
Pattern
htmlTag
=
Pattern.compile(
".*?trans\"\\:\"(.*?)\",\""
,
Pattern.DOTALL);
Matcher
tagMatch
=
htmlTag.matcher(
WebSiteManager.translationText);
while (tagMatch.find()){
translatedSentence
+=
tagMatch.group(1);
}
textHint.setText(translatedSentence);
} else {
textHint.setText(
"Cannot
translation from Google Translate"
);
}
}
}.start();
}
});
btnNewProblem.setBounds(250, 480, 151, 23);
frmHangmanPractice.getContentPane().add(btnNewProblem);
textStatus = new JTextField();
textStatus.setText("...");
textStatus.setColumns(10);
textStatus.setBounds(0, 528, 674, 20);
frmHangmanPractice.getContentPane().add(textStatus);
new Thread(){
@Override
public void run(){
WebSiteManager
.executeGetPage(textStatus,
selectedWord + ".html",
get
"http://simple.m." +
"wiktionary.org/wiki/" +
selectedWord);
waitForStatus();
if (!textStatus.getText().contains("Error")){
createGameButton();
String textInEnglish =
hangman.getOriginalLine().replaceAll
("\\s", "+");
textStatus.setText("Connecting
to
Google
Translate...");
textHint.setText("Getting
translation
from
Google Translate...");
WebSiteManager.translateUsingGoogle(textStatus,
textInEnglish,
"https://translate.google.com/translate_a/t?client=j&text=" +
textInEnglish +
"&hl=en&sl=en&tl=id");
waitForStatus();
if (!textStatus.getText()
.contains("Error")){
String translatedSentence ="";
Pattern htmlTag = Pattern.compile(
".*?trans\"\\:\"(.*?)\",\""
, Pattern.DOTALL);
Matcher tagMatch = htmlTag.matcher(
WebSiteManager.translationText);
while (tagMatch.find()){
translatedSentence
+=
tagMatch.group(1);
}
textHint.setText(translatedSentence);
} else {
textHint.setText(
"Cannot get translation
from Google Translate"
);
}
}
}
}.start();
}
private String parseProblem(String text){
String problems="";
Pattern htmlTag = Pattern.compile(
"<h2.*?</h2>.*?<table.*?</table>.*?<ol>.*?" +
"<dl>.*?<dd><i>.*?</i></dd>.*?</dl>.*?"
+ "</ol>"
, Pattern.DOTALL);
Matcher tagMatch = htmlTag.matcher(
text);
while (tagMatch.find()){
String parts = tagMatch.group();
Pattern htmlTag2 = Pattern.compile(
"<dd><i>(.*?)</i></dd>"
, Pattern.DOTALL);
Matcher tagMatch2 = htmlTag2.matcher(
parts);
while (tagMatch2.find()){
if (!tagMatch2.group(1).contains("<img")){
problems += tagMatch2.group(1)
.replaceAll("(</*b>|" +
"</*a.*?>)", "") +
"####\n";
} else if (tagMatch2.group(1).contains("<img")
&&
tagMatch2.group(1).contains("alt=\""))
{
String temp = tagMatch2.group(1)
.replaceAll("(</*b>|" +
"</*a.*?>)", "");
temp = temp.replaceAll
("<img.*?alt=\"(.*?)\".*?>",
"$1");
problems += temp + "####\n";
}
}
}
return problems;
}
private void createGameButton(){
String problem[] =
parseProblem(
WebSiteManager.htmlText)
.split("####\\n");
int numberOfProblem
= problem.length;
String listOfProblem="";
for (int i=0; i<numberOfProblem; i++){
listOfProblem += listOfProblem + String.valueOf(i) + " ";
}
int numberOfSelectedProblem = (int)
(Math.random()*numberOfProblem);
boolean isNumberOfButtonOK = false;
hangman = new HangmanManager(problem
[numberOfSelectedProblem]);
listOfProblem = listOfProblem
.replaceAll("\\b" +
numberOfSelectedProblem +
"\\s", "");
int numberOfWordInOriginalProblem =
hangman.getNumberOfUniqueWords();
do {
String[] restOfProblem =
listOfProblem.trim()
.split("\\s");
numberOfSelectedProblem = Integer
.parseInt(
restOfProblem[(int)
(Math.random()*
restOfProblem.length)]);
hangman.addDistractor(
problem[numberOfSelectedProblem]);
listOfProblem = listOfProblem
.replaceAll("\\b" +
String.valueOf(numberOfSelectedProblem) +
"\\s", "");
if (hangman
.getNumberOfUniqueWords()
>numberOfWordInOriginalProblem*2){
isNumberOfButtonOK = true;
}
} while (!isNumberOfButtonOK &&
!listOfProblem.trim().isEmpty());
textProblem.setText(hangman.getDisplayedProblem());
hangman.setNumberOfMaximumMiss(
(int) (hangman.getNumberOfUniqueWords()*.2));
textTryLeft.setText(""+hangman.getNumberOfMaximumMiss());
arrayWord = hangman.getUniqueWords().split(" ");
if (Form1.debug==false){
Arrays.sort(arrayWord);
}
panelButton.removeAll();
for (String word:arrayWord){
JButton b = new JButton(word);
b.setFont(new Font("Calibri", Font.BOLD, 22));
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (hangman.isPlaying() && !isHandlingClick){
isHandlingClick = true;
String
word
=
((JButton)
arg0.getSource()).getText();
if
(!("
"
+
hangman.getAnsweredWords() + " ")
.toLowerCase()
.contains(" " + word + " ")){
if
(hangman.isAnwerCorrect(word)){
//soundButton.playRandomSound(null);
((JButton)
arg0.getSource())
.setForeground(new Color(50,150,50));
textProblem.setText(hangman.getDisplayedProblem());
if
(hangman.isAllWordsAnswered() /*||
Form1.debug*/){
hangman.setPlaying(false);
JOptionPane.showMessageDialog(null,
"Congratulations...");
}
} else {
((JButton)
arg0.getSource()).setForeground(
new
Color(150,50,50));
hangman.setNumberOfCurrentMiss(
hangman
.getNumberOfCurrentMiss()-1);
//
//
if (Form1.debug){
hangman.setNumberOfCurrentMiss(0);
//
}
int
missed
hangman.getNumberOfCurrentMiss();
if (missed==0){
hangman.setPlaying(false);
textProblem.setText(
hangman.getTaggedLine()
.replaceAll("@@@", "")
.replaceAll("###", ""));
hangman.setDisplayedProblem(textProblem
.getText().toString());
=
textTryLeft.setText(""+ missed);
JOptionPane.showMessageDialog(null,
"You fail. Better luck next time...");
} else {
textTryLeft.setText(""+ missed);
}
}
}
else
if(("
"
+
hangman.getAnsweredWords() + " ")
.toLowerCase(Locale.US)
.contains(" " + word + "
")){
//
Toast.makeText(mContext,
//
"You
have answered with the word, please try other words," +
//
"\nor if you want to load definition from the Web, " +
//
"\nthen long click on the word button...",
//
Toast.LENGTH_LONG).show();
}
isHandlingClick = false;
}
}
});
//buttonList.addFirst(b);
panelButton.add(b);
}
grid = new GridLayout (
panelButton.getComponentCount()/3,
3,10,10);
panelButton.setLayout(grid);
panelButton.revalidate();
panelButton.repaint();
frmHangmanPractice.validate();
frmHangmanPractice.repaint();
while (scrollButton.getHorizontalScrollBar()
.isShowing()){
grid = new GridLayout (grid.getRows()+1,3,10,10);
panelButton.setLayout(grid);
panelButton.revalidate();
panelButton.repaint();
frmHangmanPractice.validate();
frmHangmanPractice.repaint();
}
}
private void waitForStatus(){
while (!(textStatus.getText().contains("Success")||
textStatus.getText().contains("Error"))){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
WebsiteManager
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JTextField;
public class WebSiteManager {
public static String htmlText;
public static String translationText;
public static void executeGetPage(JTextField status,
String nameOfFile, String urlName){
final JTextField textStatus = status;
final String name = nameOfFile;
final String myURL = urlName;
new Thread(){
@Override
public void run(){
htmlText = "";
File file=null;
boolean fileNotFound = false;
try {
file = new File(name);
FileReader fr = new FileReader(file);
char[] chars = new char[(int) file.length()];
fr.read(chars);
htmlText = new String(chars);
fr.close();
} catch (FileNotFoundException e) {
fileNotFound = true;
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
if (fileNotFound){
URL url;
InputStream is = null;
char[] buffer = new char[4096];
//textStatus.setText("Connecting...");
try {
//String
myURL="http://simple.m.wiktionary.org/wiki/Wiktionary:Extended_Basic_English_
alphabetical_wordlist";
url = new URL(myURL);
HttpURLConnection
conn
=
(HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000
milliseconds */);
conn.setConnectTimeout(15000
milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
/*
/*
is = conn.getInputStream();
textStatus.setText("Reading 0 bytes...");
Reader reader = null;
reader = new InputStreamReader(is,
"UTF-8");
while (reader.read(buffer)!=-1){
String a = new String(buffer);
htmlText += a;
textStatus.setText("Reading "+
htmlText.length()
+ " bytes");
a = null;
}
is.close();
if (htmlText.length()<100){
textStatus.setText("Error:
Reading Interrupted");
} else {
FileWriter
fw
=
new
FileWriter(file);
fw.write(htmlText.toCharArray());
fw.close();
textStatus.setText("Success");
}
} catch (MalformedURLException e) {
textStatus.setText("Error:
"
e.getMessage());
+
} catch (IOException e) {
textStatus.setText("Error:
"+
} catch (Exception e){
textStatus.setText("Error:
"+
e.getMessage());
e.getMessage());
}
} else {
textStatus.setText("Success");
}
}
}.start();
}
public static void translateUsingGoogle(JTextField status,
String nameOfFile, String urlName){
final JTextField textStatus = status;
final String name = nameOfFile;
final String myURL = urlName;
new Thread(){
@Override
public void run(){
translationText = "";
File file=null;
boolean fileNotFound = false;
try {
file = new File(name);
FileReader fr = new FileReader(file);
char[] chars = new char[(int) file.length()];
fr.read(chars);
translationText = new String(chars);
fr.close();
} catch (FileNotFoundException e) {
fileNotFound = true;
} catch (IOException e){
e.printStackTrace();
}
if (fileNotFound){
URL url;
InputStream is = null;
char[] buffer = new char[4096];
//textStatus.setText("Connecting...");
try {
//String
myURL="http://simple.m.wiktionary.org/wiki/Wiktionary:Extended_Basic_English_
alphabetical_wordlist";
url = new URL(myURL);
HttpURLConnection
conn
=
(HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000
/*
milliseconds */);
conn.setConnectTimeout(15000
/*
milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.addRequestProperty("User-Agent",
"Mozilla/4.0
(compatible;
MSIE 6.0; Windows NT 5.0)");
conn.connect();
is = conn.getInputStream();
textStatus.setText("Reading 0 bytes...");
Reader reader = null;
reader = new InputStreamReader(is,
"UTF-8");
while (reader.read(buffer)!=-1){
String a = new String(buffer);
translationText += a;
textStatus.setText("Reading "+
translationText.length() + " bytes");
a = null;
}
is.close();
if (translationText.length()<100){
textStatus.setText("Error:
Reading Interrupted");
} else {
FileWriter
fw
=
new
FileWriter(file);
fw.write(translationText.toCharArray());
fw.close();
textStatus.setText("Success");
}
} catch (MalformedURLException e) {
textStatus.setText("Error:
"
+
e.getMessage());
} catch (IOException e) {
textStatus.setText("Error:
"+
} catch (Exception e){
textStatus.setText("Error:
"+
e.getMessage());
e.getMessage());
}
} else {
textStatus.setText("Success");
}
}
}.start();
}
}
HangmanManager
import java.util.Locale;
public class HangmanManager {
private String originalLine = "";
private String taggedLine = "";
private String displayedProblem = "";
private String underscoreTemplateProblem = "";
private String uniqueWords = "";
private int numberOfUniqueWords = 0;
private String answeredWords = "";
private boolean playing = true;
private int numberOfMaximumMiss = 0;
private int numberOfCurrentMiss = 0;
public HangmanManager(String problem) {
generateProblem(problem, true);
}
public void addDistractor(String distractor) {
generateProblem(distractor, false);
}
public String getOriginalLine() {
return originalLine;
}
public String getTaggedLine() {
return taggedLine;
}
public int getNumberOfUniqueWords() {
return numberOfUniqueWords;
}
public String getUniqueWords() {
return uniqueWords;
}
public String getDisplayedProblem() {
return displayedProblem;
}
public void setDisplayedProblem(String p) {
displayedProblem = p;
}
public String getAnsweredWords() {
return answeredWords;
}
public boolean isPlaying() {
return playing;
}
public void setPlaying(boolean state) {
playing = state;
}
public int getNumberOfMaximumMiss() {
return numberOfMaximumMiss;
}
public void setNumberOfMaximumMiss(int max) {
numberOfMaximumMiss = max;
numberOfCurrentMiss = max;
}
public int getNumberOfCurrentMiss() {
return numberOfCurrentMiss;
}
public void setNumberOfCurrentMiss(int max) {
numberOfCurrentMiss = max;
}
private void generateProblem(String line, boolean isProblem) {
line = line.replaceAll("\\(http\\:[\\w\\.\\/]+\\)\\.", "");
line = line.replaceAll("<p>", "");
line = line.replaceAll("</p>", "");
line = line.replaceAll("<([A-Za-z][A-Za-z0-9]*)\\b[^>]*>(.*?)</\\1>",
"$2"); // http ...
line = line.replaceAll(
"[(\\w\\s\\.\\+\\\\!\\@\\#]\\$\\%\\^\\&\\*\\(\\)\\_\\:\\;\\\"\\'\\/\\?\\<\\>]+\\(Reuters\\)[\\s]+\\-[\\s]+", "");
line = line.replaceAll(
"[(\\w\\s\\,]+\\(Reuters\\)[\\s]+\\-[\\s]+", "");
line = line.replaceAll("\\(Reuters\\)[\\s]+\\-[\\s]+", "");
if (isProblem) {
taggedLine = line;
originalLine = line;
originalLine = originalLine.replaceAll(
"([\\d]+)(\\-|\\s)1/2(\\s|\\-)", "$1and a half$3");
originalLine = originalLine.replaceAll("(\\s)1/2(\\s)", "$a
half");
originalLine = originalLine.replaceAll(
"([\\d]+)(\\-|\\s)1/4(\\s|\\-)",
"$1and
a
quarter$3");
originalLine = originalLine.replaceAll("(\\s)1/4(\\s)",
"$a quarter");
originalLine = originalLine.replaceAll("([\\d]+|[\\d]+\\.)\\-",
"$1 ");
//For correct pronunciation,
//it is assumed that
//every sentence never ends
//with an abbreviation.
originalLine = originalLine.replaceAll("\\bDr\\.\\s",
"doctor "); //Make Dr. is pronounced "doctor"
//and not pronounced "drive"
originalLine = originalLine.replaceAll("(\\w\\.[\\w\\.]+)\\.",
"$1"); //last dot in abbreviation is
//deleted to prevent confusion
//in pronunciation, especially
//if a capital letter follows
originalLine = originalLine.replaceAll("\\b([A-Za-z][A-Zaz])\\.\\b*",
"$1"); //prevent dot in 2-word abbreviation
//from
having
wrong
pronunciation
}
line = line.replaceAll("([\\d,]+)\\.([\\d]+)", "$1UUU$2");
line = line.replaceAll("([\\d]+)/([\\d]+)", "$1VVV$2");
line = line.replaceAll("([\\w]+),([\\w]+)", "$1WWW$2");
line = line.replaceAll("([\\w]+)'([\\w]+)", "$1XXX$2");
line = line.replaceAll("(\\w\\.[\\w\\.]+)\\.",
"$1&ZZABBRDOTZZ"); //last dot in abbreviation
line = line.replaceAll("\\b([A-Za-z][A-Za-z])\\.\\b*",
"$1&ZZABBRDOTZZ"); //prevent the dot in 2-letters
//abbreviation
from
being
// recognized as the endof-sentence dot
// in the next 2 lines of
code
line = line.replaceAll("\\.(\\s[A-Z]|\\s\"|\")", " ZZLASTDOTZZ$1");
if (line.lastIndexOf(".")!=-1){
line = line.substring(0, line.lastIndexOf("."))
+ " ZZLASTDOTZZ"
+ (line.length() > line.lastIndexOf(".") + 1 ?
line.substring(
line.lastIndexOf(".")
+
1,
line.length() ) : "");
}
line = line.replaceAll("\\.\\.\\.", "");
line = line.replaceAll("\\.", "ZZDOTZZ");
line = line.replaceAll("\\-", "ZZHYPHENZZ");
line = line.replaceAll("\\:", "ZZCOLONZZ");
line = line.replaceAll("\\&", "ZZAMPERSANDZZ");
line = line.replaceAll("\\/", "ZZSLASHZZ");
line = line.replaceAll("[\\s]+", " ");
line = line.replaceAll("\\$", "");
line
=
line.replaceAll("[\\.\\+\\\\!\\@\\#]\\$\\^\\&\\*\\(\\)\\_\\:\\;\\\"\\'\\/\\?\\<\\>]+", "");
line = line.replaceAll("[,\"\\(\\)\\%]+","");
line = line.replaceAll("\\sZZHYPHENZZ\\s", " ");
line = line.replaceAll("ZZHYPHENZZ", " ");
line = line.replaceAll("\\sZZCOLONZZ\\s", " ");
line = line.replaceAll("ZZCOLONZZ", " ");
line = line.replaceAll("ZZAMPERSANDZZ", "&");
line = line.replaceAll("ZZSLASHZZ", "/");
line = line.replaceAll("\\sZZLASTDOTZZ", " ");
line = line.replaceAll("ZZDOTZZ", ".");
line = line.replaceAll("&ZZABBRDOTZZ", ".");
line = line.replaceAll("([\\d,]+)UUU([\\d]+)", "$1.$2");
line = line.replaceAll("([\\d]+)VVV([\\d]+)", "$1/$2");
line = line.replaceAll("([\\w]+)WWW([\\w]+)", "$1,$2");
line = line.replaceAll("([\\w]+)XXX([\\w]+)", "$1'$2");
line = line.trim();
if (isProblem) {
taggedLine = taggedLine.replaceAll("[\\s]+", " ");
taggedLine = taggedLine.replaceAll("([\\d,]+)\\.([\\d]+)",
"$1UUU$2");
taggedLine
=
taggedLine.replaceAll("([\\d]+)/([\\d]+)",
"$1VVV$2");
taggedLine
=
taggedLine.replaceAll("([\\w]+),([\\w]+)",
"$1WWW$2");
taggedLine
=
taggedLine.replaceAll("([\\w]+)'([\\w]+)",
"$1XXX$2");
taggedLine
=
taggedLine.replaceAll("\\.\\.\\.",
"ZZELLIPSISZZ");
//It is assumed that every sentence is not
//ended by an abbreviation.
taggedLine = taggedLine.replaceAll("(\\w\\.[\\w\\.]+)\\.",
"$1&ZZABBRDOTZZ");
//last
dot
in
abbreviation
taggedLine
=
taggedLine.replaceAll("\\b([A-Za-z][A-Za-
z])\\.\\b*",
"$1&ZZABBRDOTZZ"); //prevent dot in 2word abbreviation
//from
being
recognized as
//
end
of
sentence dot
// in the next 2
lines of code
taggedLine = taggedLine.replaceAll("\\.(\\s[A-Z]|\\s\"|\")",
" ZZLASTDOTZZ$1");
if (taggedLine.lastIndexOf(".")!=-1){
taggedLine
=
taggedLine.substring(0,
taggedLine.lastIndexOf("."))
+ " ZZLASTDOTZZ"
+
(taggedLine.length()
>
taggedLine.lastIndexOf(".") + 1 ? taggedLine
.substring(taggedLine.lastIndexOf(".") +
1,
taggedLine.length() ) : "");
}
taggedLine = taggedLine.replaceAll("\\.", "ZZDOTZZ");
taggedLine = taggedLine.replaceAll("\\sZZLASTDOTZZ",
".");
taggedLine = taggedLine.replaceAll("ZZELLIPSISZZ", "...");
displayedProblem = taggedLine.replaceAll("[\\w\\&\\/]+", "_");
underscoreTemplateProblem = displayedProblem;
taggedLine
=
taggedLine.replaceAll("([\\w\\&\\/]+)",
"@@@$1###");
taggedLine
=
taggedLine.replaceAll("&ZZABBRDOTZZ",
".");
taggedLine = taggedLine.replaceAll("([\\d,]+)UUU([\\d]+)",
"$1.$2");
taggedLine
=
taggedLine.replaceAll("([\\d]+)VVV([\\d]+)",
"$1/$2");
taggedLine = taggedLine.replaceAll("([\\w]+)WWW([\\w]+)",
"$1,$2");
taggedLine = taggedLine.replaceAll("([\\w]+)XXX([\\w]+)",
"$1'$2");
taggedLine = taggedLine.replaceAll("ZZDOTZZ", ".");
}
line = line.replaceAll("[\\s]+", " ");
line = line.toLowerCase(Locale.US) + " ";
if (isProblem) {
uniqueWords = " ";
}
int found = -1;
int oldFound = -1;
do {
oldFound = found;
found = line.indexOf(" ", found + 1);
if (found != -1) {
if (oldFound == -1) {
if (isProblem) {
uniqueWords = line.substring(0, found)
+ " ";
numberOfUniqueWords++;
} else {
String word = line.substring(oldFound +
1, found)
.toLowerCase(Locale.US);
if (!(" " + uniqueWords).contains(" " +
word + " ")) {
uniqueWords += word + " ";
numberOfUniqueWords++;
}
}
} else {
String word = line.substring(oldFound + 1,
found)
.toLowerCase(Locale.US);
if (!(" " + uniqueWords).contains(" " + word + "
")) {
uniqueWords += word + " ";
numberOfUniqueWords++;
}
}
}
} while (found != -1);
}
public boolean isAnwerCorrect(String word) {
answeredWords += word + " ";
int wordPosition = -1;
boolean found = false;
do {
wordPosition = taggedLine.toLowerCase(Locale.US).indexOf(
"@@@" + word + "###", wordPosition + 1);
if (wordPosition != -1) {
int endOfWordPosition = -1;
int numberOfWord = 0;
do {
endOfWordPosition = (taggedLine + "
").toLowerCase(
Locale.US).indexOf("###",
endOfWordPosition + 1);
if (endOfWordPosition != -1) {
numberOfWord++;
if (endOfWordPosition > wordPosition)
{
int wordPositionInTemplate = -1;
for (int i = 0; i < numberOfWord;
i++) {
wordPositionInTemplate
= underscoreTemplateProblem
.indexOf("_",
wordPositionInTemplate + 1);
}
String foundWord = "";
int newpos = 0;
foundWord
=
underscoreTemplateProblem
=
.substring(
0, (newpos
=
taggedLine.substring(wordPosition + 3,
taggedLine.indexOf("###", wordPosition));
underscoreTemplateProblem
underscoreTemplateProblem
.indexOf("_",
wordPositionInTemplate - 1)))
+ foundWord
+
underscoreTemplateProblem
.substring(newpos);
endOfWordPosition = -1;
found = true;
}
}
} while (endOfWordPosition != -1);
}
} while (wordPosition != -1);
displayedProblem
underscoreTemplateProblem.replaceAll("([\\w\\.]+)_",
"$1");
if (found) {
return true;
} else {
return false;
}
}
public boolean isAllWordsAnswered() {
if (!displayedProblem.contains("_")) {
=
return true;
} else {
return false;
}
}
}
Download