jdalbey

GridGuess.java

Sep 20th, 2013
379
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.01 KB | None | 0 0
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.applet.*;
  4. /**
  5.  *  A simple grid guessing game
  6.  */
  7. public class GridGuess extends Applet implements ActionListener
  8. {
  9.     final static int BOARDSIZE = 5;
  10.     private Button[][] ButtonGrid = new Button[BOARDSIZE][BOARDSIZE];
  11.     private Panel p;
  12.     private Label NameLabel;
  13.     private int RowHideSpot, ColHideSpot;
  14.    
  15.     public void init() {
  16.      setLayout(new BorderLayout());    
  17.      p = new Panel();
  18.      p.setLayout(new GridLayout(BOARDSIZE,BOARDSIZE));
  19.        // Randomly select the solution
  20.        RowHideSpot = (int) ((BOARDSIZE-1)  * Math.random() );
  21.        ColHideSpot = (int) ((BOARDSIZE-1)  * Math.random() );
  22.      for(int r=0;r<BOARDSIZE;r++)
  23.       for(int c=0;c<BOARDSIZE;c++) {
  24.            Button button = new Button("");
  25.            if (r == RowHideSpot && c == ColHideSpot)
  26.                 button.setActionCommand("target");
  27.                 ButtonGrid[r][c] = button;
  28.                 ButtonGrid[r][c].setBackground(Color.WHITE);
  29.                 ButtonGrid[r][c].addActionListener(this);
  30.                 p.add(ButtonGrid[r][c]);
  31.       }
  32.      add(p,BorderLayout.CENTER);
  33.      
  34.      // Create label at the bottom
  35.      NameLabel = new Label();
  36.      add(NameLabel,BorderLayout.SOUTH);
  37.         NameLabel.setText("" + RowHideSpot  + " " + ColHideSpot);                                
  38.     }
  39.  
  40.     public void actionPerformed(ActionEvent e) {
  41.         Button b = (Button)e.getSource();
  42.                // if it's correct button
  43.                     b.setBackground(Color.BLUE);
  44.                     if (b.getActionCommand().equals("target")){
  45.                     NameLabel.setText("CORRECT!");
  46.                     b.setBackground(Color.GREEN);
  47.                     }
  48.                     else
  49.                         NameLabel.setText("Nope.");                
  50.              
  51.          
  52.     }
  53.     public void ErrorFound(String s) {
  54.         NameLabel.setText("Fatal error, " +
  55.                           "game terminated: " + s);
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment