home *** CD-ROM | disk | FTP | other *** search
/ Java Developer's Companion / Java Developer's Companion.iso / documentation / tutorial / intl / stepbystep / example-1.1 / WordMatch.java < prev   
Encoding:
Java Source  |  1997-07-13  |  16.2 KB  |  514 lines

  1. /*
  2.  * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
  3.  *
  4.  * Permission to use, copy, modify, and distribute this software
  5.  * and its documentation for NON-COMMERCIAL purposes and without
  6.  * fee is hereby granted provided that this copyright notice
  7.  * appears in all copies. Please refer to the file "copyright.html"
  8.  * for further important copyright and licensing information.
  9.  *
  10.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  11.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  12.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  13.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  14.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  15.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  16.  */
  17. /*
  18.  * @(#)WordMatch.java    1.5  25 Oct 1995 11:07:56
  19.  * @author Patrick Chan
  20.  *
  21.  * Copyright (c) 1994-1995 Sun Microsystems, Inc. All Rights Reserved.
  22.  *
  23.  * Permission to use, copy, modify, and distribute this software
  24.  * and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and
  25.  * without fee is hereby granted. 
  26.  * Please refer to the file http://java.sun.com/copy_trademarks.html
  27.  * for further important copyright and trademark information and to
  28.  * http://java.sun.com/licensing.html for further important licensing
  29.  * information for the Java (tm) Technology.
  30.  * 
  31.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  32.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  33.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  34.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  35.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  36.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  37.  * 
  38.  * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
  39.  * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
  40.  * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
  41.  * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
  42.  * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
  43.  * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
  44.  * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES").  SUN
  45.  * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
  46.  * HIGH RISK ACTIVITIES.
  47.  */
  48.  
  49. import java.awt.*;
  50. import java.applet.*;
  51. import java.awt.*;
  52. import java.awt.event.*;
  53. import java.util.*;
  54.  
  55. public class WordMatch extends Applet 
  56.         implements ActionListener, ItemListener {
  57.  
  58.     // Number of displayed cards and words.
  59.     int numCards = 4;
  60.  
  61.     // Currently selected language.
  62.     int curLanguage;
  63.  
  64.     // card[i] refers to the i'th word.
  65.     int cards[];
  66.  
  67.     // words[i] refers to the i'th card.
  68.     int words[];
  69.  
  70.     // Currently selected card.
  71.     int curCard;
  72.  
  73.     // The components.
  74.     Box soundBox;
  75.     List languageList = new List();
  76.     Label statusBar = new Label("Ready");
  77.     Button scoreButton;
  78.     Box[] cardBoxes;
  79.     Box[] wordBoxes;
  80.  
  81.     // If true, the user has successfully matched all the words.
  82.     boolean done;
  83.     
  84.     // links[i] == j -> cards[i] is linked to words[j].
  85.     int links[];
  86.  
  87.     // Images of pictures.  There is one image for each different word.
  88.     Image images[];
  89.  
  90.     // The dimensions of the images.  They must all be the same size.
  91.     int imageW, imageH;
  92.  
  93.     int numWords;
  94.  
  95.     // Width of language list.
  96.     int languageListW = 120;
  97.  
  98.     // Used to layout the components.
  99.     int gap = 10;
  100.  
  101.     /**
  102.      * Initialize the applet. Resize and load images.
  103.      */
  104.     public void init() {
  105.         imageW = Integer.parseInt(getParameter("image-w"));
  106.         imageH = Integer.parseInt(getParameter("image-h"));
  107.  
  108.         numWords = dictionary[0].length;
  109.  
  110.         // Create data structures.
  111.         cards = new int[numCards];
  112.         cardBoxes = new Box[numCards];
  113.         words = new int[numCards];
  114.         wordBoxes = new Box[numCards];
  115.         links = new int[numCards];
  116.         images = new Image[numWords];
  117.         curLanguage = 0;
  118.  
  119.         // Load the images.
  120.         for (int i=0; i<numWords; i++) {
  121.         images[i] = getImage(getCodeBase(), "rsrc/"
  122.         + dictionary[0][i] + ".gif");
  123.         }
  124.  
  125.         // Layout the components.  Use absoluting positioning.
  126.         setLayout(null);
  127.  
  128.         // Setup the score button.
  129.         scoreButton = new Button("Score");
  130.         add(scoreButton);
  131.         Dimension d = scoreButton.getPreferredSize();
  132.         scoreButton.setBounds(0, getSize().height-d.height, 
  133.             languageListW, d.height);
  134.         scoreButton.addActionListener(this);
  135.  
  136.         // Setup the language list.
  137.     for (int i = 0; i < languages.length; i ++) {
  138.         languageList.add(languages[i]);
  139.     }
  140.         add(languageList);
  141.         languageList.setBounds(0, 0, 
  142.             languageListW, getSize().height-d.height);
  143.         languageList.addItemListener(this);
  144.         languageList.select(curLanguage);
  145.  
  146.     // Setup the status bar.
  147.         add(statusBar);
  148.         statusBar.setBounds(languageListW+2*gap, getSize().height-d.height, 
  149.             getSize().width-languageListW-2*gap, d.height);
  150.  
  151.         // Setup sound box.
  152.         soundBox = new Box(getImage(getCodeBase(), "rsrc/sound.gif"));
  153.         add(soundBox);
  154.         soundBox.addItemListener(this);
  155.         soundBox.setBounds(0, 0, 32, 32);
  156.  
  157.     Font f = new Font("SansSerif", Font.PLAIN, 16);
  158.         for (int i=0; i<numCards; i++) {
  159.             // Setup the picture cards.
  160.             cardBoxes[i] = new Box(images[cards[i]]);
  161.             add(cardBoxes[i]);
  162.             cardBoxes[i].setBounds(languageListW+2*gap, 
  163.                 i*(imageH+gap), imageW, imageH);
  164.             cardBoxes[i].addItemListener(this);
  165.             cardBoxes[i].select(i == 0);
  166.  
  167.             // Setup up the word boxes.
  168.             wordBoxes[i] = new Box(dictionary[curLanguage][words[i]], f);
  169.             add(wordBoxes[i]);
  170.             wordBoxes[i].setBounds(languageListW+4*gap+2*imageW, 
  171.                 i*(imageH+gap), getSize().width, imageH);
  172.             wordBoxes[i].addItemListener(this);
  173.         }
  174.  
  175.         moveSoundBox();
  176.         newRound();
  177.     }
  178.  
  179.     /**
  180.      * Paint the screen.
  181.      */
  182.     public void paint(Graphics g) {
  183.         int x, y;
  184.  
  185.         // Paint links.
  186.         g.setColor(Color.black);
  187.         for (int i=0; i<numCards; i++) {
  188.             if (links[i] >= 0) {
  189.                 Point pt1 = cardBoxes[i].getLocation();
  190.                 Point pt2 = wordBoxes[links[i]].getLocation();
  191.  
  192.                 pt1.translate(imageW+gap, imageH/2);
  193.                 pt2.translate(-gap, imageH/2);
  194.  
  195.                 g.drawLine(pt1.x, pt1.y, pt2.x, pt2.y);
  196.             }
  197.     }
  198.     }
  199.  
  200.     public void itemStateChanged(ItemEvent evt) {
  201.         if (!done) {
  202.             statusBar.setText(null);
  203.         }
  204.         if (evt.getSource() == soundBox) {
  205.         play(getCodeBase(), "rsrc/" + dictionary[0][cards[curCard]] 
  206.         + "." + languages[curLanguage] + ".au");
  207.         }
  208.  
  209.         // Was the event fired from one of the picture cards?
  210.         for (int i=0; i<cardBoxes.length; i++) {
  211.             if (cardBoxes[i] == evt.getSource()) {
  212.             // In card box.
  213.                 cardBoxes[curCard].select(false);
  214.                 cardBoxes[i].select(true);
  215.                 curCard = i;
  216.  
  217.                 moveSoundBox();
  218.         repaint();
  219.                 break;
  220.         }
  221.         } 
  222.  
  223.         // Was the event fired from one of the words?
  224.         for (int i=0; i<wordBoxes.length; i++) {
  225.             if (wordBoxes[i] == evt.getSource()) {
  226.         // Break an old link if necessary.
  227.         for (int j=0; j<numCards; j++) {
  228.             if (links[j] == i) {
  229.             links[j] = -1;
  230.             }
  231.         }
  232.         links[curCard] = i;
  233.         repaint();
  234.             }
  235.         } 
  236.  
  237.         // Was the event fired from the language list?
  238.         if (evt.getSource() == languageList) {
  239.             curLanguage = languageList.getSelectedIndex();
  240.             for (int i=0; i<wordBoxes.length; i++) {
  241.                 wordBoxes[i].setText(dictionary[curLanguage][words[i]]);
  242.             }
  243.         }
  244.     }
  245.  
  246.     void moveSoundBox() {
  247.     // Move the sound box.
  248.     Point pt = cardBoxes[curCard].getLocation();
  249.     soundBox.setLocation(
  250.         pt.x+imageW-soundBox.getSize().width/2, 
  251.         pt.y+imageH-soundBox.getSize().height/2);
  252.     }
  253.  
  254.     public void actionPerformed(ActionEvent evt) {
  255.         if (evt.getSource() == scoreButton) {
  256.             if (done) {
  257.             scoreButton.setLabel("Score");
  258.                 newRound();
  259.                 repaint();
  260.             }
  261.             int count = 0;
  262.             for (int i=0; i<numCards; i++) {
  263.                 if (links[i] == -1) {
  264.                     statusBar.setText("You have not yet matched all the words.");
  265.                     return;
  266.                 }
  267.                 if (cards[i] == words[links[i]]) {
  268.                     count++;
  269.                 }
  270.             }
  271.             if (count == numCards) {            
  272.         statusBar.setText("Congratulations, they're all right!");
  273.                 done = true;
  274.                 scoreButton.setLabel("New Game");
  275.             } else if (count == 1) {
  276.         statusBar.setText("There is only 1 correct match.");
  277.             } else if (count == 0) {
  278.         statusBar.setText("There are no correct matches.");
  279.             } else {
  280.         statusBar.setText("There are " + count + " correct matches.");
  281.             }
  282.         }
  283.     }
  284.  
  285.     /**
  286.      * Starts a new round.
  287.      */
  288.     public void newRound() {
  289.         boolean[] picked = new boolean[numWords];
  290.  
  291.         statusBar.setText(null);
  292.         done = false;
  293.  
  294.         // Pick new cards.
  295.         for (int i=0; i<numCards; i++) {
  296.         while (true) {
  297.                 int r = (int)Math.floor(Math.random() * numWords);
  298.  
  299.                 if (!picked[r]) {
  300.                 cards[i] = r;
  301.                 words[i] = r;
  302.                 links[i] = -1;
  303.                 picked[r] = true;
  304.                     break;
  305.                 }
  306.             }
  307.     }
  308.  
  309.         // Scramble the pictures
  310.         for (int i=0; i<100; i++) {
  311.         int r = (int)Math.floor(Math.random() * numCards);
  312.             int t = cards[r];
  313.  
  314.             cards[r] = cards[i%numCards];
  315.             cards[i%numCards] = t;
  316.         }
  317.  
  318.  
  319.     // Initialize the new pictures and words.
  320.     for (int i=0; i<numCards; i++) {
  321.         cardBoxes[i].setImage(images[cards[i]]);
  322.         wordBoxes[i].setText(dictionary[curLanguage][words[i]]);
  323.     }
  324.     }
  325.  
  326.  
  327.     // Added by K.A. Smith 10/25/95 
  328.     public String getAppletInfo() {
  329.        return "Author: Patrick Chan\nVersion: 2.0, June 1 1997";
  330.     }
  331.     /* List of words in various languages */
  332.     String englishWords[] = {
  333.         "house", "book", "java", "lips", "airplane", "UnitedStates",
  334.         "apple", "clock", "phone", "star", "flower", "television",
  335.         "car", "dog", "bug", "bird"};
  336.     String cantoneseWords[] = {
  337.         "fohng uk", "syu", "ga fe", "seuhn", "fei gei", "meih gwok",
  338.         "pihng gwo", "jung", "dihn wa", "sing", "fa", "dihn sih",
  339.         "che", "gau", "chuhng", "jeuk"};
  340.     String dutchWords[] = {
  341.         "huis", "boek", "koffie", "lippen", "vliegtuig", "Verenigde Staten",
  342.         "appel", "klok", "telefoon", "ster", "bloem", "televisie",
  343.         "auto", "hond", "insekt", "vogel"};
  344.     String frenchWords[] = {
  345.         "maison", "livre", "cafe", "levres", "avion", "Etats Unis",
  346.         "pomme", "horloge", "telephone", "astre", "fleur", "television",
  347.         "voiture", "chien", "insecte", "oiseaux"};
  348.     String germanWords[] = {
  349.         "Haus", "Buch", "Kaffee", "Lippen", "Flugzeug", "Vereinigte Staaten",
  350.         "Apfel", "Uhr", "Telephon", "Stern", "Blume", "Fernsehgeraet",
  351.         "Auto", "Hund", "Kaefer", "Vogel"};
  352.     String geekspeakWords[] = {
  353.         "lab", "FM (of RTFM)", "Peet's", "programming languages", "wings", "www.usa.com",
  354.         "food", "MHz", "cellular", "splat (aka asterisk)", "inflorescence", "tube",
  355.         "wheels", "386", "feature", "finger"};
  356.     String hebrewWords[] = {
  357.         "ba'it", "sefer", "java", "s'fata'im", "matos", "ar'tzot ha'brit",
  358.         "tapu'ach", "sha'on", "tele'phon", "kochav", "pe'rach", "televizia",
  359.         "m'chonit", "kelev", "cha'rak", "tsipor"};
  360.     String hindiWords[] = {
  361.         "ghar", "kitab", "coffee", "honth", "hawai jahaj", "America",
  362.         "seb", "ghadi", "doorbhash", "sitara", "phool", "television",
  363.         "gaadi", "kutta", "keeda", "chidiya"};
  364.     String italianWords[] = {
  365.         "house", "book", "coffee", "lips", "airplane", "UnitedStates",
  366.         "apple", "clock", "phone", "star", "flower", "television",
  367.         "car", "dog", "bug", "bird"};
  368.     String japaneseWords[] = {
  369.         "ie", "hon", "kouhii", "kuchibiru", "hikouki", "Amerika",
  370.         "ringo", "tokei", "denwa", "hoshi", "hana", "terebi",
  371.         "kuruma", "inu", "mushi", "tori"};
  372.     String mandarinWords[] = {
  373.         "fang wu", "shu", "ka fei", "chun", "fei ji", "mei guo",
  374.         "ping guo", "zhong", "dian hua", "xing", "hua", "dian shi",
  375.         "che", "gou", "chong", "niao"};
  376.     String portugueseWords[] = {
  377.         "casa", "livro", "cafe", "lapios", "aviao", "Estados Unidos",
  378.         "maca", "relogio", "telefone", "estrela", "flor", "televisao",
  379.         "carro", "cachorro", "bicho", "passarinho"};
  380.     String pigLatinWords[] = {
  381.         "ouse-hay", "ook-bay", "ava-jay", "ips-lay", "airplane-gay", "United-gay Ates-Stay",
  382.         "apple-gay", "ock-clay", "one-phay", "ar-stay", "ower-flay", "elevision-tay",
  383.         "ar-cay", "og-day", "ug-bay", "ird-bay"};
  384.     String spanishWords[] = {
  385.         "casa", "libro", "cafe", "labios", "avion", "Estados Unidos",
  386.         "manzana", "reloj", "telefono", "estrella", "flor", "television",
  387.         "coche", "perro", "insecto", "pajaro"};
  388.     String swissGermanWords[] = {
  389.         "Huus", "Buech", "Cafi", "Lippe", "Flugzueg", "Vereinigti Staate",
  390.         "Oepfel", "Uhr", "Telephon", "Stern", "Blueme", "Fernsehapparat",
  391.         "Auto", "Hund", "Chaefer", "Vogel"};
  392.  
  393.     /* List of languages. */
  394.     String languages[] = {
  395.         "English",
  396.         "Cantonese",
  397.         "Dutch",
  398.         "French",
  399.         "Geekspeak",
  400.         "German",
  401.         "Hebrew",
  402.         "Hindi",
  403.         "Japanese",
  404.         "Mandarin",
  405.         "PigLatin",
  406.         "Portuguese",
  407.         "Spanish",
  408.         "SwissGerman"};
  409.  
  410.     String dictionary[][] = {
  411.         englishWords,
  412.         cantoneseWords,
  413.         dutchWords,
  414.         frenchWords,
  415.         geekspeakWords,
  416.         germanWords,
  417.         hebrewWords,
  418.         hindiWords,
  419.         japaneseWords,
  420.         mandarinWords,
  421.         pigLatinWords,
  422.         portugueseWords,
  423.         spanishWords,
  424.         swissGermanWords};
  425. }
  426.  
  427. class Box extends Canvas implements ItemSelectable {
  428.     Font font;
  429.     Image image;
  430.     String string;
  431.     boolean selected;
  432.  
  433.     Box(Image image) {
  434.         this.image = image;
  435.         addMouseListener(new MouseEventHandler());
  436.     }
  437.  
  438.     Box(String string, Font f) {
  439.         this.string = string;
  440.         font = f;
  441.         addMouseListener(new MouseEventHandler());
  442.     }
  443.  
  444.     public void select(boolean s) {
  445.         selected = s;
  446.         repaint();
  447.     }
  448.  
  449.     public void setText(String s) {
  450.         string = s;
  451.         repaint();
  452.     }
  453.  
  454.     public void setImage(Image i) {
  455.         image = i;
  456.         repaint();
  457.     }
  458.  
  459.     public Object[] getSelectedObjects() {
  460.     Object[] result;
  461.         if (selected) {
  462.             result = new Object[1];
  463.             result[0] = this;
  464.         } else {
  465.             result = new Object[0];
  466.         }
  467.         return result;
  468.     }
  469.  
  470.     public void paint(Graphics g) {
  471.         int w = getSize().width;
  472.         int h = getSize().height;
  473.  
  474.         // If it's an image, paint it.
  475.         if (image != null) {
  476.             g.drawImage(image, 0, 0, this);
  477.  
  478.             if (selected) {
  479.                 g.setColor(Color.red);
  480.                 g.drawRect(0, 0, w-1, h-1);
  481.             }
  482.         }
  483.         // If it's a string, paint it.
  484.         if (string != null) {
  485.             g.setFont(font);
  486.             FontMetrics fontM = g.getFontMetrics();
  487.  
  488.         g.setColor(Color.black);
  489.         g.drawString(string, 0, (h-fontM.getHeight())/2+fontM.getAscent());
  490.         }
  491.     }
  492.  
  493.     class MouseEventHandler extends MouseAdapter {
  494.         public void mousePressed(MouseEvent evt) {
  495.         ItemEvent e = new ItemEvent(Box.this, 
  496.             ItemEvent.ITEM_STATE_CHANGED, string, ItemEvent.SELECTED);
  497.     
  498.         if (ItemListener != null) {
  499.             ItemListener.itemStateChanged(e);
  500.         }
  501.         }
  502.     }
  503.  
  504.     ItemListener ItemListener;
  505.     public synchronized void addItemListener(ItemListener l) {
  506.     ItemListener = AWTEventMulticaster.add(ItemListener, l);
  507.     }
  508.  
  509.     public synchronized void removeItemListener(ItemListener l) {
  510.     ItemListener = AWTEventMulticaster.remove(ItemListener, l);
  511.     }
  512.  
  513. }
  514.