This is actually an old 'problem' that I never really knew how to improve, but I'm wondering now if there is a better approach for this problem.
I'm creating MineSweeper with Java and struggling with an OOP aspect of the game. Basically I have a class Square.java, SquareBoms(extends Square) and Field.java. My approach on the Square is that it should only be aware of itself and should not communicate in any way or form with the Field.
However, the Field should check the surrounding SquaresBombs for bombs once a Square has been clicked. So the Square SHOULD message the Field that it has been clicked, but I don't think this is the right way of using OOP.
import java.awt.Color;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
public class Square extends JButton {
Field owner; //This is not OOP as the Square should only be aware of itself and what is in it.
int coords;
boolean isChecked = false;
boolean isMarked = false;
int bombsAround;
public Square(Field owner, int coords) {
this.owner = owner;
this.coords = coords;
this.setSize(400, 400);
this.setMargin(new Insets(0, 0, 0, 0));
this.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if (e.getButton() == MouseEvent.BUTTON1) {
Clicked();
}
else if(e.getButton() == MouseEvent.BUTTON3) {
Mark();
}
}
});
}
public void Clicked() {
if(!isChecked) {
this.setBackground(new Color(238, 238, 238)); // Reset when it had been marked
isChecked = true;
this.setEnabled(false);
owner.checkSquare(this); //This is not OOP as the Square should only be aware of itself and what is in it.
}
}
public void Mark() {
if(!isChecked) {
if(!isMarked)
this.setBackground(Color.GREEN);
else
this.setBackground(null);
isMarked = !isMarked; // toggle on every click
}
}
}
UPDATE
My original question was if it was 'allowed' to let a child object know about its parent. After doing some research i've come to the conclusion that this is not wrong in pure OOP-terms.
Field? How is aFielddifferent from aSquare? \$\endgroup\$Fieldis the playing board which containsSquaresas in playing tiles. \$\endgroup\$