import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; import javafx.util.Duration; public class WhackAMouse extends Application { // constants private static final int BN_SIZE = 75; private static final int N_ROWS = 5; private static final int N_COLS = 7; private static final int APP_WIDTH = N_COLS * BN_SIZE; private static final int APP_HEIGHT = N_ROWS * BN_SIZE; private static final String IMG_NAME = "file:Mouse.gif"; // imgName private static final int INTERVAL = 500; // msec private static final int DURATION = 5; // seconds // GUI variables private BorderPane mainPane; private HBox controlPanel; private GridPane grid; private Button[][] buttons; private ImageView ivMouse; private Timeline timerMain; // functional variables private int score; // gain if user clicks on the mouse button public void start(Stage stage) { // setup calls setupControlPanel(); setupImage(); setupBoard(); setupTimers(); assignMouse(); Scene scene = new Scene(mainPane, APP_WIDTH, APP_HEIGHT); stage.setTitle("CS112 F24 Whack-A-Mouse"); stage.setScene(scene); stage.show(); // TEMPORARY timerMain.play(); } private void setupControlPanel() { controlPanel = new HBox(); mainPane.setTop(controlPanel); // create buttons // create labels } private void setupImage() { ivMouse = new ImageView( new Image(IMG_NAME) ); } private void setupBoard() { grid = new GridPane(); mainPane.setCenter(grid); buttons = new Button[N_ROWS][N_COLS]; for (int r = 0; r < N_ROWS; ++r) { for (int c = 0; c < N_COLS; ++c) { Button bn = new Button(); bn.setPrefSize(BN_SIZE, BN_SIZE); // add to array buttons[r][c] = bn; bn.setOnAction( e -> { onClick(e); }); // add to board (grid pane) grid.add(bn, c, r); } } } private void onClick(ActionEvent e) { Object src = e.getSource(); Button clickedButton = (Button) src; // if the clicked button has the graphics, user scores if (clickedButton.getGraphic() != null) { ++score; } else { --score; } System.out.println("Current score = " + score); } private void setupTimers() { // setup key frame KeyFrame keyFrame = new KeyFrame(Duration.millis(500), e -> { assignMouse(); }); // setup timerMain timerMain = new Timeline(keyFrame); timerMain.setCycleCount(10); } private void assignMouse() { // generate two random integers (row, column) int row = (int) (Math.random() * N_ROWS); int col = (int) (Math.random() * N_COLS); // assign ivMouse to the button at (row, column) buttons[row][col].setGraphic(ivMouse); } public static void main(String[] args) { launch(args); } }