/* ** Pairs sample applet ** ** by (c) Copyright 2001 Simon Huggins ** ** For demonstration purposes only. ** ** You may use this applet on your web site, but it cannot be ** sold in either its original or altered state. ** This original notice must be included in all versions of ** the applet distributed, even if altered. ** ** The author accepts no liability for any difficulties or loss ** arising from use of this applet. It is primarily intended for ** demonstration purposes. ** ** Change History ** ~~~~~~~~~~~~~~ ** 01-Oct-2001 v1.0 Release version */ /* ** Import section - tells the compiler where to look for different classes ** used within this file */ import java.awt.event.*; import javax.swing.*; import java.awt.*; /* ** Defines a class called Pairs which takes the basic JApplet ** class as a template, and adds to it to create our Applet. ** Also implementing ActionListener interface for mouse clicks */ public class Pairs extends JApplet implements ActionListener { JButton buttons[]; // array of buttons to appear on grid int buttonValues[]; // values of those buttons (hidden) int squaresAcross = 4, squaresDown = 4; // default grid size int firstSelection = -1; // first value index selected of pair boolean oneSelected = false; // has first of pair been selected? JButton firstButton,secondButton; // last pair of buttons selected /* ** Initialize the applet - i.e. set up any values before processing begins */ public void init() { /* Get number of buttons across and down from HTML parameters */ String squaresAcrossString = getParameter("squaresAcross"); if(squaresAcrossString != null) // check if the parameter was used squaresAcross = Integer.parseInt(squaresAcrossString); String squaresDownString = getParameter("squaresDown"); if(squaresDownString != null) // check if the parameter was used squaresDown = Integer.parseInt(squaresDownString); /* Set up a grid layout holding the given number of squares across and down */ getContentPane().setLayout(new GridLayout(squaresDown,squaresAcross)); int buttonCount = squaresDown * squaresAcross; // store this for easy reference /* Set up the arrays to hold JButtons and their hidden values to match the grid */ buttons = new JButton[buttonCount]; buttonValues = new int[buttonCount]; /* Set up pairs of numbers in the buttonValues array in sequential order */ for (int i=0 ; i < buttonCount ; i++) buttonValues[i] = (int)((i+2)/2.0); /* Randomize the ordering of buttonValues by swapping values around */ for (int i=0 ; i < buttonCount ; i++) { int swapFirst = (int)(Math.random() * buttonCount); int swapSecond = (int)(Math.random() * buttonCount); int swapValue = buttonValues[swapFirst]; buttonValues[swapFirst] = buttonValues[swapSecond]; buttonValues[swapSecond] = swapValue; } /* Add all the buttons to the content pane from the buttons array. Note that each button is givena name buttonx where x is the number corresponding to the buttonValues array - this is used later */ for (int i=0;i