import java.awt.*; import java.awt.event.*; import java.applet.*; /** * A simple grid guessing game */ public class GridGuess extends Applet implements ActionListener { final static int MAXTRIES = 5; private Button[][] ButtonGrid = new Button[5][5]; private Panel p; private Label NameLabel; private int RowHideSpot, ColHideSpot; public void init() { setLayout(new BorderLayout()); p = new Panel(); p.setLayout(new GridLayout(5,5)); for(int r=0;r<5;r++) for(int c=0;c<5;c++) { ButtonGrid[r][c] = new Button(""); ButtonGrid[r][c].setBackground(Color.WHITE); ButtonGrid[r][c].addActionListener(this); p.add(ButtonGrid[r][c]); } add(p,BorderLayout.CENTER); // Create label at the bottom NameLabel = new Label(); add(NameLabel,BorderLayout.SOUTH); // Randomly select the solution RowHideSpot = (int) (4 * Math.random() ); ColHideSpot = (int) (4 * Math.random() ); NameLabel.setText("" + RowHideSpot + " " + ColHideSpot); } public void actionPerformed(ActionEvent e) { Button b = (Button)e.getSource(); // Determine which button was pressed by // comparing all of them against the one who fired the event for(int r=0; r <5; r++) for(int c=0;c <5; c++) { // if this button fired the event, see if it's correct if (b == ButtonGrid[r][c]){ b.setBackground(Color.BLUE); if (r == RowHideSpot && c == ColHideSpot) { NameLabel.setText("CORRECT!"); b.setBackground(Color.GREEN); } else NameLabel.setText("Nope."); } } } public void ErrorFound(String s) { NameLabel.setText("Fatal error, " + "game terminated: " + s); } }