Guest User

Untitled

a guest
Mar 17th, 2012
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.43 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package test3;
  6.  
  7. import java.awt.event.ActionEvent;
  8. import java.awt.event.ActionListener;
  9. import java.util.ArrayList;
  10. import java.util.Random;
  11. import javax.swing.Timer;
  12.  
  13. /**
  14.  *
  15.  * @author Nomi
  16.  */
  17. public class NewJFrame extends javax.swing.JFrame {
  18.  
  19.     ActionListener timerListener; // Swing's timer listens to timerListener.
  20.     private String currentRandomWord = ""; // User will see this word with a vowel pulled out at random position.
  21.     private String userInput = ""; // Get the user input.
  22.     Game1 g = new Game1(); // Game1 has the words list.
  23.     private int minutes = 1; // This is how long the game will last in minutes. Make it final?
  24.     private int seconds = 60; // This is how long the game will last in seconds. Make it final?
  25.     private final int milliSecond = 1000;
  26.     javax.swing.Timer timer; // Swing's timer
  27.  
  28.     /*
  29.      * Sets up the timer Each event is fired at a second's interval.
  30.      */
  31.     public void setupTimer() {
  32.         System.out.println("going in setupTimer"); // For Debugging. To be taken out.
  33.         // labelRandomWord.setText(g1.getRandomWord());
  34.         // This should go in a better place?
  35.         labelTimer.setText(minutes + ":" + seconds); // Sets up the labelTimer.
  36.         timerListener = new ActionListener() {
  37.  
  38.             public void actionPerformed(ActionEvent e) {
  39.                 javax.swing.SwingUtilities.invokeLater(new updateTimer());
  40.             }
  41.         };
  42.         timer = new Timer(milliSecond, timerListener); // Each event is fired at a second's interval. Make the second final?
  43.         currentRandomWord = g.getRandomWord().toLowerCase();
  44.         labelRandomWord.setText(g.takeArandomVowelOut(currentRandomWord));
  45.         timer.start(); // Starts the timer.
  46.     }
  47.  
  48.     /*
  49.      * Timer uses a thread. Can sleep the thread too?
  50.      */
  51.     private class updateTimer implements Runnable {
  52.  
  53.         public void run() {
  54.             System.out.println("going in run()"); // For debugging. To be taken out.
  55.             seconds--;
  56.             if (seconds <= 0) {
  57.                 seconds = 60;
  58.                 minutes--;
  59.                 if (minutes < 0) {
  60.                     timer.stop();
  61.                 }
  62.             }
  63.             if (timer.isRunning()) {
  64.                 userTest();
  65.             }
  66.             labelTimer.setText(minutes + ":" + seconds);
  67.             if (!timer.isRunning()) {
  68.                 labelTimer.setText("Time's up");
  69.                 textFieldWordInput.setEditable(false);
  70.                 textFieldWordInput.setEnabled(false);
  71.             }
  72.         }
  73.     }
  74.  
  75.     public void userTest() {
  76.         System.out.println(currentRandomWord);
  77.        
  78.         // This listens if the user has hit enter
  79.         // Need to go over the game rules.
  80.         // What to do if the user inputs a wrong word?
  81.         // For now I will generate a new random word, maybe come back to it later?
  82.         textFieldWordInput.addActionListener(new ActionListener() {
  83.  
  84.             public void actionPerformed(ActionEvent e) {
  85.                 userInput = textFieldWordInput.getText();
  86.                 if ((userInput.equalsIgnoreCase(currentRandomWord)) || (g.check(userInput))) {
  87.                     System.out.println("Test 1");
  88.                     //textFieldWordInput.setText("");
  89.                     labelStatus.setText("Word Exists");
  90.                     currentRandomWord = g.getRandomWord();
  91.                     labelRandomWord.setText(g.takeArandomVowelOut(currentRandomWord));
  92.                 } else {
  93.                     System.out.println("Test 2");
  94.                     labelStatus.setText("Word Does Not Exists");
  95.                     textFieldWordInput.setText("");
  96.                 }
  97.                 //textFieldWordInput.setText("");
  98.             }
  99.         });
  100.     }
  101.  
  102.     /**
  103.      * Creates new form NewJFrame
  104.      */
  105.     public NewJFrame() {
  106.         g.buildList();
  107.         initComponents();
  108.         setupTimer();
  109.     }
  110.  
  111.     /**
  112.      * This method is called from within the constructor to initialize the form.
  113.      * WARNING: Do NOT modify this code. The content of this method is always
  114.      * regenerated by the Form Editor.
  115.      */
  116.     @SuppressWarnings("unchecked")
  117.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  118.     private void initComponents() {
  119.  
  120.         labelRandomWord = new javax.swing.JLabel();
  121.         textFieldWordInput = new javax.swing.JTextField();
  122.         labelTimer = new javax.swing.JLabel();
  123.         labelStatus = new javax.swing.JLabel();
  124.  
  125.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  126.  
  127.         labelRandomWord.setText("jLabel1");
  128.  
  129.         textFieldWordInput.addActionListener(new java.awt.event.ActionListener() {
  130.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  131.                 textFieldWordInputActionPerformed(evt);
  132.             }
  133.         });
  134.  
  135.         labelTimer.setText("jLabel2");
  136.  
  137.         labelStatus.setText("jLabel1");
  138.  
  139.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  140.         getContentPane().setLayout(layout);
  141.         layout.setHorizontalGroup(
  142.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  143.             .addGroup(layout.createSequentialGroup()
  144.                 .addContainerGap()
  145.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  146.                     .addComponent(labelRandomWord, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  147.                     .addComponent(textFieldWordInput, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE))
  148.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 150, Short.MAX_VALUE)
  149.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  150.                     .addComponent(labelTimer, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
  151.                     .addComponent(labelStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  152.                 .addContainerGap())
  153.         );
  154.         layout.setVerticalGroup(
  155.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  156.             .addGroup(layout.createSequentialGroup()
  157.                 .addContainerGap()
  158.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  159.                     .addComponent(labelRandomWord)
  160.                     .addComponent(labelTimer))
  161.                 .addGap(18, 18, 18)
  162.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  163.                     .addComponent(textFieldWordInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  164.                     .addComponent(labelStatus))
  165.                 .addContainerGap(237, Short.MAX_VALUE))
  166.         );
  167.  
  168.         pack();
  169.     }// </editor-fold>                        
  170.  
  171.     private void textFieldWordInputActionPerformed(java.awt.event.ActionEvent evt) {                                                  
  172.         // TODO add your handling code here:
  173.     }                                                  
  174.  
  175.     /**
  176.      * @param args the command line arguments
  177.      */
  178.     public static void main(String args[]) {
  179.         /*
  180.          * Set the Nimbus look and feel
  181.          */
  182.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  183.         /*
  184.          * If Nimbus (introduced in Java SE 6) is not available, stay with the
  185.          * default look and feel. For details see
  186.          * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  187.          */
  188.         try {
  189.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  190.                 if ("Nimbus".equals(info.getName())) {
  191.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  192.                     break;
  193.  
  194.  
  195.                 }
  196.             }
  197.         } catch (ClassNotFoundException ex) {
  198.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  199.         } catch (InstantiationException ex) {
  200.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  201.         } catch (IllegalAccessException ex) {
  202.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  203.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  204.             java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  205.         }
  206.         //</editor-fold>
  207.  
  208.         /*
  209.          * Create and display the form
  210.          */
  211.         java.awt.EventQueue.invokeLater(new Runnable() {
  212.  
  213.             public void run() {
  214.                 new NewJFrame().setVisible(true);
  215.             }
  216.         });
  217.     }
  218.     // Variables declaration - do not modify                    
  219.     private javax.swing.JLabel labelRandomWord;
  220.     private javax.swing.JLabel labelStatus;
  221.     private javax.swing.JLabel labelTimer;
  222.     private javax.swing.JTextField textFieldWordInput;
  223.     // End of variables declaration                  
  224. }
  225.  
  226. /*
  227.  * To change this template, choose Tools | Templates
  228.  * and open the template in the editor.
  229.  */
  230. package test3;
  231.  
  232. import java.io.BufferedReader;
  233. import java.io.DataInputStream;
  234. import java.io.FileInputStream;
  235. import java.io.InputStream;
  236. import java.io.InputStreamReader;
  237. import java.util.ArrayList;
  238. import java.util.HashSet;
  239. import java.util.Random;
  240. import java.io.File;
  241.  
  242. /**
  243.  *
  244.  * @author Nomi
  245.  */
  246. public class Game1 {
  247.  
  248.     public ArrayList<String> wordsList = new ArrayList<String>();
  249.     private ArrayList<Integer> randomIntegers = new ArrayList<Integer>(); // Store random words so we don't get repeats.
  250.     private final int randomWordSize = 71447; // Change it back to 71447
  251.     private ArrayList<Integer> saveRandom = new ArrayList<Integer>();
  252.     private Random random = new Random();
  253.  
  254.     public void buildList() {
  255.         try {
  256.             File dir1 = new File(".");
  257.             System.out.println("Current dir : " + dir1.getCanonicalPath());
  258.             InputStream in = getClass().getResourceAsStream("SINGLE.txt");
  259.             //FileInputStream fstream = new FileInputStream(getClass().getResource("SINGLE.txt"));
  260.             //DataInputStream in = new DataInputStream(fstream);
  261.             BufferedReader br = new BufferedReader(new InputStreamReader(in));
  262.             String strLine = "";
  263.             while ((strLine = br.readLine()) != null) {
  264.                 if (strLine.length() >= 5 && strLine.length() <= 9) {
  265.                     wordsList.add(strLine);
  266.                 }
  267.             }
  268.             System.out.println("Success");
  269.             getRandomWordsListSize();
  270.         } catch (Exception e) {
  271.             System.out.println("Words of length between 5 and 9 were not added to the arrayList.");
  272.             e.printStackTrace();
  273.         }
  274.     }
  275.  
  276.     public boolean check(String word) {
  277.        
  278.         for (int i = 0; i < wordsList.size(); i++) {
  279.             if (word.equalsIgnoreCase(wordsList.get(i))) {
  280.                 return true;
  281.             }
  282.         }
  283.         return false;
  284.     }
  285.  
  286.     // Maybe make this final?
  287.     public int getRandomWordsListSize() {
  288.         return randomWordSize;
  289.     }
  290.  
  291.     // I don't think this method is doing what I think it is.
  292.     // Should test this method throughly.
  293.     // For now this suffice.
  294.     public String getRandomWord() {
  295.         int temp = random.nextInt(randomWordSize);
  296.         // I am actually not 100% sure what this if statement is doing.
  297.         // Should test to make sure. Is this saying
  298.         // generate a random number until a new number has
  299.         // has not been generated that was not in the
  300.         // randomIntegers list?
  301.         if (randomIntegers.contains(temp)) {
  302.             temp = random.nextInt(randomWordSize);
  303.         }
  304.         randomIntegers.add(temp);
  305.         return wordsList.get(temp);
  306.     }
  307.  
  308.     public String takeArandomVowelOut(String word) {
  309.         ArrayList<Integer> vowelPositions = new ArrayList<Integer>();
  310.         char cTemp;
  311.         int temp = 0;
  312.         int temp2 = 0;
  313.         for (int i = 0; i < word.length(); i++) {
  314.             cTemp = word.toLowerCase().charAt(i);
  315.             if (cTemp == 'a' || cTemp == 'e' || cTemp == 'i' || cTemp == 'o' || cTemp == 'u' || cTemp == 'y') {
  316.                 vowelPositions.add(i);
  317.             }
  318.         }
  319.         System.out.println(word);
  320.         System.out.println("vowelPositions.size = " + vowelPositions.size());
  321.         temp = random.nextInt(vowelPositions.size());
  322.         temp2 = vowelPositions.get(temp);
  323.         String sTemp = word.substring(0, temp2);
  324.         sTemp = sTemp.concat(word.substring(temp2 + 1, word.length()));
  325.         vowelPositions.clear();
  326.         return sTemp;
  327.     }
  328.    
  329.     public String getWord(int i)
  330.     {
  331.         return wordsList.get(i);
  332.     }
  333.    
  334.     /**
  335.      * @param args the command line arguments
  336.      */
  337. //    public static void main(String[] args)
  338. //    {
  339. //        // TODO code application logic here
  340. //        Game1 gg = new Game1();
  341. //        gg.takeAvowelOut("white");
  342. //    }
  343. }
Advertisement
Add Comment
Please, Sign In to add comment