Import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*;import java.util.*;import javax.swing.border.*;p ublic class Test extends japplet{private static final int up=0,down=1,left=2,right=3;private static final int wid=150,sp=10;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};p rivate 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)};p rivate Map cmap=new HashMap ();p ublic static rectobject[][] Rset=new rectobject[4][4 ];p ublic rectobject[][] list=new rectobject[4][4];p rivate my2048panel myp;private linkedlist saveList=new LinkedList () ;p rivate 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};p rivate int[] yindex={SP,2* Sp+wid,3*sp+2*wid,4*sp+3*wid};p Ublic void Paintcomponent (Graphics g) {//backgroundsuper.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 rectanglefor (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);} 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); 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);} public void Paintcomponent (Graphics g) {super.paintcomponent (g); Font font=new font ("Timesroman", font.bold,60); G.setfont (font); 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", GetHeight ()/2+20);}} public class Gobacklistener implements Actionlistener{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 initpublic 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, +); 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 ();}} Public Test () {//savethestep (); for (int i=0;i<7;i++) {cmap.put (Label[i], clo[i]);}} Moveleftpublic void MoveLeft (Boolean flag) {clearlist (list); for (inti=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 ();}} Moverightpublic 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 ();}} Moveuppublic 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 ();}} Movedownpublic 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 functionsprivate 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 rectanglepublic 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 is other steps or Notpublic 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 ();} public void Savethestep () {if (Savelist.size () <20) {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 ();}} 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 Test (), 900, 800);}}
2048 programs written in Java