-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainGame.java
More file actions
692 lines (606 loc) · 18.9 KB
/
Copy pathMainGame.java
File metadata and controls
692 lines (606 loc) · 18.9 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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.Timer;
import java.util.Scanner;
import java.io.*;
public class MainGame extends JPanel {
private static JFrame frame;
private static JPanel bigPanel;
private static JLayeredPane layeredPane;
private static boolean debug;
private static int frameSize;
private static int spotSize;
private static int numSpots;
private static int topBarSize;
private static double bombPercent;
private static HashMap<JButton, Integer> rowNumbers;
private static HashMap<JButton, Boolean> bombList;
private static HashMap<JButton, Boolean> markedTiles;
private static ArrayList<ArrayList<JButton>> buttons;
private static ArrayList<Color> colors;
private static int time;
private static Timer timer;
private static int tilesRemaining;
private static int bombsRemaining;
private static int score;
private static String bombText;
public MainGame(int numSpots, int spotSize){
this.numSpots=numSpots;
this.spotSize=spotSize;
runGame();
}
public MainGame(int numSpots){
this.numSpots=numSpots;
spotSize=30;
runGame();
}
public MainGame(){
numSpots=20;
spotSize=30;
runGame();
}
public static void main(String[] args){
numSpots=20;
spotSize=30;
runGame();
}
private static void runGame(){
//set to true to mark all bombs
debug=false;
frameSize=numSpots*spotSize+30;
topBarSize=44;
bombPercent=0.12;
//bombPercent=.04;
//initialize rows
rowNumbers = new HashMap<JButton, Integer>();
//initialize marked tiles
markedTiles = new HashMap<JButton, Boolean>();
//initial bomb value
bombsRemaining=(int)(numSpots*numSpots*bombPercent);
//initial time value
time=0;
bombText="✦";
//setting colors for number tiles
colors = new ArrayList<Color>();
colors.add(new Color(66, 134, 244));
colors.add(new Color(75, 242, 89));
colors.add(new Color(255, 89, 89));
colors.add(new Color(188, 89, 255));
colors.add(new Color(193, 0, 0));
tilesRemaining=numSpots*numSpots;
//create frame for minesweeper
frame = new JFrame();
frame.setResizable(false);
frame.setSize(frameSize,frameSize+topBarSize+4); //top bar is 22 tall
frame.setTitle("Minesweeper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
//create layered pane
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(frameSize,frameSize));
//create large panel
bigPanel = new JPanel();
bigPanel.setLayout(new BorderLayout());
bigPanel.setBounds(0,20,frameSize,frameSize);
//create bomblist
bombList = new HashMap<JButton, Boolean>();
//time
JLabel timeLabel = new JLabel("Time: "+time);
timeLabel.setSize(350,30);
timeLabel.setVerticalTextPosition(JLabel.CENTER);
timeLabel.setHorizontalTextPosition(JLabel.CENTER);
timeLabel.setBounds(20,0,350,15);
bigPanel.add(timeLabel);
//instruction
JLabel instructionLabel = new JLabel("Use right click to mark bombs");
instructionLabel.setSize(350,30);
instructionLabel.setVerticalTextPosition(JLabel.CENTER);
instructionLabel.setHorizontalTextPosition(JLabel.CENTER);
instructionLabel.setBounds(frameSize-205,0,350,15);
bigPanel.add(instructionLabel);
//quit panel
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new BorderLayout());
quitPanel.setBounds(frameSize/2-75/2,frameSize+5,75,25);
MenuSelectionButton quitButton = new MenuSelectionButton("Quit");
quitPanel.add(quitButton);
frame.add(quitPanel);
quitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent action){
restartGame();
}
});
timer = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e){
time++;
timeLabel.setText("Time: "+time);
}
});
JPanel tilePanel = new JPanel();
tilePanel.setLayout(new GridBagLayout());
//create all tiles
buttons = createButtons(tilePanel);
bigPanel.add(tilePanel);
layeredPane.add(bigPanel,new Integer(1));
frame.add(layeredPane);
createBombs();
//set frame to visible
frame.setVisible(true);
//create listeners for all buttons
for(int i=0;i<buttons.size();i++){
for(int j=0;j<buttons.get(0).size();j++){
JButton button = buttons.get(i).get(j);
button.addActionListener(new ActionListener() {
//Override
public void actionPerformed(ActionEvent action){
if(!timer.isRunning()){
timer.start();
}
if(markedTiles.get(button)==null || markedTiles.get(button)==false){
if(bombList.get(button)!=null && bombList.get(button)==true){
button.setText(bombText);
button.setForeground(Color.RED);
button.setBackground(Color.RED);
button.setEnabled(false);
button.setOpaque(true);
gameEndLose();
frame.repaint();
} else {
int numSurrounding = findAdjacentBombs(button);
if(numSurrounding!=0){
button.setText(""+numSurrounding);
button.setEnabled(false);
button.setBackground(colors.get(numSurrounding-1));
button.setOpaque(true);
frame.repaint();
tilesRemaining--;
if(checkIfWon()){
int numBombs=(int)(numSpots*numSpots*bombPercent);
double percent = (1 - ((double)(tilesRemaining-bombsRemaining)) / ((double)(numSpots*numSpots-numBombs))) * 100;
if(hasHighScore()){
gameEndWin(true);
getLeaderboardName();
} else {
gameEndWin(false);
}
}
} else {
clearZeroSquares(button);
frame.repaint();
if(checkIfWon()){
if(hasHighScore()){
gameEndWin(true);
getLeaderboardName();
} else {
gameEndWin(false);
}
}
}
}
}
}
});
//add right click listener
button.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
if(SwingUtilities.isRightMouseButton(e) && button.isEnabled()==true){
if(markedTiles.get(button)!=null){
boolean isMarked = markedTiles.get(button);
if(!isMarked){
button.setText(bombText);
button.setForeground(Color.RED);
button.setBackground(Color.RED);
markedTiles.put(button,true);
} else {
button.setText("");
markedTiles.put(button,false);
}
} else {
markedTiles.put(button,true);
button.setText(bombText);
button.setForeground(Color.RED);
button.setBackground(Color.RED);
button.setPreferredSize(new Dimension(spotSize,spotSize));
}
}
}
});
}
}
}
private static boolean checkIfWon(){
int numBombs = (int)((numSpots*numSpots)*bombPercent);
return (tilesRemaining-numBombs==0);
}
private static ArrayList<ArrayList<JButton>> createButtons(JPanel frame){
ArrayList<ArrayList<JButton>> buttons = new ArrayList<ArrayList<JButton>>();
for(int i=0;i<numSpots;i++){
buttons.add(new ArrayList<JButton>());
}
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
for(int i=0;i<numSpots;i++){
for(int j=0;j<numSpots;j++){
JButton button = new JButton();
button.setPreferredSize(new Dimension(spotSize,spotSize));
c.gridx = j;
c.gridy = i;
bombList.put(button,false);
buttons.get(i).add(button);
rowNumbers.put(button,i);
frame.add(button, c);
}
}
JButton button = new JButton("");
button.setBounds(0,0,0,0);
button.setVisible(false);
frame.add(button);
return buttons;
}
private static void createBombs(){
int bombCount=0;
int maxBombs = (int)(Math.pow(numSpots,2)*bombPercent);
while(bombCount<maxBombs){
int randNumX = (int)(Math.random()*(numSpots));
int randNumY = (int)(Math.random()*(numSpots));
JButton button = buttons.get(randNumY).get(randNumX);
if(bombList.get(button)!=true){
bombList.remove(button);
bombList.put(button, true);
bombCount++;
if(debug){
button.setText(bombText);
}
}
}
}
private static void clearZeroSquares(JButton button){
int numSurrounding=findAdjacentBombs(button);
if(bombList.get(button)==false && numSurrounding==0 && button.isEnabled()==true){
button.setText("");
button.setEnabled(false);
button.setBackground(new Color(170,170,170));
button.setOpaque(true);
tilesRemaining--;
ArrayList<JButton> adjacentTiles = getAdjacentTiles(button);
for(int i=0;i<adjacentTiles.size();i++){
JButton b = adjacentTiles.get(i);
clearZeroSquares(b);
}
} else if(bombList.get(button)==false && numSurrounding!=0 && button.isEnabled()==true){
button.setText(numSurrounding+"");
button.setEnabled(false);
button.setBackground(colors.get(numSurrounding-1));
button.setOpaque(true);
tilesRemaining--;
}
}
private static ArrayList<JButton> getAdjacentTiles(JButton button){
ArrayList<JButton> toReturn = new ArrayList<JButton>();
int row = rowNumbers.get(button);
int index = buttons.get(row).indexOf(button);
if(row-1>=0){
ArrayList<JButton> rowList = buttons.get(row-1);
if(index-1>=0){
toReturn.add(rowList.get(index-1));
}
if(index>=0){
toReturn.add(rowList.get(index));
}
if(index+1<numSpots){
toReturn.add(rowList.get(index+1));
}
}
if(row+1<numSpots){
ArrayList<JButton> rowList = buttons.get(row+1);
if(index-1>=0){
toReturn.add(rowList.get(index-1));
}
if(index>=0){
toReturn.add(rowList.get(index));
}
if(index+1<numSpots){
toReturn.add(rowList.get(index+1));
}
}
ArrayList<JButton> rowList = buttons.get(row);
if(index-1>=0){
JButton tile = rowList.get(index-1);
toReturn.add(rowList.get(index-1));
}
if(index+1<numSpots){
toReturn.add(rowList.get(index+1));
}
return toReturn;
}
private static int findAdjacentBombs(JButton button){
int row = rowNumbers.get(button);
int index = buttons.get(row).indexOf(button);
int count=0;
if(row-1>=0){
ArrayList<JButton> rowList = buttons.get(row-1);
if(index-1>=0){
JButton tile = rowList.get(index-1);
if(bombList.get(tile)!=null && bombList.get(tile)==true){
count++;
}
}
if(index>=0){
JButton tile = rowList.get(index);
if(bombList.get(tile)!=null && bombList.get(tile)==true){
count++;
}
}
if(index+1<numSpots){
JButton tile = rowList.get(index+1);
if(bombList.get(tile)!=null && bombList.get(tile)==true){
count++;
}
}
}
if(row+1<numSpots){
ArrayList<JButton> rowList = buttons.get(row+1);
if(index-1>=0){
JButton tile = rowList.get(index-1);
if(bombList.get(tile)!=null && bombList.get(tile)==true){
count++;
}
}
if(index>=0){
JButton tile = rowList.get(index);
if(bombList.get(tile)!=null && bombList.get(tile)==true){
count++;
}
}
if(index+1<numSpots){
JButton tile = rowList.get(index+1);
if(bombList.get(tile)!=null && bombList.get(tile)==true){
count++;
}
}
}
ArrayList<JButton> rowList = buttons.get(row);
if(index-1>=0){
JButton tile = rowList.get(index-1);
if(bombList.get(tile)!=null && bombList.get(tile)==true){
count++;
}
}
if(index+1<numSpots){
JButton tile = rowList.get(index+1);
if(bombList.get(tile)!=null && bombList.get(tile)==true){
count++;
}
}
return count;
}
private static void gameEndLose(){
timer.stop();
for(JButton button : bombList.keySet()){
button.setEnabled(false);
}
JPanel losePanel = new JPanel();
losePanel.setLayout(null);
losePanel.setBounds(frameSize/2-250/2,frameSize/2-125/2,250,125);
Color boxColor = new Color(90,90,90,200);
losePanel.setBackground(boxColor);
boxColor=new Color(90,90,90,0);
JPanel textPanel = new JPanel();
textPanel.setPreferredSize(new Dimension(250,35));
textPanel.setBounds(0,0,250,35);
textPanel.setLayout(new BorderLayout());
textPanel.setBackground(boxColor);
DrawText textOne = new DrawText(250,4,26,"Game Over");
textPanel.add(textOne);
losePanel.add(textPanel);
JPanel textPanel2 = new JPanel();
textPanel2.setPreferredSize(new Dimension(250,50));
textPanel2.setBounds(0,35,250,50);
textPanel2.setLayout(new BorderLayout());
textPanel2.setBackground(boxColor);
int numBombs=(int)(numSpots*numSpots*bombPercent);
int percent = (int)((1 - ((double)(tilesRemaining-bombsRemaining)) / ((double)(numSpots*numSpots-numBombs))) * 100);
DrawText textTwo = new DrawText(250,10,20,"Time: "+time+" seconds "+percent+"% complete");
textPanel2.add(textTwo);
losePanel.add(textPanel2);
MenuSelectionButton restartButton = new MenuSelectionButton("Restart");
int panelWidth = 250;
int panelHeight = losePanel.getSize().height;
int buttonWidth=250/2;
int buttonHeight=panelHeight/4;
restartButton.setBounds(panelWidth/2-buttonWidth/2,panelHeight-buttonHeight-10,buttonWidth,buttonHeight);
restartButton.setBackground(boxColor);
losePanel.add(restartButton);
layeredPane.add(losePanel, new Integer(2));
restartButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent action){
restartGame();
}
});
}
private static void gameEndWin(boolean hasHighScore){
timer.stop();
for(JButton button : bombList.keySet()){
if(bombList.get(button)==true){
button.setEnabled(false);
}
}
if(!hasHighScore){
JPanel winPanel = new JPanel();
winPanel.setLayout(null);
winPanel.setBounds(frameSize/2-250/2,frameSize/2-125/2,250,125);
Color boxColor = new Color(90,90,90,200);
winPanel.setBackground(boxColor);
boxColor=new Color(90,90,90,0);
JPanel textPanel = new JPanel();
textPanel.setPreferredSize(new Dimension(250,35));
textPanel.setBounds(0,0,250,35);
textPanel.setLayout(new BorderLayout());
textPanel.setBackground(boxColor);
DrawText textOne = new DrawText(250,0,24,"Winner!");
textPanel.add(textOne);
winPanel.add(textPanel);
JPanel textPanel2 = new JPanel();
textPanel2.setPreferredSize(new Dimension(250,50));
textPanel2.setBounds(0,30,250,50);
textPanel2.setLayout(new BorderLayout());
textPanel2.setBackground(boxColor);
DrawText textTwo = new DrawText(250,2,20,"Time: "+time+" seconds "+"Score: "+score);
textPanel2.add(textTwo);
winPanel.add(textPanel2);
MenuSelectionButton restartButton = new MenuSelectionButton("Restart");
int panelWidth = 250;
int panelHeight = winPanel.getSize().height;
int buttonWidth=250/2;
int buttonHeight=panelHeight/4;
restartButton.setBounds(panelWidth/2-buttonWidth/2,panelHeight-buttonHeight-10,buttonWidth,buttonHeight);
restartButton.setBackground(boxColor);
winPanel.add(restartButton);
layeredPane.add(winPanel, new Integer(2));
restartButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent action){
restartGame();
}
});
}
}
public static void restartGame(){
JFrame oldFrame = frame;
MineSweeper newGame = new MineSweeper();
oldFrame.dispose();
}
private static void updateLeaderboard(String playerName){
File file = new File("leaderboard.txt");
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> scores = new ArrayList<Integer>();
boolean hasHighScore = false;
try {
Scanner scan = new Scanner(file);
int i=0;
while(scan.hasNextLine()){
String line = scan.nextLine();
String[] strArr = line.split(";");
names.add(strArr[0]);
scores.add(Integer.parseInt(strArr[1]));
i++;
}
} catch (Exception e){
System.out.println(e);
}
//add new high score (if it exists) to names/scores
int scoreSize=scores.size();
if(scoreSize==0){
scores.add(score);
names.add(playerName);
} else {
boolean inserted = false;
for(int i=0;i<scoreSize;i++){
if(score>scores.get(i)){
scores.add(i,score);
names.add(i,playerName);
inserted=true;
break;
}
}
if(!inserted){
scores.add(scoreSize,score);
names.add(scoreSize,playerName);
}
}
gameEndWin(hasHighScore);
//rewrite leaderboard file
scoreSize=scores.size();
try {
PrintWriter pw = new PrintWriter(file);
pw.close();
FileWriter writer = new FileWriter("leaderboard.txt");
BufferedWriter out = new BufferedWriter(writer);
for(int i=0;i<Math.min(scoreSize,5);i++){
String toWrite = names.get(i)+";"+scores.get(i);
out.write(toWrite);
out.newLine();
}
out.close();
} catch (Exception e){
System.out.println(e);
}
}
private static boolean hasHighScore(){
File file = new File("leaderboard.txt");
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> scores = new ArrayList<Integer>();
boolean hasHighScore = false;
//SCORE CALCULATION
score = (int)(Math.pow(numSpots,6)/(time)/150);
try {
Scanner scan = new Scanner(file);
int i=0;
while(scan.hasNextLine()){
String line = scan.nextLine();
String[] strArr = line.split(";");
names.add(strArr[0]);
scores.add(Integer.parseInt(strArr[1]));
i++;
}
} catch (Exception e){
System.out.println(e);
}
int scoreSize=scores.size();
if(scoreSize<5){
hasHighScore=true;
} else {
for(int i=0;i<scoreSize;i++){
if(score>scores.get(i)){
hasHighScore=true;
break;
}
}
}
return hasHighScore;
}
private static void getLeaderboardName(){
JPanel namePanel = new JPanel();
namePanel.setLayout(null);
namePanel.setBounds(frameSize/2-250/2,frameSize/2-150/2,250,150);
Color boxColor = new Color(90,90,90,200);
namePanel.setBackground(boxColor);
boxColor=new Color(90,90,90,0);
JPanel textPanel = new JPanel();
textPanel.setPreferredSize(new Dimension(250,75));
textPanel.setBounds(0,0,250,75);
textPanel.setLayout(new BorderLayout());
textPanel.setBackground(boxColor);
DrawHighScore lineOne = new DrawHighScore(250,150,24,"New High Score! "+score);
textPanel.add(lineOne);
JPanel nameFieldPanel = new JPanel();
nameFieldPanel.setPreferredSize(new Dimension(75,25));
nameFieldPanel.setBounds(250/2-75/2,150/2+10,75,25);
nameFieldPanel.setLayout(new BorderLayout());
nameFieldPanel.setBackground(new Color(0,0,0));
JTextField nameField = new JTextField("Name",10);
nameFieldPanel.add(nameField);
JPanel continueButtonPanel = new JPanel();
continueButtonPanel.setLayout(new BorderLayout());
continueButtonPanel.setPreferredSize(new Dimension(150,35));
continueButtonPanel.setBounds(250/2-150/2,150-35,150,35);
continueButtonPanel.setBackground(boxColor);
MenuSelectionButton continueButton = new MenuSelectionButton("Continue");
continueButtonPanel.add(continueButton);
namePanel.add(continueButtonPanel);
namePanel.add(nameFieldPanel);
namePanel.add(textPanel);
layeredPane.add(namePanel, new Integer(2));
frame.repaint();
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent action){
String text = nameField.getText();
updateLeaderboard(text);
restartGame();
}
});
}
}