欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现的2048游戏完整实例

程序员文章站 2023-12-17 16:05:52
本文实例讲述了java实现的2048游戏。分享给大家供大家参考,具体如下: 先来看看运行效果: 具体代码如下: package awtdemo; imp...

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

先来看看运行效果:

java实现的2048游戏完整实例

具体代码如下:

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);
  }
}

ps:这里再为大家推荐另两款本站2048游戏供大家参考(js实现)

在线2048游戏:

在线2048小游戏数字版:

更多关于java算法相关内容感兴趣的读者可查看本站专题:《java数据结构与算法教程》、《java操作dom节点技巧总结》、《java文件与目录操作技巧汇总》和《java缓存操作技巧汇总

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

上一篇:

下一篇: