package Minesweeper; import java.awt.Color; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JOptionPane; enum CellType { Number, Bomb } public class Cell extends JButton { private static final Color FLAGCOLOR = Color.RED; private static final Color FLOODEDCOLOR = Color.LIGHT_GRAY; private static final Color HIDDENCOLOR = Color.WHITE; private static final Color MINECOLOR = Color.BLACK; private static final long serialVersionUID = 1L; private Playfield playfield; public CellType type; public Point cord; public boolean flagged = false; public int value = 0; public Cell(CellType _type, Playfield _playfield, Point _cord) { type = _type; cord = _cord; playfield = _playfield; setBackground(HIDDENCOLOR); addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { OnMouseClick(); } }); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub super.mousePressed(e); if (e.getButton() == 3) { OnMouseRightClick(); } } }); } protected void OnMouseClick() { if (!flagged) { reveal(); if (type != CellType.Bomb) { flood(); } else { playfield.revealAllBombs(); JOptionPane.showMessageDialog(getParent(),"KABOOM! Try again!"); playfield.reset(); } } } protected void OnMouseRightClick() { if (isEnabled()) { if (flagged) { flagged = false; setBackground(HIDDENCOLOR); if (type == CellType.Number) { playfield.cellDried(); } } else { flagged = true; setBackground(FLAGCOLOR); if (type == CellType.Number) { playfield.cellFlooded(); } } } } public void reveal() { if (type == CellType.Number) { if(value > 0) { setText(String.valueOf(value)); } } else { setBackground(MINECOLOR); } } public void flood() { if (type == CellType.Bomb || flagged) { return; } setBackground(FLOODEDCOLOR); setEnabled(false); reveal(); playfield.cellFlooded(); if (value == 0) { if (cord.y > 0) { if (playfield.cells[cord.y - 1][cord.x].type == CellType.Number && playfield.cells[cord.y - 1][cord.x].isEnabled()) { playfield.cells[cord.y - 1][cord.x].flood(); } } if (cord.x < playfield.Size - 1) { if (playfield.cells[cord.y][cord.x + 1].type == CellType.Number && playfield.cells[cord.y][cord.x + 1].isEnabled()) { playfield.cells[cord.y][cord.x + 1].flood(); } } if (cord.y < playfield.Size - 1) { if (playfield.cells[cord.y + 1][cord.x].type == CellType.Number && playfield.cells[cord.y + 1][cord.x].isEnabled()) { playfield.cells[cord.y + 1][cord.x].flood(); } } if (cord.x > 0) { if (playfield.cells[cord.y][cord.x - 1].type == CellType.Number && playfield.cells[cord.y][cord.x - 1].isEnabled()) { playfield.cells[cord.y][cord.x - 1].flood(); } } } } }