-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMineView.java
More file actions
294 lines (250 loc) · 10.5 KB
/
MineView.java
File metadata and controls
294 lines (250 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/** A MineView displays a graphical user interface for the Mine Sweeper game.
* It relies on a separate MineModel to manage the state of the game itself.
*
* Author: Andrew Merrill
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MineView
{
// set debug to true to see all cells, not just the visible ones
private final boolean debug = false;
// these are the initial values for the three text fields
private int defaultNumRows = 10;
private int defaultNumCols = 10;
private int defaultNumMines = 20;
private JFrame mainFrame;
private GamePanel gamePanel;
private ControlPanel controlPanel;
private MineModel mineModel;
MineView(MineModel mineModel, int width, int height)
{
this.mineModel = mineModel;
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
gamePanel = new GamePanel();
controlPanel = new ControlPanel();
mainPanel.add(gamePanel, BorderLayout.CENTER);
mainPanel.add(controlPanel, BorderLayout.SOUTH);
mainFrame = new JFrame("Minesweeper");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add(mainPanel);
mainFrame.setSize(width, height);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
/////////////////////////////////////////////////////////////////////////////////////////
/** The ControlPanel is the panel with the New Game button and the text fields for configuring the game. */
private class ControlPanel extends JPanel
{
private JTextField rowsField, colsField, minesField;
private JLabel flagsLabel, timeLabel;
private javax.swing.Timer timer;
ControlPanel()
{
setLayout(new FlowLayout());
JButton newGameButton = new JButton("New Game");
newGameButton.addActionListener(new NewGameListener());
newGameButton.setMnemonic(KeyEvent.VK_N);
add(newGameButton);
rowsField = new JTextField(defaultNumRows+"", 4);
colsField = new JTextField(defaultNumCols+"", 4);
minesField = new JTextField(defaultNumMines+"", 4);
add(new JLabel("Rows: "));
add(rowsField);
add(new JLabel("Cols: "));
add(colsField);
add(new JLabel("Mines: "));
add(minesField);
add(new JLabel("Flags: "));
flagsLabel = new JLabel("0 ");
add(flagsLabel);
timeLabel = new JLabel(" 0:00");
add(new JLabel("Time: "));
add(timeLabel);
timer = new javax.swing.Timer(100, new TimerListener());
timer.start();
}
/////////////////////////////////////////////////////////////////////////////////////////
/** NewGameListener is used when the New Game button is clicked. */
class NewGameListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
try {
int numRows, numCols, numMines;
numRows = Integer.parseInt(rowsField.getText());
numCols = Integer.parseInt(colsField.getText());
numMines = Integer.parseInt(minesField.getText());
mineModel.newGame(numRows, numCols, numMines);
gamePanel.calculateCellSize();
gamePanel.repaint();
}
catch (NumberFormatException error)
// parseInt throws this exception when a non-number is entered in one of the text fields
{
JOptionPane.showMessageDialog(mainFrame, "That was not an integer: " + error.getMessage(), "Input Error", JOptionPane.ERROR_MESSAGE);
}
}
} // class NewGameListener
/////////////////////////////////////////////////////////////////////////////////////////
/** The timer is used to update the display of the current time and the number of flags placed. */
class TimerListener implements ActionListener
{
private java.text.DecimalFormat twoDigitFormat = new java.text.DecimalFormat("00");
public void actionPerformed(ActionEvent event)
{
if (mineModel.isGameStarted() && ! mineModel.isGameOver())
{
int elapsedTime = mineModel.getElapsedSeconds();
int minutes = elapsedTime / 60;
int seconds = elapsedTime % 60;
timeLabel.setText(minutes + ":" + twoDigitFormat.format(seconds));
flagsLabel.setText(mineModel.getNumFlags() + "");
}
}
}
} // class ControlPanel
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* The GamePanel is where the field is drawn on the screen. */
private class GamePanel extends JPanel
{
private int panelHeight, panelWidth; // size of the entire game panel
private int rowHeight, colWidth; // size of each cell
private int offsetX, offsetY; // offset between the northwest corner of the panel
// and the northwest corner of the upper-left cell
GamePanel()
{
addMouseListener(new MineMouseListener());
addComponentListener(new GamePanelComponentListener());
}
/* Calculates the dimensions of the cells in the field of the game,
* based on the size of the game panel, and the number of rows and columns in the field.
* This method is called whenever the field is resized.
*/
void calculateCellSize()
{
if (! mineModel.isGameStarted()) return;
Dimension d = getSize();
panelWidth = d.width;
panelHeight = d.height;
rowHeight = panelHeight / mineModel.getNumRows();
colWidth = panelWidth / mineModel.getNumCols();
offsetX = (panelWidth - colWidth*mineModel.getNumCols()) / 2;
offsetY = (panelHeight - rowHeight*mineModel.getNumRows()) / 2;
}
/* paintComponent re-draws the field */
protected void paintComponent(Graphics pen)
{
// don't do any drawing if the game hasn't started yet
if (! mineModel.isGameStarted()) return;
// make the background black
pen.setColor(Color.BLACK);
pen.fillRect(0, 0, panelWidth, panelHeight);
int numRows = mineModel.getNumRows();
int numCols = mineModel.getNumCols();
// draw every cell
for (int r=0; r<numRows; r++) {
for (int c=0; c<numCols; c++) {
Cell cell = mineModel.getCell(r,c);
drawCell(pen, cell);
}
}
} // paintComponent()
private void drawCell(Graphics pen, Cell cell)
{
// compute x and y coordinates of the north-west corner of the cell
int nw_x = cell.getCol() * colWidth + offsetX;
int nw_y = cell.getRow() * rowHeight + offsetY;
// draw a border around the cell
pen.setColor(Color.BLUE);
pen.drawRect(nw_x, nw_y, colWidth, rowHeight);
if (cell.isFlagged())
{
// draw an orange flag on a white background
pen.setColor(Color.WHITE);
pen.fillRect(nw_x+1, nw_y+1, colWidth-2, rowHeight-2);
int[] flag_x = new int[] {nw_x+colWidth/3, nw_x+colWidth/3, nw_x+2*colWidth/3, nw_x+colWidth/3};
int[] flag_y = new int[] {nw_y+5*rowHeight/6, nw_y+rowHeight/6, nw_y+2*rowHeight/6, nw_y+3*rowHeight/6};
pen.setColor(Color.ORANGE);
pen.fillPolygon(flag_x, flag_y, 4);
pen.setColor(Color.BLACK);
pen.drawPolygon(flag_x, flag_y, 4);
}
else if (!debug && !cell.isVisible())
{
// unless we are debugging, draw non-visible squares in gray
pen.setColor(Color.GRAY);
pen.fillRect(nw_x+1, nw_y+1, colWidth-2, rowHeight-2);
}
else if (cell.isMine())
{
// draw mines as red circles on a white background
pen.setColor(Color.WHITE);
pen.fillRect(nw_x+1, nw_y+1, colWidth-2, rowHeight-2);
pen.setColor(Color.RED);
int radius = Math.min(colWidth,rowHeight)/3;
pen.fillOval(nw_x+colWidth/2-radius, nw_y+rowHeight/2-radius, 2*radius, 2*radius);
}
else
{
// draw the number of adjacent mines on a green background
// (or a yellow background if we are debugging and this square is not yet visible)
if (debug && !cell.isVisible())
pen.setColor(Color.YELLOW);
else
pen.setColor(Color.GREEN);
pen.fillRect(nw_x+1, nw_y+1, colWidth-2, rowHeight-2);
pen.setColor(Color.BLACK);
pen.setFont(pen.getFont().deriveFont(Font.BOLD, 14));
pen.drawString(String.valueOf(cell.getNeighborMines()), nw_x + 3*colWidth/7, nw_y + 5*rowHeight/7);
}
} // drawCell()
/////////////////////////////////////////////////////////////////////////////////////////
class MineMouseListener implements MouseListener
{
public void mousePressed(MouseEvent event)
{
if (!mineModel.isGameStarted() || mineModel.isGameOver()) return;
int x = event.getX();
int y = event.getY();
if ( x < offsetX || y < offsetY) return;
int row = (y-offsetY) / rowHeight;
int col = (x-offsetX) / colWidth;
if (row < 0 || row >= mineModel.getNumRows() || col < 0 || col >= mineModel.getNumCols()) return;
int button = event.getButton();
if (button == MouseEvent.BUTTON3 || event.isShiftDown()) // right-click or shift-click
{
mineModel.placeOrRemoveFlagOnCell(row, col);
}
else if (button == MouseEvent.BUTTON1) // left-click
{
mineModel.stepOnCell(row, col);
}
repaint();
if (mineModel.isPlayerDead()) {
JOptionPane.showMessageDialog(mainFrame, "Boom! You just stepped on a mine! You're dead!");
}
else if (mineModel.isGameWon()) {
JOptionPane.showMessageDialog(mainFrame, "Congratulations! You won the game!");
}
}
public void mouseClicked(MouseEvent event) { }
public void mouseReleased(MouseEvent event) { }
public void mouseEntered(MouseEvent event) { }
public void mouseExited(MouseEvent event) { }
} // class MineMouseListener
//////////////////////////////////////////////////////////////////////////////////////////
class GamePanelComponentListener extends ComponentAdapter
{
public void componentResized(ComponentEvent event)
{
// when the game panel is resized, adjust the size of the cells
calculateCellSize();
repaint();
}
} // class GamePanelComponentListener
/////////////////////////////////////////////////////////////////////////////////////////
} // class GamePanel
} // class MineView