-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.java
More file actions
660 lines (612 loc) · 21.5 KB
/
test.java
File metadata and controls
660 lines (612 loc) · 21.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
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
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.sound.sampled.*;
import javax.swing.*;
class Tile{
int x;
int y;
public Tile(int x0,int y0){
x = x0;
y = y0;
}
}
public class SnakeDemo extends JComponent{
/**
*
*/
private static final long serialVersionUID = 3794762291171148906L;
private final int MAX_SIZE = 400;//蛇身体最长为400节
private Tile temp = new Tile(0,0);
private Tile temp2 = new Tile(0,0);
private Tile head = new Tile(227,100);//头部的位置初始化为(227,100)
private Tile[] body = new Tile[MAX_SIZE];
private String direction = "R";//默认向右走
private String current_direction = "R";//当前方向
private boolean first_launch = false;
private boolean iseaten = false;
private boolean isrun = true;
private int randomx,randomy;
private int body_length = 5;//身体长度初始化为5
private Thread run;
private JLabel label = new JLabel("当前长度:");
private JLabel label2 = new JLabel("所花时间:");
private JLabel label3 = new JLabel("说 明:");
private JTextArea explain = new JTextArea("此游戏是一个贪吃蛇Demo版本,实现简单地移动,得分,判断撞墙和撞自己的功能,"
+ "初始长度为6,头部为红色,身体的颜色渐变。游戏本身代码只有300行,加上一些显示,计时和音效后多了几百行。\n"
+ "游戏界面按上下左右键实现移动,按ESC重新开始,按空格键可以实现暂停和开始");
private JLabel Score = new JLabel("6");
private JLabel Time = new JLabel("");
private Font f = new Font("微软雅黑",Font.PLAIN,15);
private Font f2 = new Font("微软雅黑",Font.PLAIN,13);
private JPanel p = new JPanel();
private int hour =0;
private int min =0;
private int sec =0 ;
private boolean pause = false;
public SnakeDemo(){
String lookAndFeel =UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(lookAndFeel);
} catch (ClassNotFoundException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
} catch (InstantiationException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
//布局
add(label);
label.setBounds(500, 10, 80, 20);
label.setFont(f);
add(Score);
Score.setBounds(500, 35, 80, 20);
Score.setFont(f);
add(label2);
label2.setBounds(500, 60, 80, 20);
label2.setFont(f);
add(Time);
Time.setBounds(500, 85, 80, 20);
Time.setFont(f);
add(p);
p.setBounds(498, 110, 93, 1);
p.setBorder(BorderFactory.createLineBorder(Color.black));
add(label3);
label3.setBounds(500, 115, 80, 20);
label3.setFont(f);
add(explain);
explain.setBounds(498, 138, 100, 350);
explain.setFont(f2);
explain.setLineWrap(true);
explain.setOpaque(false);
for(int i = 0; i < MAX_SIZE;i++)
{
body[i] = new Tile(0,0);
}
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(isrun && current_direction != "L")
{
direction = "R";
}
}
if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(isrun && current_direction != "R")
{
direction = "L";
}
}
if(e.getKeyCode() == KeyEvent.VK_UP)
{
if(isrun && current_direction != "D")
{
direction = "U";
}
}
if(e.getKeyCode() == KeyEvent.VK_DOWN)
{
if(isrun && current_direction != "U")
{
direction = "D";
}
}
if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int i = 0; i < MAX_SIZE;i++)
{
body[i].x = 0;
body[i].y = 0;
}
run = new Thread();
run.start();
System.out.println("Start again");
}
if(e.getKeyCode() == KeyEvent.VK_SPACE)//按空格键开始和暂停暂时没做,还在思考中
{
if(!pause)//暂停
{
pause = true;
isrun = false;
}
else//开始
{
pause = false;
isrun = true;
}
}
}
});
new Timer();
setFocusable(true);
}
public void paintComponent(Graphics g1){
super.paintComponent(g1);
Graphics2D g = (Graphics2D) g1;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,RenderingHints.VALUE_STROKE_NORMALIZE);
//画头部
g.setColor(Color.red);
g.fillRoundRect(head.x, head.y, 20, 20, 10, 10);
g.setPaint(new GradientPaint(115,135,Color.CYAN,230,135,Color.MAGENTA,true));
if(!first_launch)
{
//初始化身体
int x = head.x;
for(int i = 0;i < body_length;i++)
{
x -= 22;//相邻两个方块的间距为2个像素,方块宽度都为20像素
body[i].x = x;
body[i].y = head.y;
g.fillRoundRect(body[i].x, body[i].y, 20, 20, 10, 10);
}
//初始化食物位置
ProduceRandom();
g.fillOval(randomx, randomy, 19, 19);
}
else
{
//每次刷新身体
for(int i = 0;i < body_length;i++)
{
g.fillRoundRect(body[i].x, body[i].y, 20, 20, 10, 10);
}
if(EatFood())//被吃了重新产生食物
{
ProduceRandom();
g.fillOval(randomx, randomy, 19, 19);
iseaten = false;
}
else
{
g.fillOval(randomx, randomy, 19, 19);
}
}
first_launch = true;
//墙
g.setStroke( new BasicStroke(4,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL));
g.setBackground(Color.black);
g.drawRect(2, 7, 491, 469);
//网格线
for(int i = 1;i < 22;i++)
{
g.setStroke( new BasicStroke(1,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL));
g.setColor(Color.black);
g.drawLine(5+i*22,9,5+i*22,472);
if(i <= 20)
{
g.drawLine(4,10+i*22,491,10+i*22);
}
}
}
public void ProduceRandom(){
boolean flag = true;
Random rand = new Random();
randomx = (rand.nextInt(21) + 1) * 22 + 7;
randomy = (rand.nextInt(20) + 1) *22 + 12;
while(flag)
{
for(int i = 0;i < body_length; i++)
{
if(body[i].x == randomx && body[i].y == randomy)
{
randomx = (rand.nextInt(21) + 1) * 22 + 7;
randomy = (rand.nextInt(20) + 1) *22 + 12;
flag = true;
break;
}
else
{
if(i == body_length - 1)
{
flag = false;
}
}
}
}
}
public void HitWall(){//判断是否撞墙
if(current_direction == "L")
{
if(head.x < 7)
{
new AePlayWave("over.wav").start();
isrun = false;
int result=JOptionPane.showConfirmDialog(null, "Game over! Try again?", "Information", JOptionPane.YES_NO_OPTION);
if(result==JOptionPane.YES_NO_OPTION)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int i = 0; i < MAX_SIZE;i++)
{
body[i].x = 0;
body[i].y = 0;
}
run = new Thread();
run.start();
System.out.println("Start again");
}
else
{
run.stop();
}
}
}
if(current_direction == "R")
{
if(head.x > 489)
{
new AePlayWave("over.wav").start();
isrun = false;
int result=JOptionPane.showConfirmDialog(null, "Game over! Try again?", "Information", JOptionPane.YES_NO_OPTION);
if(result==JOptionPane.YES_NO_OPTION)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int i = 0; i < MAX_SIZE;i++)
{
body[i].x = 0;
body[i].y = 0;
}
run = new Thread();
run.start();
System.out.println("Start again");
}
else
{
run.stop();
}
}
}
if(current_direction == "U")
{
if(head.y < 12)
{
new AePlayWave("over.wav").start();
isrun = false;
int result=JOptionPane.showConfirmDialog(null, "Game over! Try again?", "Information", JOptionPane.YES_NO_OPTION);
if(result==JOptionPane.YES_NO_OPTION)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int i = 0; i < MAX_SIZE;i++)
{
body[i].x = 0;
body[i].y = 0;
}
run = new Thread();
run.start();
System.out.println("Start again");
}
else
{
run.stop();
}
}
}
if(current_direction == "D")
{
if(head.y > 472)
{
new AePlayWave("over.wav").start();
isrun = false;
int result=JOptionPane.showConfirmDialog(null, "Game over! Try again?", "Information", JOptionPane.YES_NO_OPTION);
if(result==JOptionPane.YES_NO_OPTION)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int i = 0; i < MAX_SIZE;i++)
{
body[i].x = 0;
body[i].y = 0;
}
run = new Thread();
run.start();
System.out.println("Start again");
}
else
{
run.stop();
}
}
}
}
public void HitSelf(){//判断是否撞到自己身上
for(int i = 0;i < body_length; i++)
{
if(body[i].x == head.x && body[i].y == head.y)
{
new AePlayWave("over.wav").start();
isrun = false;
int result=JOptionPane.showConfirmDialog(null, "Game over! Try again?", "Information", JOptionPane.YES_NO_OPTION);
if(result==JOptionPane.YES_NO_OPTION)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int j = 0; j < MAX_SIZE;j++)
{
body[j].x = 0;
body[j].y = 0;
}
run = new Thread();
run.start();
System.out.println("Start again");
}
else
{
run.stop();
}
break;
}
}
}
public boolean EatFood(){
if(head.x == randomx && head.y == randomy)
{
iseaten = true;
return true;
}
else
{
return false;
}
}
public void Thread(){
long millis = 300;//每隔300毫秒刷新一次
run = new Thread() {
public void run() {
while (true)
{
try {
Thread.sleep(millis);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
if(!pause)
{
temp.x = head.x;
temp.y = head.y;
//头部移动
if(direction == "L")
{
head.x -= 22;
}
if(direction == "R")
{
head.x += 22;
}
if(direction == "U")
{
head.y -= 22;
}
if(direction == "D")
{
head.y += 22;
}
current_direction = direction;//刷新当前前进方向
//身体移动
for(int i = 0;i < body_length;i++)
{
temp2.x = body[i].x;
temp2.y = body[i].y;
body[i].x = temp.x;
body[i].y = temp.y;
temp.x = temp2.x;
temp.y = temp2.y;
}
if(EatFood())
{
body_length ++;
body[body_length-1].x = temp2.x;
body[body_length-1].y = temp2.y;
Score.setText("" + (body_length+1) );
new AePlayWave("eat.wav").start();
}
repaint();
HitWall();
HitSelf();
}
}
}
};
run.start();
}
public static void main(String[] args) {
SnakeDemo t = new SnakeDemo();
t.Thread();
JFrame game = new JFrame();
Image img=Toolkit.getDefaultToolkit().getImage("title.png");//窗口图标
game.setIconImage(img);
game.setTitle("Snake By XJX");
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// game.setSize(502, 507);
game.setSize(602, 507);
game.setResizable(false);
game.setLocationRelativeTo(null);
game.add(t);
game.setVisible(true);
}
//计时器类
class Timer extends Thread{
public Timer(){
this.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
if(isrun){
sec +=1 ;
if(sec >= 60){
sec = 0;
min +=1 ;
}
if(min>=60){
min=0;
hour+=1;
}
showTime();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void showTime(){
String strTime ="" ;
if(hour < 10)
strTime = "0"+hour+":";
else
strTime = ""+hour+":";
if(min < 10)
strTime = strTime+"0"+min+":";
else
strTime =strTime+ ""+min+":";
if(sec < 10)
strTime = strTime+"0"+sec;
else
strTime = strTime+""+sec;
//在窗体上设置显示时间
Time.setText(strTime);
}
}
}
class AePlayWave extends Thread {
private String filename;
private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
public AePlayWave(String wavfile) {
filename = wavfile;
}
public void run() {
File soundFile = new File(filename);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}