Minsweeper game advice
I am currently in the process of making a java minesweeper game for school and have run into a problem. I have created an array of 64 buttons arranged in a开发者_如何学C grid layout. The problem i am having is getting the x and y co-ordinates of a particular button pressed and sending these co-ordinates to another class which contains a 2d array. any suggestions on how i can obtain the x and y position of the button pressed??? any help on this matter would be greatly appreciated
thanks
Once you know the click position you can use basic math to get the square hit. Then it's object-oriented programming to give that info to other parts of the game. You could follow a MVC (Model View Controller) pattern.
Basically your controller (main part) will register as listening to your view (your button(s)).
Here is a similar game with source code included if it helps.
Do you need the x-y coordinates on the canvas or just the x and y as in which column/row the button is?
If it's the latter just ensure that the other class can listen to events, and fire an event with the coordinates.
class OtherClass {
public void fireEvent(MineSweepButton button);
}
and for your button:
class MineSweepButton extends JButton {
private int x;
private int y;
public MineSweepButton(String text, int x, int y) {
super(text);
this.x = x;
this.y = y;
}
}
Now add an action listener that fires an event on the OtherClass.
精彩评论