-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTetris.java
More file actions
1430 lines (1181 loc) · 59 KB
/
Tetris.java
File metadata and controls
1430 lines (1181 loc) · 59 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.swing.*;
public class Tetris extends JFrame {
private JLabel label, gameLabel, easyLabel,overlayLabel,scoreLabel,nextBlockLabel,holdLabel,timeLabel,progressLabel,chlabel,abilitylabel,explainlabel;
private JButton startButton, exitButton, easyButton, mediumButton, hardButton;
private ImageIcon originalIcon, easyIcon,chIcon,abIcon,overlayImageIcon;
private Timer timer;
private boolean isEasyCleared = false,isMediumCleared = false,isHardCleared = false,holdUsed = false,abilityUsed = false,isDirectionLocked = false,check = false;
private final int initialWidth = 800,initialHeight = 800;
private int[][] board = new int[20][10];
private JLabel[][] cellLabels = new JLabel[20][10];
private int currentX, currentY, blockType,nextBlockType,rotation = 0,lockedBlocksCount = 0,gameSpeed = 500,holdBlockType = -1,remainingTime = 180,totalScore = 0,highestScore = 0, totalBlocks = 70,clearedBlocks = 0,currentDifficulty;
private Color currentColor = Color.BLUE;
private Timer countdownTimer; // 제한시간을 관리하는 타이머
private long blockStartTime;
private String selectedCharacter = ""; // 선택된 캐릭터
private String[] characters = {"에린 카르테스", "레온 하르트", "셀레나", "루미엘", "슬리"};
private String[] imagePaths = {
"images/ch/man_1.png",
"images/ch/man_2.png",
"images/ch/woman_1.png",
"images/ch/woman_2.png",
"images/ch/slime.png"
};
private MusicManager musicManager = new MusicManager();
// 현재 난이도에 맞는 배경음악 경로 반환
private String getBackgroundMusic() {
if (currentDifficulty == 1) {
return "sings/easy.wav";
} else if (currentDifficulty == 2) {
return "sings/normal.wav";
} else if (currentDifficulty == 3) {
return "sings/hard.wav";
} else {return null;}
}
// SHAPE 배열은 그대로 두고, 랜덤으로 블록을 선택할 예정입니다.
static final int[][][][] SHAPE = {
{ // ㄱ 모양 블록
{ {0,0,0,0},{0,1,1,1},{0,0,0,1},{0,0,0,0} },
{ {0,0,0,0},{0,0,0,1},{0,0,0,1},{0,0,1,1} },
{ {0,0,0,0},{0,0,0,0},{0,1,0,0},{0,1,1,1} },
{ {0,1,1,0},{0,1,0,0},{0,1,0,0},{0,0,0,0} }
},
{ // ㅁ 모양 블록
{ {0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0} },
{ {0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0} },
{ {0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0} },
{ {0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0} }
},
{ // ㄴ 모양 블록
{ {0,0,0,0},{1,0,0,0},{1,1,1,0},{0,0,0,0} },
{ {0,0,0,0},{0,1,1,0},{0,1,0,0},{0,1,0,0} },
{ {0,0,0,0},{0,0,0,0},{1,1,1,0},{0,0,1,0} },
{ {0,1,0,0},{0,1,0,0},{1,1,0,0},{0,0,0,0} }
},
{ // -_ 모양 블록 (S 모양)
{ {0,0,0,0},{1,1,0,0},{0,1,1,0},{0,0,0,0} },
{ {0,0,0,0},{0,0,1,0},{0,1,1,0},{0,1,0,0} },
{ {0,0,0,0},{1,1,0,0},{0,1,1,0},{0,0,0,0} },
{ {0,0,0,0},{0,0,1,0},{0,1,1,0},{0,1,0,0} }
},
{ // _- 모양 블록 (Z 모양)
{ {0,0,0,0},{0,1,1,0},{1,1,0,0},{0,0,0,0} },
{ {0,0,0,0},{0,1,0,0},{0,1,1,0},{0,0,1,0} },
{ {0,0,0,0},{0,1,1,0},{1,1,0,0},{0,0,0,0} },
{ {0,0,0,0},{0,1,0,0},{0,1,1,0},{0,0,1,0} }
},
{ // ㅡ 모양 블록 (I 모양)
{ {0,1,0,0},{0,1,0,0},{0,1,0,0},{0,1,0,0} },
{ {0,0,0,0},{1,1,1,1},{0,0,0,0},{0,0,0,0} },
{ {0,1,0,0},{0,1,0,0},{0,1,0,0},{0,1,0,0} },
{ {0,0,0,0},{1,1,1,1},{0,0,0,0},{0,0,0,0} }
},
{ // ㅗ 모양 블록 (T 모양)
{ {0,0,0,0},{0,1,0,0},{1,1,1,0},{0,0,0,0} },
{ {0,0,0,0},{0,1,0,0},{0,1,1,0},{0,1,0,0} },
{ {0,0,0,0},{0,0,0,0},{1,1,1,0},{0,1,0,0} },
{ {0,0,0,0},{0,1,0,0},{1,1,0,0},{0,1,0,0} }
}
};
public class MusicManager {
private Clip clip;
// 음악을 재생하는 메소드
public void playMusic(String filePath) {
// 기존 음악을 멈추고 새로운 음악을 재생
stopMusic(); // 기존 음악 종료
try {
File file = new File(filePath);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audioStream);
// 음악 종료 후 Clip 리소스 해제
clip.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) {
clip.close();
}
});
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
// 음악을 멈추는 메소드
public void stopMusic() {
// clip이 존재하고 음악이 실행 중이면 멈추기
if (clip != null && clip.isRunning()) {
clip.stop();
clip.close();
}
}
}
public Tetris() {
setTitle("테트리스");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(null);
setSize(initialWidth, initialHeight);
originalIcon = new ImageIcon("images/first.png");
label = new JLabel();
label.setBounds(0, 0, initialWidth, initialHeight);
updateBackgroundImage();
startButton = new JButton("시작하기");
startButton.setBounds(350, 500, 100, 50);
exitButton = new JButton("종료하기");
exitButton.setBounds(350, 580, 100, 50);
startButton.addActionListener(e -> {
musicManager.playMusic("sings/start.wav");
showDifficultyButtons();});
exitButton.addActionListener(e -> {
musicManager.playMusic("sings/start.wav");
int result = JOptionPane.showConfirmDialog(null, "정말 종료하시겠습니까?", "종료 확인",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION) System.exit(0);
});
label.add(startButton);
label.add(exitButton);
c.add(label);
setFocusable(true); // 키보드 입력 활성화
addKeyListener(new TetrisKeyListener()); // 키 리스너 추가
setVisible(true);
}
private void showDifficultyButtons() {
startButton.setVisible(false);
exitButton.setVisible(false);
easyButton = new JButton("난이도 하");
easyButton.setBounds(350, 400, 100, 50);
easyButton.addActionListener(e -> showCharacterSelection(300, 1));
mediumButton = new JButton("난이도 중");
mediumButton.setBounds(350, 470, 100, 50);
mediumButton.addActionListener(e -> showCharacterSelection(250, 2));
hardButton = new JButton("난이도 상");
hardButton.setBounds(350, 540, 100, 50);
hardButton.addActionListener(e -> showCharacterSelection(200, 3));
label.add(easyButton);
label.add(mediumButton);
label.add(hardButton);
label.revalidate();
label.repaint();
}
private void showCharacterSelection(int speed, int difficulty) {
gameSpeed = speed;
currentDifficulty = difficulty;
getContentPane().removeAll(); // 기존 UI 제거
revalidate();
repaint();
musicManager.stopMusic(); // 기존 음악 정지
// 시작 화면 배경음악 재생
musicManager.playMusic("sings/first.wav");
JPanel charSelectionPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // 기존의 컴포넌트 그리기
// 배경 이미지 그리기
ImageIcon backgroundImage = new ImageIcon("images/select.png");
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
};
charSelectionPanel.setLayout(null);
charSelectionPanel.setBounds(0, 0, getWidth(), getHeight());
JLabel charLabel = new JLabel("각각의 고유 능력을 지닌 캐릭터를 선택하세요!");
charLabel.setBounds(280, 50, 300, 50);
charLabel.setForeground(Color.WHITE);
charLabel.setHorizontalAlignment(SwingConstants.CENTER);
charSelectionPanel.add(charLabel);
JLabel charImageLabel = new JLabel();
charImageLabel.setBounds(50, 150, 370, 400);
charImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
charImageLabel.setVerticalAlignment(SwingConstants.CENTER);
charSelectionPanel.add(charImageLabel);
JLabel charDescLabel = new JLabel();
charDescLabel.setBounds(500, 150, 200, 20);
charDescLabel.setForeground(Color.WHITE);
charDescLabel.setHorizontalAlignment(SwingConstants.CENTER);
charSelectionPanel.add(charDescLabel);
// 새로운 설명을 표시할 라벨 추가
JLabel descriptionLabel = new JLabel("");
descriptionLabel.setBounds(430, 180, 400, 400); // 설명 위치 및 크기 조정
descriptionLabel.setHorizontalAlignment(SwingConstants.CENTER);
descriptionLabel.setVerticalAlignment(SwingConstants.TOP);
charSelectionPanel.add(descriptionLabel);
// 각 캐릭터 설명 준비 (배열에 캐릭터 설명 추가)
String[] characterDescriptions = {
"직업: 검성(Blade Master) / 왕국의 기사\n\n나이: 24세\n\n출신지: 루멘테르 왕국의 수도, 크라운스피어(Crownspear)\n\n역할: 파티장, 주 공격수, 전략의 중심\n\n루멘테르 왕국 출신의 기사로, 정의와 명예를 중시합니다.\n\n어릴 때부터 빛의 신 루멘의 가르침을 받았으며,\n 에테르 기사단의 마지막 계승자로서 \n조상 대대로 전해내려온 성검을 지니고\n 사명을 지니고 있습니다.\n\n냉철하지만 팀원들을 아끼며 책임감이 강합니다.",
"직업: 성기사 (Paladin)\n\n나이: 29세\n\n출신지: 루멘테르 왕국의 외곽 마을, 실바린(Silvarin)\n\n역할: 파티의 탱커 및 정신적 지주\n\n레온은 루멘테르 왕국의 외곽 농촌 마을에서 태어나\n 어린 시절부터 착하고 강인한 성격으로\n 동네 사람들에게 존경받았습니다.\n\n 그의 마을은 마족의 습격을 받아\n 거의 전멸했지만,\n 레온은 홀로 마을을 지키기 위해 싸우다\n 루멘 신전의 성기사단에 의해 구출됩니다.",
"직업: 원소 마법사(Elemental Mage) / 화염 전문가\n\n나이: 24세\n\n출신지: 아르카디아의 외곽 마을, 에텔로스(Ethelos)\n\n역할: 강력한 마법 딜러, 전략적인 제압 스페셜리스트\n\n셀레나는 평화로운 에텔로스 마을에서 태어났지만,\n\n 그녀가 8살이 되던 해,\n 마을은 정체불명의 마족의 습격으로 전멸당했습니다.\n 그녀는 화염 속에서 기적적으로 살아남았으며,\n 이후 자신의 내면에\n 원소 마법의 재능이 깃들어 있다는 것을 알게 되었습니다.\n\n 그녀의 고향이 불타오르는 장면은 셀레나의 트라우마이지만,\n 동시에 그녀의 가장 큰 힘의 원천이기도 합니다.",
"직업: 성녀 (Saint) / 치유와 축복의 사제\n\n나이: 19세\n\n출신지: 신성 제국, 일루미네르 수도\n\n역할: 치유와 보호, 파티의 정신적 지주\n\n루미엘은 태어날 때부터 \n신성한 빛에 선택받은 축복받은 아이로,\n 일루미네르 성당에서 자랐습니다.\n 그녀의 부모는 이름 없는 농민이었지만,\n 그녀가 태어난 날 밤 \n하늘에 빛나는 성운이 나타나\n 그녀의 신성한 운명을 예고했습니다.\n\n 어린 시절부터 치유의 기적을 보여준\n 그녀는 신성 제국의 주목을 받았고,\n 성녀로서 수련을 받게 되었습니다.\n\n 그러나 그녀는 단순히 역할에 만족하지 않고\n 자신의 힘으로 사람들을 진정으로 돕고 싶어했습니다.",
"종족: 마법 슬라임\n\n성별: 없음 \n(하지만 모든 파티원이 각각 다르게 부릅니다. \n루미엘은 '그 아이', \n셀레나는 '얘', \n레온은 '녀석', \n에린은 '슬리'로 부름.)\n\n나이: 추정 불가 (외관상 아기처럼 보임)\n\n출신지: 불명의 고대 유적 (마법으로 태어난 존재)\n\n역할: 파티의 귀여운 마스코트이자, \n서포터 겸 의외의 전투원\n\n슬리는 원래 고대 유적지에서 잠들어 있던 존재로,\n 루미엘이 처음으로 발견했습니다.\n\n 유적의 신성한 에너지가 반응하며 \n슬라임이 생명체로 깨어났고,\n 파티원들과 함께 행동하기 시작했습니다."
};
int x = 60;
for (int i = 0; i < characters.length; i++) {
final int index = i; // i를 final 변수로 캡처
String character = characters[i];
String imagePath = imagePaths[i];
JButton button = new JButton(character);
button.setBounds(x + i * 30, 600, 120, 50);
button.addActionListener(e -> {
selectedCharacter = character;
charImageLabel.setIcon(scaleImageToLabel(new ImageIcon(imagePath), charImageLabel));
charDescLabel.setText(character); // 캐릭터 이름 변경
descriptionLabel.setOpaque(true);
descriptionLabel.setForeground(Color.black);
descriptionLabel.setBackground(Color.LIGHT_GRAY);
descriptionLabel.setText("<html>" + characterDescriptions[index].replace("\n", "<br>") + "</html>"); // 캐릭터 설명 변경
});
charSelectionPanel.add(button);
x += 120;
}
JButton confirmButton = new JButton("확인");
confirmButton.setBounds(350, 680, 100, 50);
confirmButton.addActionListener(e -> {
if (!selectedCharacter.isEmpty()) {
JOptionPane.showMessageDialog(this, selectedCharacter + "로 게임을 시작합니다!", "캐릭터 선택 완료", JOptionPane.INFORMATION_MESSAGE);
if (check == false) {
JOptionPane.showMessageDialog(this, "블럭이 20, 40, 60마다 장애물이 생깁니다!", "장애물 팁", JOptionPane.INFORMATION_MESSAGE);
check = true;
}
startGame(speed, difficulty,selectedCharacter);
} else {
JOptionPane.showMessageDialog(this, "캐릭터를 선택해주세요!", "오류", JOptionPane.WARNING_MESSAGE);
}
});
charSelectionPanel.add(confirmButton);
getContentPane().add(charSelectionPanel);
revalidate();
repaint();
}
// 이미지 크기를 라벨 크기에 맞게 조정하는 메서드
private ImageIcon scaleImageToLabel(ImageIcon icon, JLabel label) {
Image img = icon.getImage();
int width = label.getWidth();
int height = label.getHeight();
Image scaledImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH); // 라벨 크기에 맞게 이미지 조정
return new ImageIcon(scaledImg);
}
private void startGame(int speed, int difficulty, String selectedCharacter) {
gameSpeed = speed;
currentDifficulty = difficulty; // 현재 난이도 저장
initializeGameBoard(difficulty,selectedCharacter);
// 제한시간 초기화 및 표시
remainingTime = 180;
timeLabel.setText("남은 시간: 03:00");
// 제한시간 타이머 시작
startCountdownTimer();
// 블록 이동 타이머 시작
timer = new Timer(gameSpeed, e -> moveBlockDown());
timer.start();
}
private void startCountdownTimer() {
countdownTimer = new Timer(1000, e -> {
remainingTime--;
// 시간 포맷팅 및 라벨 업데이트
int minutes = remainingTime / 60;
int seconds = remainingTime % 60;
timeLabel.setText(String.format("남은 시간: %02d:%02d", minutes, seconds));
if (remainingTime <= 0) {
countdownTimer.stop();
timer.stop();
musicManager.stopMusic(); // 게임 오버 후 음악 멈추기
musicManager.playMusic("sings/gameover.wav"); // 게임 오버 소리 재생
JOptionPane.showMessageDialog(this, "시간 초과! 게임 오버!", "알림", JOptionPane.INFORMATION_MESSAGE);
resetGame(); // 게임 초기화
}
});
countdownTimer.start(); // 타이머 시작
}
private void initializeGameBoard(int difficulty,String selectedCharacter) {
currentDifficulty = difficulty;
getContentPane().removeAll();
revalidate();
repaint();
musicManager.stopMusic(); // 기존 음악 정지
// 음악 파일 경로가 유효하면 재생
if (getBackgroundMusic() != null) {
musicManager.playMusic(getBackgroundMusic());
}
if (difficulty == 1) {
easyIcon = new ImageIcon("images/easy.jpg");
}
else if (difficulty == 2) {
easyIcon = new ImageIcon("images/normal.jpg");
}
else if (difficulty == 3) {
easyIcon = new ImageIcon("images/hard.jpg");
}
//"에린 카르테스", "레온 하르트", "셀레나 블레이즈", "루미엘 에테리아", "슬리"
if (selectedCharacter.equals("에린 카르테스")) {chIcon = new ImageIcon("images/ch/man_1.png"); abIcon = new ImageIcon("images/ability/sword.png");}
else if (selectedCharacter.equals("레온 하르트")) {chIcon = new ImageIcon("images/ch/man_2.png"); abIcon = new ImageIcon("images/ability/shield_icon.png");}
else if (selectedCharacter.equals("셀레나")) {chIcon = new ImageIcon("images/ch/woman_1.png"); abIcon = new ImageIcon("images/ability/fire.png");}
else if (selectedCharacter.equals("루미엘")) {chIcon = new ImageIcon("images/ch/woman_2.png"); abIcon = new ImageIcon("images/ability/cross.png");}
else if (selectedCharacter.equals("슬리")) {chIcon = new ImageIcon("images/ch/slime.png"); abIcon = new ImageIcon("images/ability/red.png");}
easyLabel = new JLabel(easyIcon);
easyLabel.setLayout(null);
easyLabel.setBounds(0, 0, getWidth(), getHeight());
gameLabel = new JLabel();
gameLabel.setBounds(100, 100, 250, 600);
gameLabel.setOpaque(true);
gameLabel.setBackground(Color.BLACK);
gameLabel.setLayout(new GridLayout(20, 10));
easyLabel.add(gameLabel);
// 다음 블럭을 보여줄 4x4 라벨 생성 및 위치 지정
nextBlockLabel = new JLabel();
nextBlockLabel.setBounds(400, 100, 100, 100);
nextBlockLabel.setLayout(new GridLayout(4, 4)); // 4x4 그리드 설정
easyLabel.add(nextBlockLabel);
holdLabel = new JLabel();
holdLabel.setBounds(400, 220, 100, 100);
holdLabel.setOpaque(true); // 배경을 보이게 설정
holdLabel.setBackground(Color.black); // 디버깅용 배경색 추가
holdLabel.setLayout(new GridLayout(4, 4)); // 4x4 그리드 설정
easyLabel.add(holdLabel);
timeLabel = new JLabel("남은 시간: 03:00");
timeLabel.setBounds(400, 340, 100, 100); // 위치와 크기 설정
timeLabel.setForeground(Color.WHITE); // 글자 색상 설정
timeLabel.setOpaque(true); // 배경을 보이게 설정
timeLabel.setBackground(Color.black); // 디버깅용 배경색 추가
easyLabel.add(timeLabel);
// 현재 진행 상황을 표시할 라벨 추가
progressLabel = new JLabel(String.format("블록: %d / %d", clearedBlocks, totalBlocks));
progressLabel.setBounds(400, 460, 100, 50);
progressLabel.setForeground(Color.WHITE); // 글자 색상 설정
progressLabel.setOpaque(true); // 배경을 보이게 설정
progressLabel.setBackground(Color.BLACK);
easyLabel.add(progressLabel);
if (totalScore > highestScore) {
highestScore = totalScore;
}
totalScore = 0;
scoreLabel = new JLabel(String.format("<html>현재점수/최고점수<br> %d / %d", totalScore, highestScore));
scoreLabel.setBounds(400, 520, 100, 50); // 위치와 크기 설정
scoreLabel.setForeground(Color.WHITE); // 글자 색상 설정
scoreLabel.setOpaque(true); // 배경 활성화
scoreLabel.setBackground(Color.BLACK); // 배경색 설정
easyLabel.add(scoreLabel); // 게임 화면에 추가s
explainlabel = new JLabel("<html>Z : 블록 다운<br>X : 홀딩<br>C : 능력 사용</html>");
if (selectedCharacter.equals("루미엘")) {explainlabel.setText("<html>Z : 블록 다운<br>X : 홀딩<br>능력 사용 : 패시브</html>");}
explainlabel.setBounds(400, 580, 100, 100); // 위치와 크기 설정
explainlabel.setForeground(Color.WHITE); // 글자 색상 설정
explainlabel.setOpaque(true); // 배경을 보이게 설정
explainlabel.setBackground(Color.black); // 디버깅용 배경색 추가
easyLabel.add(explainlabel);
overlayImageIcon = new ImageIcon("images/ch/devil.png"); // 미리 로드
overlayLabel = new JLabel(overlayImageIcon);
overlayLabel.setBounds(0, 0, getWidth(), getHeight());
overlayLabel.setOpaque(false);
overlayLabel.setVisible(false);
easyLabel.add(overlayLabel);
//능력에 대한 이미지를 넣고 사용지 없는것처럼 보이게 할 겁니다.
abilitylabel = new JLabel(abIcon);
abilitylabel.setBounds(550, 130, 100, 50); // 위치와 크기 설정
abilitylabel.setOpaque(false); // 배경을 보이게 설정
// 이미지 크기를 라벨 크기에 맞게 조정
Image abimg = abIcon.getImage();
int abwidth = abilitylabel.getWidth();
int abheight = abilitylabel.getHeight();
Image abscaledImg = abimg.getScaledInstance(abwidth, abheight, Image.SCALE_SMOOTH); // 라벨 크기에 맞게 이미지 크기 조정
abIcon = new ImageIcon(abscaledImg); // 크기 조정된 이미지를 다시 chIcon에 저장
abilitylabel.setIcon(abIcon); // 크기 조정된 이미지를 라벨에 적용
easyLabel.add(abilitylabel);
// 캐릭터 이미지 라벨 생성 및 크기 조정
chlabel = new JLabel(chIcon);
chlabel.setBounds(550, 200, 200, 500); // 위치와 크기 설정
chlabel.setOpaque(false); // 배경을 보이게 설정
// 이미지 크기를 라벨 크기에 맞게 조정
Image img = chIcon.getImage();
int width = chlabel.getWidth();
int height = chlabel.getHeight();
Image scaledImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH); // 라벨 크기에 맞게 이미지 크기 조정
chIcon = new ImageIcon(scaledImg); // 크기 조정된 이미지를 다시 chIcon에 저장
chlabel.setIcon(chIcon); // 크기 조정된 이미지를 라벨에 적용
easyLabel.add(chlabel);
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 10; j++) {
cellLabels[i][j] = new JLabel();
cellLabels[i][j].setOpaque(true);
cellLabels[i][j].setBackground(Color.BLACK);
gameLabel.add(cellLabels[i][j]);
}
}
clearedBlocks=0;
progressLabel.setText(String.format("블록: %d / %d", clearedBlocks, totalBlocks));
// 첫 블록과 다음 블록 설정
Random rand = new Random();
blockType = rand.nextInt(SHAPE.length); // 현재 블록 랜덤 생성
nextBlockType = rand.nextInt(SHAPE.length); // 다음 블록 랜덤 생성
// 다음 블록 표시
showNextBlock();
getContentPane().add(easyLabel);
revalidate();
repaint();
startFallingBlock();
}
private void startFallingBlock() {
rotation = 0; // 초기 회전 상태
currentX = 0; // 초기 X 위치
currentY = 3; // 초기 Y 위치
blockStartTime = System.currentTimeMillis(); // 블록 시작 시간 기록
currentColor = getColorForBlock(blockType); // 현재 블록의 색상 설정
// 게임 오버 여부 확인
if (isGameOver()) {
timer.stop();
musicManager.stopMusic(); // 게임 오버 후 음악 멈추기
musicManager.playMusic("sings/gameover.wav"); // 게임 오버 소리 재생
JOptionPane.showMessageDialog(this, "게임 오버!", "알림", JOptionPane.INFORMATION_MESSAGE);
resetGame();
return;
}
// 현재 블록을 화면에 그림
drawBlock(rotation);
}
// 다음에 나타날 블럭을 nextBlockLabel에 표시하는 메소드
private void showNextBlock() {
nextBlockLabel.removeAll(); // 기존 블록 지우기
if (nextBlockType != -1) {
int[][] shape = SHAPE[nextBlockType][0]; // 초기 회전 상태
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
JLabel cell = new JLabel();
cell.setOpaque(true);
if (shape[i][j] == 1) {
cell.setBackground(getColorForBlock(nextBlockType)); // 색상 설정
} else {
cell.setBackground(Color.BLACK); // 빈 칸은 검정
}
nextBlockLabel.add(cell);
}
}
}
nextBlockLabel.revalidate();
nextBlockLabel.repaint();
}
private void drawBlock(int rotation) {
clearBoard(); // 기존 블록의 셀만 초기화
int[][] shape;
if (blockType == -2) { // 에린의 능력 블록
shape = new int[][] {
{1, 1},
{1, 1},
{1, 1},
{1, 1},
};
} else if (blockType == -1) { // 셀레나의 능력 블록 (1x1 하얀 블록)
shape = new int[][] { {1} };
} else {
shape = SHAPE[blockType][rotation];
}
for (int i = 0; i < shape.length; i++) {
for (int j = 0; j < shape[i].length; j++) {
if (shape[i][j] == 1) {
int x = currentX + i;
int y = currentY + j;
if (x >= 0 && x < 20 && y >= 0 && y < 10) {
if (blockType == -1) {
// 능력 블록인 경우 이미지 설정
ImageIcon fireIcon = new ImageIcon("images/ability/fire.png");
setBlockImage(fireIcon, x, y);
} else if(blockType == -2) {
ImageIcon swordIcon = new ImageIcon("images/ability/sword.png");
setBlockImage(swordIcon, x, y);
}
else {
// 일반 블록인 경우 색상 설정
cellLabels[x][y].setBackground(getColorForBlock(blockType));
cellLabels[x][y].setIcon(null);
}
}
}
}
}
}
// 블록 색을 설정하는 메소드
private Color getColorForBlock(int blockType) {
switch (blockType) {
case 0: return Color.CYAN; // I
case 1: return Color.YELLOW; // O
case 2: return Color.GREEN; // S
case 3: return Color.GRAY; // Z
case 4: return Color.BLUE; // L
case 5: return Color.PINK; // T
case 6: return Color.ORANGE; // J
default: return Color.WHITE; // 기본 값
}
}
// 블록을 아래로 이동
private void moveBlockDown() {
if (blockType == -1) { // Serena의 능력 블록일 경우
// 능력 블록이 아래로 이동할 수 있는지 확인
if (canMove(currentX + 1, currentY)) {
currentX++; // 이동 가능하면 아래로 이동
drawBlock(rotation); // 블록 다시 그리기
} else {
// 이동 불가능한 경우에만 블록 제거 및 다음 블록으로 전환
removeSurroundingBlocks(currentX, currentY);
blockType = nextBlockType;
Random rand = new Random();
nextBlockType = rand.nextInt(SHAPE.length); // 새 블록 랜덤 설정
showNextBlock(); // 다음 블록 표시
startFallingBlock(); // 새로운 블록 시작
}
} else if (blockType != -2){
// 일반 블록 처리
if (canMove(currentX + 1, currentY)) {
currentX++; // 이동 가능하면 아래로 이동
drawBlock(rotation);
} else {
fixBlock(); // 이동 불가능하면 블록 고정
}
}
if (blockType == -2) { // 에린의 능력 블록일 경우
// 이동 중 충돌한 블록을 삭제
deleteCollidedBlock(currentX, currentY);
// 아래로 이동 가능한지 확인
if (canMove(currentX + 1, currentY)) {
currentX++;
drawBlock(rotation); // 블록을 화면에 그리기
} else {
// 더 이상 이동 불가 -> 바닥 도달 시 능력 블록 제거
clearCurrentBlock();
// 다음 블록 생성
blockType = nextBlockType;
Random rand = new Random();
nextBlockType = rand.nextInt(SHAPE.length);
showNextBlock(); // 다음 블록 표시
startFallingBlock(); // 새로운 블록 시작
}
} else {
if (canMove(currentX + 1, currentY)) {
// 이동 가능하면 이동
currentX++;
drawBlock(rotation);
// 능력 블록의 새로운 위치에 이미지 설정
if (blockType == -1) {
ImageIcon fireIcon = new ImageIcon("images/ability/fire.png");
setBlockImage(fireIcon, currentX, currentY);
}
} else {
fixBlock(); // 일반 블록은 고정
}
}
}
// 블록 이동 여부 체크
private boolean canMove(int x, int y) {
int[][] shape = blockType >= 0 ? SHAPE[blockType][rotation] : new int[][] { {1} }; // Serena 능력 블록의 모양
for (int i = 0; i < shape.length; i++) {
for (int j = 0; j < shape[i].length; j++) {
if (shape[i][j] == 1) {
int newX = x + i;
int newY = y + j;
// 경계를 벗어나거나 고정된 블록과 충돌 여부 확인
if (newX >= 20 || newY < 0 || newY >= 10 || board[newX][newY] == 1) {
return false; // 이동 불가
}
}
}
}
return true; // 이동 가능
}
// 블럭 생성 시 고정된 블럭과의 충돌 여부를 체크하여 게임 오버 상태를 결정하는 메소드
private boolean isGameOver() {
int[][] shape = SHAPE[blockType][rotation];
for (int i = 0; i < shape.length; i++) {
for (int j = 0; j < shape[i].length; j++) {
if (shape[i][j] == 1 && board[currentX + i][currentY + j] == 1) {
// 게임 오버 상태에서 성녀 부활 기능 체크
if (selectedCharacter.equals("루미엘") && !abilityUsed) {
ruminel(); // 외부 클래스의 메서드 호출
return false; // 게임 오버 방지
}
return true; // 부활 불가 시 게임 오버
}
}
}
return false;
}
private void showOverlayImage(int durationMillis) {
overlayLabel.setVisible(true); // 이미지 표시
Timer timer = new Timer(durationMillis, e -> {
overlayLabel.setVisible(false); // 1초 후 숨김
});
timer.setRepeats(false);
timer.start();
}
private void fixBlock() {
if (blockType == -1) {
// 능력 블록일 경우 주변 블록 제거
removeSurroundingBlocks(currentX, currentY);
// 새로운 블록 시작
blockType = nextBlockType;
Random rand = new Random();
nextBlockType = rand.nextInt(SHAPE.length);
showNextBlock(); // 다음 블록 표시
startFallingBlock(); // 새로운 블록 시작
return; // 이후 일반 블록 고정 로직 실행하지 않음
}
// 일반 블록 고정
int[][] shape = blockType >= 0 ? SHAPE[blockType][rotation] : new int[][] { {1} };
for (int i = 0; i < shape.length; i++) {
for (int j = 0; j < shape[i].length; j++) {
if (shape[i][j] == 1) {
board[currentX + i][currentY + j] = 1;
cellLabels[currentX + i][currentY + j].setBackground(currentColor);
}
}
}
clearFullLines(); // 줄 삭제 확인
// 블록 내려온 시간 측정 및 점수 계산
long blockEndTime = System.currentTimeMillis();
long elapsedTime = (blockEndTime - blockStartTime) / 1000; // 초 단위로 변환
if (elapsedTime <= 0.5) {
totalScore += 5;
} else if (elapsedTime <= 1) {
totalScore += 3;
} else {
totalScore += 1;
}
//String.format("블록: %d / %d", clearedBlocks, totalBlocks)
scoreLabel.setText(String.format("<html>현재점수/최고점수<br> %d / %d", totalScore, highestScore));
holdUsed = false; // 홀드 사용 가능 상태 초기화
clearedBlocks++;
updateProgress();
if (clearedBlocks >= totalBlocks) {
timer.stop();
countdownTimer.stop();
handleRewards(currentDifficulty);
resetGame();
return;
}
// 방향키 잠금 활성화 조건
if ((clearedBlocks == 20 || clearedBlocks == 40 || clearedBlocks == 60) && !isDirectionLocked) {
int randomInt = (int) (Math.random() * 2) + 1; // 1에서 10 사이의 정수
if (randomInt == 1) {
isDirectionLocked = true; // 방향키 잠금
lockedBlocksCount = 0; // 잠금 상태에서 떨어진 블록 개수 초기화
} else if (randomInt == 2) {
generateRandomObstacle();
}
showOverlayImage(1000);
musicManager.playMusic("sings/devil_sound.wav");
musicManager.clip.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) {
musicManager.playMusic(getBackgroundMusic());
}
});
}
// 잠금 상태에서 떨어진 블록 카운트
if (isDirectionLocked) {
lockedBlocksCount++;
if (lockedBlocksCount > 1) {
isDirectionLocked = false; // 블록 2개가 떨어지면 잠금 해제
}
}
blockType = nextBlockType; // 현재 블록을 다음 블록으로 설정
Random rand = new Random();
nextBlockType = rand.nextInt(SHAPE.length);
showNextBlock(); // 다음 블록 UI 갱신
startFallingBlock(); // 새로운 블록 시작
}
// 랜덤 이미지 배치하는 함수
private void generateRandomObstacle() {
Random rand = new Random();
// 모든 블록을 2칸 위로 이동
for (int y = 2; y < 20; y++) { // 아래에서 위로 이동
for (int x = 0; x < 10; x++) {
board[y - 2][x] = board[y][x];
cellLabels[y - 2][x].setBackground(cellLabels[y][x].getBackground());
cellLabels[y][x].setBackground(Color.BLACK); // 기존 위치 초기화
board[y][x] = 0;
}
}
// 두 줄의 빨간색 장애물 생성
for (int y = 18; y < 20; y++) { // 하단 두 줄(18, 19)
int emptyIndex = rand.nextInt(10); // 각 줄에 1x1 빈 자리 생성
for (int x = 0; x < 10; x++) {
if (x == emptyIndex) {
// 빈 칸 설정
board[y][x] = 0;
cellLabels[y][x].setBackground(Color.BLACK);
} else {
// 빨간색 블록 설정
board[y][x] = 1;
cellLabels[y][x].setBackground(Color.RED);
}
}
}
}
// 진행 상황 라벨 업데이트
private void updateProgress() {
progressLabel.setText(String.format("블록: %d / %d", clearedBlocks, totalBlocks));
}
// 게임 재시작을 위한 메소드 수정
private void resetGame() {
musicManager.stopMusic();
// 제한시간 초기화
remainingTime = 180;
abilityUsed = false;
// 제한시간 타이머 중지
if (countdownTimer != null) {
countdownTimer.stop();
countdownTimer = null; // 이전 타이머 해제
}
// 게임 타이머 중지
if (timer != null) {
timer.stop();
timer = null; // 이전 타이머 해제
}
// 게임 보드 초기화
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 10; j++) {
board[i][j] = 0;
cellLabels[i][j].setBackground(Color.BLACK); // 보드 색 초기화
}
}
// 다음 블록 라벨 초기화
if (nextBlockLabel != null) {
nextBlockLabel.removeAll();
nextBlockLabel.revalidate();
nextBlockLabel.repaint();
}
// 메인 화면으로 돌아가기
getContentPane().removeAll();
getContentPane().add(label);
startButton.setVisible(true);
exitButton.setVisible(true);
if (easyButton != null) easyButton.setVisible(false);
if (mediumButton != null) mediumButton.setVisible(false);
if (hardButton != null) hardButton.setVisible(false);
abilityUsed = false;
revalidate();
repaint();
}
private void handleRewards(int difficulty) {
if (difficulty == 1 && !isEasyCleared) {
isEasyCleared = true;
JOptionPane.showMessageDialog(this, "축하합니다! \n골드: 10000, 정수: 250\n 칭호 : <하의 정복자>", "Easy 보상", JOptionPane.INFORMATION_MESSAGE);
} else if (difficulty == 2 && !isMediumCleared) {
isMediumCleared = true;
JOptionPane.showMessageDialog(this, "축하합니다! \n골드: 20000, 정수: 500\n 칭호 : <중의 정복자>", "Medium 보상", JOptionPane.INFORMATION_MESSAGE);
} else if (difficulty == 3 && !isHardCleared) {
isHardCleared = true;
JOptionPane.showMessageDialog(this, "축하합니다! \n골드: 30000, 정수: 750\n 칭호 : <상의 정복자>", "Hard 보상", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "이미 정복한 난이도입니다. 보상이 지급되지 않습니다.", "알림", JOptionPane.WARNING_MESSAGE);
}
if (isEasyCleared && isMediumCleared && isHardCleared) {
JOptionPane.showMessageDialog(this, "축하합니다! 모든 난이도를 정복했습니다! 칭호: '완전한 정복자'", "정복자 칭호", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this, "에린파티의 서브 스토리가 해금되었습니다.", "스토리 해금", JOptionPane.INFORMATION_MESSAGE);
}
}
private void erin() {
if (abilityUsed) return; // 이미 능력을 사용했다면 실행하지 않음
musicManager.playMusic("sings/knife.wav");
// 효과음 종료 후 배경음악 재생
musicManager.clip.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) {
musicManager.playMusic(getBackgroundMusic());
}
});
// 기존 블록 제거
clearCurrentBlock();
// 능력 블록 생성
blockType = -2; // 에린 특수 블록 타입
rotation = 0;
currentX = 0; // 최상단에서 시작
currentY = 3; // 중앙 정렬
ImageIcon swordIcon = new ImageIcon("images/ability/sword.png");
setBlockImage(swordIcon, currentX, currentY);
// 능력 블록 화면 표시
drawBlock(rotation);
abilityUsed = true; // 능력 사용 상태 갱신
abilitylabel.setVisible(false); // 능력 버튼 숨김
}
private void deleteCollidedBlock(int x, int y) {
// 에린의 능력 블록 크기 (4x2)
int[][] erinBlockShape = blockType >= 0 ? SHAPE[blockType][rotation] : new int[][] { {1,1},{1,1},{1,1},{1,1} };
for (int i = 0; i < erinBlockShape.length; i++) {
for (int j = 0; j < erinBlockShape[i].length; j++) {
if (erinBlockShape[i][j] == 1) {
int checkX = x + i; // 현재 X 위치
int checkY = y + j; // 현재 Y 위치
// 보드 범위를 벗어나지 않도록 체크
if (checkX >= 0 && checkX < 20 && checkY >= 0 && checkY < 10) {
if (board[checkX][checkY] == 1) { // 고정된 블록이 있다면
board[checkX][checkY] = 0; // 보드에서 제거
cellLabels[checkX][checkY].setBackground(Color.BLACK); // UI 초기화
cellLabels[checkX][checkY].setIcon(null); // 아이콘 제거
}
}
}
}
}
}
private void reon() {
if (abilityUsed) return; // 이미 능력을 사용했다면 실행되지 않음
musicManager.playMusic("sings/knife2.wav");
musicManager.clip.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) {
musicManager.playMusic(getBackgroundMusic());
}