Today we apply a little bit of everything we’ve learned in a case study of the game Lights Out. We’ll use primitives and objects, ifs and loops, arrays, files, exceptions, graphical user interfaces—the whole shebang!
Here’s your TODO to complete before we meet again:
Lab tomorrow will be crazy with review sessions, returned midterms, and SplatBot. It will be your last opportunity to submit lab 10 checkpoints and your only opportunity to submit lab 11 checkpoints.
See you next class!
Sincerely,
P.S. Here’s the code we wrote together…
FlipButton.java
packagelecture1212;
importjava.awt.Color;
importjava.awt.Dimension;
importjavax.swing.JButton;
publicclassFlipButtonextendsJButton {
privateboolean isOn;
public FlipButton() {
isOn = false;
setBackground(Color.DARK_GRAY);
setBorderPainted(false);
setOpaque(true);
setPreferredSize(newDimension(75, 75));
}
publicboolean isOn() {
return isOn;
}
publicvoid turnOn() {
isOn = true;
setBackground(Color.YELLOW);
}
publicvoid turnOff() {
isOn = false;
setBackground(Color.DARK_GRAY);
}
publicvoid flip() {
if (isOn) {
setBackground(Color.DARK_GRAY);
} else {
setBackground(Color.YELLOW);
}
isOn = !isOn;
}
}
LightsOutFrame.java
packagelecture1212;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.util.Scanner;
importjavax.swing.JFrame;
importjavax.swing.JOptionPane;
importjavax.swing.JPanel;
publicclassLightsOutFrameextendsJFrame {
private FlipButton[][] buttons;
public LightsOutFrame() {
super("Lights Out!");
JPanel panel = newJPanel(newGridLayout(5, 5, 2, 2));
classFlipListenerimplementsActionListener {
privateint r;
privateint c;
public FlipListener(int c, int r) {
this.c = c;
this.r = r;
}
publicvoid actionPerformed(ActionEvent e) {
// flip the clicked upon button and neighbors
buttons[r][c].flip();
if (r < 4)
buttons[r + 1][c].flip();
if (r > 0)
buttons[r - 1][c].flip();
if (c < 4)
buttons[r][c + 1].flip();
if (c > 0)
buttons[r][c - 1].flip();
if (isWin()) {
JOptionPane.showMessageDialog(null, "You didn't lose.");
}
}
}
buttons = new FlipButton[5][5];
for (int r = 0; r < 5; ++r) {
for (int c = 0; c < 5; ++c) {
buttons[r][c] = new FlipButton();
buttons[r][c].addActionListener(new FlipListener(c, r));
panel.add(buttons[r][c]);
}
}
add(panel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
publicvoid loadBoard(File file) throwsFileNotFoundException {
Scanner in = newScanner(file);
for (int r = 0; r < 5; ++r) {
for (int c = 0; c < 5; ++c) {
if (in.nextInt() == 1) {
buttons[r][c].turnOn();
} else {
buttons[r][c].turnOff();
}
}
}
}
publicboolean isWin() {
for (int r = 0; r < 5; ++r) {
for (int c = 0; c < 5; ++c) {
if (buttons[r][c].isOn()) {
returnfalse;
}
}
}
returntrue;
}
}