Browse Source

Add floodfill on click

feature_Minesweeper_Playfield
kfkama 3 years ago
parent
commit
4d97b75dba
  1. 73
      src/main/java/Minesweeper/Cell.java
  2. 6
      src/main/java/Minesweeper/Playfield.java

73
src/main/java/Minesweeper/Cell.java

@ -1,24 +1,89 @@
package Minesweeper;
import java.awt.Color;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
enum CellType{Number, Bomb}
enum CellType {
Number, Bomb
}
public class Cell extends JButton {
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) {
public Cell(CellType _type, Playfield _playfield, Point _cord) {
type = _type;
cord = _cord;
playfield = _playfield;
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
OnMouseClick();
}
});
}
protected void OnMouseClick() {
if (type != CellType.Bomb) {
flood();
}
}
public void update() {
if(type == CellType.Number) {
if (type == CellType.Number) {
setText(String.valueOf(value));
} else {
}
}
public void flood() {
if (type == CellType.Bomb) {
return;
}
setBackground(Color.LIGHT_GRAY);
setEnabled(false);
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();
}
}
}
}
}

6
src/main/java/Minesweeper/Playfield.java

@ -1,9 +1,11 @@
package Minesweeper;
import java.awt.Point;
public class Playfield {
private static final int CELLSIZE = 50;
private int Size;
public int Size;
private MinesweeperGame MsG;
public Cell[][] cells;
@ -27,7 +29,7 @@ public class Playfield {
for (int i = 0; i < Size; i++) {
for (int j = 0; j < Size; j++) {
cells[i][j] = new Cell(CellType.Number);
cells[i][j] = new Cell(CellType.Number, this, new Point(j, i));
cells[i][j].setBounds(j * CELLSIZE + (MsG.WIDTH / 2 - Size * CELLSIZE / 2),
i * CELLSIZE + (MsG.HEIGTH / 2 - Size * CELLSIZE / 2), CELLSIZE, CELLSIZE);

Loading…
Cancel
Save