java实现的2048游戏完整实例

时间:2021-09-21 01:18:44

本文实例讲述了java实现的2048游戏。分享给大家供大家参考,具体如下:

先来看看运行效果:

java实现的2048游戏完整实例

具体代码如下:

?
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
package awtdemo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
@suppresswarnings("serial")
public class game2048 extends japplet{
  @suppresswarnings("unused")
 private static final int up=0,down=1,left=2,right=3;
  private static final int wid=150,sp=10;
  @suppresswarnings("unused")
 private int scores=0;
  private static jlabel scorelabel;
  private boolean change,checkmode=false,gameoverflag=false,successflag=false;
  private int[] label={2,4,8,16,32,64,128};
  private color[] clo={
      new color(200,200,200),new color(228,228,160),new color(214,163,92),
      new color(234,124,72),new color(240,84,77),new color(255,68,53),new color(200,200,64)
  };
  @suppresswarnings("rawtypes")
 private map cmap=new hashmap();
  public static rectobject[][] rset=new rectobject[4][4];
  public rectobject[][] list=new rectobject[4][4];
  private my2048panel myp;
  @suppresswarnings("rawtypes")
 private linkedlist savelist=new linkedlist();
  private jbutton gobackbutton;
  keylistener kl=new keylistener(){
    public void keypressed(keyevent e){
      savethestep();
      gobackbutton.setvisible(true);
      if(gameoverflag==true){
        return;
      }
      if(!adirable()){
        gameover();
      }
      int key=e.getkeycode();
      switch(key){
      case keyevent.vk_up:
        change=false;
        moveup(true);
        if(change==true){
          getarandomrect();
          //savethestep();
        }
        break;
      case keyevent.vk_down:
        change=false;
        movedown(true);
        if(change==true){
          getarandomrect();
          //savethestep();
        }
        break;
      case keyevent.vk_left:
        change=false;
        moveleft(true);
        if(change==true){
          getarandomrect();
          //savethestep();
        }
        break;
      case keyevent.vk_right:
        change=false;
        moveright(true);
        if(change==true){
          getarandomrect();
          //savethestep();
        }
        break;
      }
      //savethestep();
    }
    public void keytyped(keyevent e){}
    public void keyreleased(keyevent e){}
  };
  class rectobject{
    private int value;
    public rectobject(){
      value=0;
    }
    public rectobject(rectobject obj){
      value=obj.value;
    }
    public boolean equals(object inobj){
      rectobject obj=(rectobject)inobj;
      if(obj.value==value){
        return true;
      }
      return false;
    }
  }
  class point{
    int x;
    int y;
    public point(int i,int j){
      x=i;
      y=j;
    }
  }
  class my2048panel extends jpanel{
    private int[] xindex={sp,2*sp+wid,3*sp+2*wid,4*sp+3*wid};
    private int[] yindex={sp,2*sp+wid,3*sp+2*wid,4*sp+3*wid};
    @suppresswarnings("deprecation")
 public void paintcomponent(graphics g){
      //background
      super.paintcomponent(g);
      for(int i=0;i<xindex.length;i++){
        for(int j=0;j<yindex.length;j++){
          g.setcolor(color.white);
          g.drawroundrect(xindex[i], yindex[j], wid, wid, wid/5, wid/5);
          g.setcolor(new color(197,183,129));
          g.fillroundrect(xindex[i], yindex[j], wid, wid, wid/5, wid/5);
        }
      }
      //paint rectangle
      for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
          if(rset[i][j]!=null){
            g.setcolor(color.white);
            g.drawroundrect(yindex[j], xindex[i], wid, wid, wid/5, wid/5);
            if(rset[i][j].value<128){
              g.setcolor((color)cmap.get(rset[i][j].value));
            }else{
              g.setcolor((color)cmap.get(128));
            }
            g.fillroundrect(yindex[j], xindex[i], wid, wid, wid/5, wid/5);
            g.setcolor(color.black);
            font font=new font("timesroman",font.bold,50);
            g.setfont(font);
            fontmetrics fm=toolkit.getdefaulttoolkit().getfontmetrics(font);
            int len=fm.stringwidth(""+rset[i][j].value);
            int hg=fm.getheight();
            g.drawstring(""+rset[i][j].value, yindex[j]+wid/2-len/2, xindex[i]+wid/2+hg/4);
            if(rset[i][j].value==2048 && successflag==false){
              successflag=true;
              gamesuccess();
            }
          }
        }
      }
    }
  }
  class gameoverpane extends jpanel{
    public gameoverpane(int w,int h){
      setsize(w,h);
      //setopaque(false);
    }
    @suppresswarnings("deprecation")
 public void paintcomponent(graphics g){
      super.paintcomponent(g);
      font font=new font("timesroman",font.bold,80);
      g.setfont(font);
      fontmetrics fm=toolkit.getdefaulttoolkit().getfontmetrics(font);
      int width=fm.stringwidth("game over");
      int height=fm.getheight();
      g.setcolor(new color(255,0,0));
      g.drawstring("game over!", getwidth()/2-width/2, getheight()/2-height/2);
    }
  }
  class successpane extends jpanel{
    public successpane(int w,int h){
      setsize(w,h);
      //setopaque(false);
    }
    public void paintcomponent(graphics g){
      super.paintcomponent(g);
      font font=new font("timesroman",font.bold,80);
      g.setfont(font);
      @suppresswarnings("deprecation")
  fontmetrics fm=toolkit.getdefaulttoolkit().getfontmetrics(font);
      int width=fm.stringwidth("success!");
      int height=fm.getheight();
      g.setcolor(new color(255,0,0));
      g.drawstring("success!", getwidth()/2-width/2, getheight()/2-height/2);
    }
  }
  class logo extends jpanel{
    public logo(int w ,int h){
      setsize(w,h);
    }
    @suppresswarnings("unused")
 public void paintcomponent(graphics g){
      super.paintcomponent(g);
      font font=new font("timesroman",font.bold,60);
      g.setfont(font);
      @suppresswarnings("deprecation")
  fontmetrics fm=toolkit.getdefaulttoolkit().getfontmetrics(font);
      int width=fm.stringwidth("2048");
      int height=fm.getheight();
      g.setcolor(new color(255,0,0));
      g.drawstring("2048", 20, getheight()/2+20);
    }
  }
  public class gobacklistener implements actionlistener{
    @suppresswarnings("rawtypes")
 public void actionperformed(actionevent e){
      if(savelist.size()==0){
        gobackbutton.setvisible(false);
        return;
      }
      arraylist arr=(arraylist)savelist.getlast();
      scorelabel.settext(""+arr.get(0));
      for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
          int num=(int)arr.get(4*i+j+1);
          if(num!=0){
            rset[i][j]=new rectobject();
            rset[i][j].value=num;
          }else{
            rset[i][j]=null;
          }
        }
      }
      savelist.removelast();
      repaint();
    }
  }
  public class resetlistener implements actionlistener{
    public void actionperformed(actionevent e){
      refreshbest();
      for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
          rset[i][j]=null;
        }
      }
      scorelabel.settext("0");
      repaint();
      getarandomrect();
      getarandomrect();
    }
  }
  //the applet init
  public void init(){
    container cp=getcontentpane();
    cp.setlayout(null);
    cp.setfocusable(true);
    cp.addkeylistener(kl);
    font font=new font("timesnewman",font.bold,30);
    jlabel sl=new jlabel();
    sl.setlayout(new gridlayout(2,1));
    jlabel sllb=new jlabel("scores");
    sllb.setfont(font);
    scorelabel=new jlabel("0");
    scorelabel.setfont(font);
    sl.add(sllb);
    sl.add(scorelabel);
    int best=0;
    try{
      file file=new file("bestrecord");
      if(file.exists()){
        randomaccessfile f=new randomaccessfile(file,"rw");
        best=f.readint();
        f.close();
      }
    }catch(filenotfoundexception e){
      best=0;
      e.printstacktrace();
    }catch(ioexception e){
      best=0;
      e.printstacktrace();
    }
    jlabel bsl=new jlabel();
    bsl.setlayout(new gridlayout(2,1));
    jlabel jl=new jlabel("best");
    jl.setfont(font);
    jlabel jl1=new jlabel(""+best);
    jl1.setfont(font);
    bsl.add(jl);
    bsl.add(jl1);
    myp=new my2048panel();
    logo logo=new logo(0,0);
    gobackbutton=new jbutton("undo");
    gobackbutton.setfont(font);
    gobackbutton.addactionlistener(new gobacklistener());
    gobackbutton.addkeylistener(kl);
    jbutton jb=new jbutton("reset");
    jb.setfont(font);
    jb.addactionlistener(new resetlistener());
    jb.addkeylistener(kl);
    sl.setbounds(500,20,200,80);
    bsl.setbounds(300,20,200,80);
    logo.setbounds(0, 0, 600, 100);
    myp.setbounds(0,90,700,700);
    gobackbutton.setbounds(700,250,150,60);
    jb.setbounds(700,450,150,60);
    cp.add(sl);
    cp.add(bsl);
    cp.add(logo);
    cp.add(myp);
    cp.add(gobackbutton);
    cp.add(jb);
    file f=new file("lastrecord");
    if(f.exists()){
      try{
        randomaccessfile file=new randomaccessfile(f,"rw");
        int num=file.readint();
        scorelabel.settext(""+num);
        for(int i=0;i<4;i++){
          for(int j=0;j<4;j++){
            num=file.readint();
            if(num!=0){
              rset[i][j]=new rectobject();
              rset[i][j].value=num;
            }
          }
        }
        file.close();
      }catch(filenotfoundexception e){
        e.printstacktrace();
      }catch(ioexception e){
        e.printstacktrace();
      }
    }else{
      getarandomrect();
      getarandomrect();
    }
  }
  @suppresswarnings("unchecked")
 public game2048(){
    //savethestep();
    for(int i=0;i<7;i++){
      cmap.put(label[i], clo[i]);
    }
  }
  //moveleft
  public void moveleft(boolean flag){
    clearlist(list);
    for(int i=0;i<4;i++){
      int k=0;
      for(int j=0;j<4;j++){
        if(rset[i][j]!=null){
          list[i][k++]=new rectobject(rset[i][j]);
        }
      }
    }
    for(int i=0;i<4 && flag;i++){
      for(int j=0;j<3;j++){
        if(list[i][j]!=null && list[i][j+1]!=null && list[i][j].value==list[i][j+1].value){
          list[i][j].value*=2;
          if(checkmode==false){
            int sum=integer.parseint(scorelabel.gettext());
            sum+=list[i][j].value;
            scorelabel.settext(""+sum);
          }
          list[i][j+1]=null;
          j++;
        }
      }
    }
    if(ischange()){
      if(checkmode==false){
        copyset(rset,list);
        repaint();
        moveleft(false);
      }
      change=true;
    }else{
      repaint();
    }
  }
  //moveright
  public void moveright(boolean flag){
    clearlist(list);
    for(int i=0;i<4;i++){
      int k=3;
      for(int j=3;j>-1;j--){
        if(rset[i][j]!=null){
          list[i][k--]=new rectobject(rset[i][j]);
        }
      }
    }
    for(int i=0;i<4 && flag;i++){
      for(int j=3;j>0;j--){
        if(list[i][j]!=null && list[i][j-1]!=null && list[i][j].value==list[i][j-1].value){
          list[i][j].value*=2;
          if(checkmode==false){
            int sum=integer.parseint(scorelabel.gettext());
            sum+=list[i][j].value;
            scorelabel.settext(""+sum);
          }
          list[i][j-1]=null;
          j--;
        }
      }
    }
    if(ischange()){
      if(checkmode==false){
        copyset(rset,list);
        repaint();
        moveright(false);
      }
      change=true;
    }else{
      repaint();
    }
  }
  //moveup
  public void moveup(boolean flag){
    clearlist(list);
    for(int j=0;j<4;j++){
      int k=0;
      for(int i=0;i<4;i++){
        if(rset[i][j]!=null){
          list[k++][j]=new rectobject(rset[i][j]);
        }
      }
    }
    for(int j=0;j<4 && flag;j++){
      for(int i=0;i<3;i++){
        if(list[i][j]!=null && list[i+1][j]!=null && list[i][j].value==list[i+1][j].value){
          list[i][j].value*=2;
          if(checkmode==false){
            int sum=integer.parseint(scorelabel.gettext());
            sum+=list[i][j].value;
            scorelabel.settext(""+sum);
          }
          list[i+1][j]=null;
          i++;
        }
      }
    }
    if(ischange()){
      if(checkmode==false){
        copyset(rset,list);
        repaint();
        moveup(false);
      }
      change=true;
    }else{
      repaint();
    }
  }
  //movedown
  public void movedown(boolean flag){
    clearlist(list);
    for(int j=0;j<4;j++){
      int k=3;
      for(int i=3;i>-1;i--){
        if(rset[i][j]!=null){
          list[k--][j]=new rectobject(rset[i][j]);
        }
      }
    }
    for(int j=0;j<4 && flag;j++){
      for(int i=3;i>0;i--){
        if(list[i][j]!=null && list[i-1][j]!=null && list[i][j].value==list[i-1][j].value){
          list[i][j].value*=2;
          if(checkmode==false){
            int sum=integer.parseint(scorelabel.gettext());
            sum+=list[i][j].value;
            scorelabel.settext(""+sum);
          }
          list[i-1][j]=null;
          i--;
        }
      }
    }
    if(ischange()){
      if(checkmode==false){
        copyset(rset,list);
        repaint();
        movedown(false);
      }
      change=true;
    }else{
      repaint();
    }
  }
  //other functions
  private void copyset(rectobject[][] dst, rectobject[][] src){
    for(int i=0;i<4;i++){
      for(int j=0;j<4;j++){
        dst[i][j]=src[i][j];
      }
    }
  }
  //detect whether rset is different from list or not
  private boolean ischange(){
    for(int i=0;i<4;i++){
      for(int j=0;j<4;j++){
        if(rset[i][j]!=null && list[i][j]!=null && !rset[i][j].equals(list[i][j])){
          return true;
        }
        if(rset[i][j]!=null && list[i][j]==null){
          return true;
        }
        if(rset[i][j]==null && list[i][j]!=null){
          return true;
        }
      }
    }
    return false;
  }
  private void clearlist(rectobject[][] s){
    for(int i=0;i<s.length;i++){
      for(int j=0;j<s[i].length;j++){
        s[i][j]=null;
      }
    }
  }
  //get a random rectangle
  @suppresswarnings({ "unchecked", "rawtypes" })
 public void getarandomrect(){
    arraylist list=new arraylist();
    for(int i=0;i<4;i++){
      for(int j=0;j<4;j++){
        if(rset[i][j]==null){
          list.add(new point(i,j));
        }
      }
    }
    if(list.size()==0 && !adirable()){
      gameover();
      return;
    }
    random rand=new random();
    int index=rand.nextint(list.size());
    point loc=(point)list.get(index);
    index=rand.nextint(2);
    rset[loc.x][loc.y]=new rectobject();
    if(index==1){
      rset[loc.x][loc.y].value=4;
    }else{
      rset[loc.x][loc.y].value=2;
    }
  }
  //detect whether there are other steps or not
  public boolean adirable(){
    checkmode=true;
    change=false;
    moveleft(true);
    moveright(true);
    movedown(true);
    moveup(true);
    checkmode=false;
    if(change==true){
      return true;
    }else{
      return false;
    }
  }
  public void gameover(){
    gameoverflag=true;
    jpanel jl=new gameoverpane(myp.getwidth(),myp.getheight());
    jl.setbounds(0, 0, 700, 700);
    jbutton jb1=new jbutton("again");
    font font=new font("timesroman",font.bold,30);
    jb1.setopaque(false);
    jb1.setfont(font);
    jbutton jb2=new jbutton("close");
    jb2.setsize(jb1.getsize());
    jb2.setopaque(false);
    jb2.setfont(font);
    jb1.addactionlistener(new actionlistener(){
      public void actionperformed(actionevent e){
        scorelabel.settext("0");
        myp.remove(jl);
        clearlist(rset);
        myp.validate();
        getarandomrect();
        getarandomrect();
        repaint();
        gameoverflag=false;
        refreshbest();
      }
    });
    jb2.addactionlistener(new actionlistener(){
      public void actionperformed(actionevent e){
        refreshbest();
        file f=new file("lastrecord");
        if(f.exists()){
          f.delete();
        }
        system.exit(0);
      }
    });
    jl.add(jb1);
    jl.add(jb2);
    myp.add(jl);
    jl.validate();
  }
  public void gamesuccess(){
    jpanel jl=new successpane(myp.getwidth(),myp.getheight());
    jl.setopaque(false);
    jl.setbounds(0, 0, 700, 700);
    jbutton jb1=new jbutton("continue");
    font font=new font("timesroman",font.bold,30);
    jb1.setopaque(false);
    jb1.setfont(font);
    jbutton jb2=new jbutton("close");
    jb2.setsize(jb1.getsize());
    jb2.setopaque(false);
    jb2.setfont(font);
    jb1.addactionlistener(new actionlistener(){
      public void actionperformed(actionevent e){
        myp.remove(jl);
        myp.validate();
        repaint();
      }
    });
    jb2.addactionlistener(new actionlistener(){
      public void actionperformed(actionevent e){
        refreshbest();
        system.exit(0);
      }
    });
    jl.add(jb1);
    jl.add(jb2);
    myp.add(jl);
    jl.validate();
  }
  @suppresswarnings("unchecked")
 public void savethestep(){
    if(savelist.size()<20){
      @suppresswarnings("rawtypes")
  arraylist arr=new arraylist();
      int score=integer.parseint(scorelabel.gettext());
      arr.add(score);
      for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
          if(rset[i][j]!=null){
            arr.add(rset[i][j].value);
          }else{
            arr.add(0);
          }
        }
      }
      savelist.addlast(arr);
    }else{
      savelist.removefirst();
      savethestep();
    }
  }
  public static string title(object o){
    string t=o.getclass().tostring();
    if(t.indexof("class")!=-1){
      t=t.substring(6);
    }
    return t;
  }
  public static void refreshbest(){
    try {
      int best=0;
      file f=new file("bestrecord");
      randomaccessfile file;
      if(f.exists()){
        file=new randomaccessfile(f,"rw");
        best=file.readint();
        file.seek(0);
      }else{
        file=new randomaccessfile(f,"rw");
      }
      //system.out.println("the best score is "+best);
      int cur=integer.parseint(scorelabel.gettext());
      if(cur>best){
        file.writeint(cur);
      }
      file.close();
    } catch (filenotfoundexception e1) {
      e1.printstacktrace();
    }catch(ioexception e2){
      e2.printstacktrace();
    }
  }
  @suppresswarnings("resource")
 public static void saverecord(){
    try{
      randomaccessfile file=new randomaccessfile(new file("lastrecord"),"rw");
      int score=integer.parseint(scorelabel.gettext());
      file.writeint(score);
      for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
          if(rset[i][j]!=null){
            file.writeint(rset[i][j].value);
          }else{
            file.writeint(0);
          }
        }
      }
    }catch(filenotfoundexception e){
      e.printstacktrace();
    }catch(ioexception e){
      e.printstacktrace();
    }
  }
  public static void run(japplet applet,int width,int height){
    jframe frame=new jframe(title(applet));
    frame.addwindowlistener(new windowadapter(){
      public void windowclosing(windowevent e){
        refreshbest();
        saverecord();
        //system.out.println("the score is "+scorelabel.gettext());
      }
    });
    frame.setdefaultcloseoperation(jframe.exit_on_close);
    frame.getcontentpane().add(applet);
    frame.setsize(width,height);
    applet.init();
    applet.start();
    frame.setvisible(true);
  }
  public static void main(string[] args){
    run(new game2048(), 900, 800);
  }
}

希望本文所述对大家java程序设计有所帮助。

原文链接:http://blog.csdn.net/cjc211322/article/details/40621471