Minesweeper LibGDX

Posted on by Kenny Cason
tags = [ java, libgdx, game ]

I previously wrote a Minesweeper game from scratch using Java’s native libraries. While this was no great task I was curious how much easier it would be to implement using the LibGDX framework. In a very happy surprise it only took me about 1 hour to port all the code into my LibGDX project and get it running. That’s even including some minor improvements!

The source can be found on GitHub.

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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.utils.TimeUtils;

import java.util.Random;

public class MineSweeper extends ApplicationAdapter {
	public static final int WIDTH = 460;
	public static final int HEIGHT = 350;

	private final Random random = new Random();

	private OrthographicCamera camera;
	private SpriteBatch batch;
	private ShapeRenderer shapeRenderer;
	private BitmapFont font;
	private Sound explosion;

	private boolean[][] map;
	private boolean[][] clicked;
	private boolean[][] flagged;
	private int[][] sorroundingMines;
	private int numMines;
	private int width;
	private int height;
	private int tileDim = 10;
	private long mouseLastClicked;
	private boolean gameOver;
	private long gameOverTime;

	@Override
	public void create () {
		width = 40;
		height = 30;
		map = new boolean[width][height];
		clicked = new boolean[width][height];
		flagged = new boolean[width][height];
		sorroundingMines = new int[width][height];
		numMines = 150;

		explosion = Gdx.audio.newSound(Gdx.files.internal("explosion.wav"));
		batch = new SpriteBatch();
		shapeRenderer = new ShapeRenderer();
		font = new BitmapFont();
		font.setColor(Color.WHITE);

		camera = new OrthographicCamera();
		camera.setToOrtho(false, WIDTH, HEIGHT);
		camera.update();

		newMap();

		Gdx.input.setInputProcessor(new InputAdapter() {
			@Override
			public boolean touchUp(int screenX, int screenY, int pointer, int button) {
				if (button == 0) {
					handlePrimaryClick(screenX, HEIGHT - screenY);
				}
				else if (button == 1) {
					handleSecondaryClick(screenX, HEIGHT - screenY);
				}
				return true;
			}
		});
	}

	@Override
	public void render () {
		if (!gameOver) {
			handleKeyboard();
			draw();
			if (isWin() || isLose()) {
				gameOver = true;
				gameOverTime = TimeUtils.millis();
				explosion.play();
			}
		}
		else {
			drawEndScreen();
			if (TimeUtils.timeSinceMillis(gameOverTime) > 2000) {
				create();
			}
		}
	}

	@Override
	public void dispose() {
		explosion.dispose();
		batch.dispose();
		shapeRenderer.dispose();
		font.dispose();
	}

	public void handlePrimaryClick(final int mx, final int my) {
		if (gameOver) { return; }

		if (TimeUtils.timeSinceMillis(mouseLastClicked) < 150) { return; }
		mouseLastClicked = TimeUtils.millis();

		final int x = (int) ((mx - 10) / (double) (tileDim + 1));
		final int y = (int) ((my - 10) / (double) (tileDim + 1));
		if (x >= 0 && x < width && y >= 0 && y < height) {
			click(x, y, 0);
		}
	}

	public void handleSecondaryClick(final int mx, final int my) {
		if (gameOver) { return; }

		if (TimeUtils.timeSinceMillis(mouseLastClicked) < 150) { return; }
		mouseLastClicked = TimeUtils.millis();

		final int x = (int) ((mx - 10) / (double) (tileDim + 1));
		final int y = (int) ((my - 10) / (double) (tileDim + 1));
		if (x >= 0 && x < width && y >= 0 && y < height) {
			flagged[x][y] = !flagged[x][y];
		}
	}

	public void handleKeyboard() {
		if(Gdx.input.isKeyPressed(Keys.H)) {
			help();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if(Gdx.input.isKeyPressed(Keys.C)) {
			clickAll();
		}
		if(Gdx.input.isKeyPressed(Keys.R)) {
			newMap();
		}
		if(Gdx.input.isKeyPressed(Keys.ESCAPE)) {
			System.exit(0);
		}
	}

	private void click(int x, int y, int depth) {
		if(x < 0 || x >= width || y < 0 || y >= height) {
			return;
		}
		if(clicked[x][y]) {
			return;
		}
		clicked[x][y] = true;
		if(map[x][y]) {
			return;
		}
		if(sorroundingMines[x][y] > 0) {
			return;
		}

		click(x - 1, y - 1, depth + 1);
		click(x, y - 1, depth + 1);
		click(x + 1, y - 1, depth + 1);
		click(x - 1, y, depth + 1);
		click(x + 1, y, depth + 1);
		click(x - 1, y + 1, depth + 1);
		click(x, y + 1, depth + 1);
		click(x + 1, y + 1, depth + 1);
	}

	private void help() {
		if(!isWin() && !isLose()) {
			for(int y = 0; y < height; y++) {
				for(int x = 0; x < width; x++) {
					if(!map[x][y] && !clicked[x][y]) {
						flagged[x][y] = false;
						click(x, y, 0);
						return;
					}
				}
			}
		}
	}

	private void drawRect(final Color color, final int x, final int y) {
		shapeRenderer.begin(ShapeType.Filled);
		shapeRenderer.setColor(color);
		shapeRenderer.rect(x, y, tileDim, tileDim);
		shapeRenderer.end();
	}

	public void draw() {
		Gdx.gl.glClearColor(0, 0, 0, 1);
		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

		camera.update();

		shapeRenderer.setProjectionMatrix(camera.combined);

		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (clicked[x][y]) {
					if (map[x][y]) { // if is mine
						drawRect(Color.RED,
								x * (tileDim + 1) + 10,
								y * (tileDim + 1) + 10);
					}
					else { // draw empty square;
						drawRect(Color.WHITE,
								x * (tileDim + 1) + 10,
								y * (tileDim + 1) + 10);

						if (sorroundingMines[x][y] > 0) {
							batch.begin();
							font.getData().setScale(0.8f, 0.8f);
							font.setColor(getMineCountColor(sorroundingMines[x][y]));
							font.draw(batch,
									String.valueOf(sorroundingMines[x][y]),
									x * (tileDim + 1) + 11,
									y * (tileDim + 1) + 19);
							batch.end();
						}
					}
				} else {
					drawRect(Color.GRAY,
							x * (tileDim + 1) + 10,
							y * (tileDim + 1) + 10);

					if (flagged[x][y]) {
						drawRect(Color.GREEN,
								x * (tileDim + 1) + 10,
								y * (tileDim + 1) + 10);
					}
				}

			}
		}
	}

	private void drawEndScreen() {
		draw();
		batch.begin();
		font.setColor(Color.RED);

		if(isWin()) {
			font.getData().setScale(2.0f, 2.0f);
			font.draw(batch, "You Win", 20, 120);
		}
		else if(isLose()) {
			font.getData().setScale(2.0f, 2.0f);
			font.draw(batch, "You Lose", 20, 120);
		}
		batch.end();
	}

	private Color getMineCountColor(int num) {
		switch(num) {
			case 1:
				return Color.BLACK;
			case 2:
				return Color.GRAY;
			case 3:
				return Color.BLUE;
			case 4:
				return Color.RED;
			case 5:
				return Color.MAGENTA;
			case 6:
				return Color.GREEN;
			default:
				return Color.BLACK;
		}
	}


	private void newMap() {
		gameOver = false;

		for(int y = 0; y < height; y++) {
			for(int x = 0; x < width; x++) {
				clicked[x][y] = false;
				flagged[x][y] = false;
				map[x][y] = false;
			}
		}

		int minesPlaced = 0;
		while(minesPlaced < numMines) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			if(!map[x][y]) {
				map[x][y] = true; // place mine
				minesPlaced++;
			}
		}

		for(int y = 0; y < height; y++) {
			for(int x = 0; x < width; x++) {
				sorroundingMines[x][y] = adjacentMines(x, y);
			}
		}
	}

	private int adjacentMines(int x, int y) {
		int tot = 0;
		if(isMine(x - 1, y - 1)) {
			tot++;
		}
		if(isMine(x, y - 1)) {
			tot++;
		}
		if(isMine(x + 1, y - 1)) {
			tot++;
		}
		if(isMine(x - 1, y)) {
			tot++;
		}
		if(isMine(x + 1, y)) {
			tot++;
		}
		if(isMine(x - 1, y + 1)) {
			tot++;
		}
		if(isMine(x, y + 1)) {
			tot++;
		}
		if(isMine(x + 1, y + 1)) {
			tot++;
		}
		return tot;
	}

	private boolean isMine(int x, int y) {
		if(x >= 0 && x < width && y >= 0 && y < height) {
			if(map[x][y]) {
				return true;
			}
		}
		return false;
	}

	private void clickAll() {
		for(int y = 0; y < height; y++) {
			for(int x = 0; x < width; x++) {
				clicked[x][y] = true;
			}
		}
	}

	private boolean isWin() {
		boolean win = true;
		for(int y = 0; y < height; y++) {
			for(int x = 0; x < width; x++) {
				win &= ((clicked[x][y] && !map[x][y]) ||
						(!clicked[x][y] && map[x][y]));
			}
		}
		return win;
	}

	private boolean isLose() {
		for(int y = 0; y < height; y++) {
			for(int x = 0; x < width; x++) {
				if(clicked[x][y] && map[x][y]) {
					return true;
				}
			}
		}
		return false;
	}

	private void debug() {
		for(int y = 0; y < height; y++) {
			for(int x = 0; x < width; x++) {
				System.out.print(map[x][y] + ",");
			}
			System.out.println();
		}
	}

}
comments powered by Disqus