Este artículo describe el juego 2048 implementado por Java. Compártelo para su referencia, como sigue:
Echemos un vistazo al efecto de carrera:
El código específico es el siguiente:
paquete awtdemo; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; @supresswarnings ("serial") clase pública 20102048 se extiende Japplet {@SuppessWarnings ("Usado") Private Static Inton INTENT INTENT INTENT INTENT INTENT INTENT INTENT INTENT INTENT INTENT INTENT INTENT INTENT INTENTO INTENTOS INTENTOS INTENTOS INTENTOS INFINALES PRIVADOS INTENTOS INTENTOS INTENTOS PRIVADOS INTENTOS INTENTOS PRIVADOS INTENTOS. Arriba = 0, abajo = 1, izquierda = 2, derecha = 3; Private estático final int wid = 150, sp = 10; @SupessWarnings ("sin usar") private int stands = 0; Jlabel static privado static scorelabel; cambio booleano privado, checkmode = false, gameOverflag = false, stritsflag = false; private int [] etiqueta = {2,4,8,16,32,64,128}; color privado [] clo = {nuevo color (200,200,200), nuevo color (228,228,160), nuevo color (214,163,92), nuevo color (234,124,72), nuevo color (240,84,77), nuevo color (255,68,53), nuevo color (200,200,64)}; @SupessWarnings ("RawTypes") Mapa privado CMAP = new HashMap (); Public static rectobject [] [] rset = new rectobject [4] [4]; public rectobject [] [] list = new rectobject [4] [4]; privado my2048panel myp; @SupessWarnings ("RawTypes") Private LinkedList savelist = new LinkedList (); JBUTTON PRIVADO JBUTTON BackButton; KEYLISTENER KL = new KeyListener () {public void KeyPressed (KeyEvent E) {saveTheSp (); GobackButton.SetVisible (verdadero); if (gameOverflag == true) {return; } if (! adirable ()) {gameOver (); } int key = e.getKeyCode (); switch (key) {case keyEvent.vk_up: change = false; MoveUp (verdadero); if (cambio == true) {getArandomRect (); // savethStep (); } romper; caso KeyEvent.vk_down: Change = False; MovedOwn (verdadero); if (cambio == true) {getArandomRect (); // savethStep (); } romper; caso KeyEvent.vk_left: Change = False; Moveleft (verdadero); if (cambio == true) {getArandomRect (); // savethStep (); } romper; Case KeyEvent.vk_right: Change = False; Moveright (verdadero); if (cambio == true) {getArandomRect (); // savethStep (); } romper; } // savethStep (); } public void keyTyped (KeyEvent E) {} public void KeyReleaded (KeyEvent E) {}}; class rectobject {private int value; public rectObject () {valor = 0; } public rectobject (rectobject obj) {value = obj.Value; } public boolean igual (objeto inobj) {rectobject obj = (rectobject) inobj; if (obj.Value == value) {return true; } return false; }} punto de clase {int x; int y; PUNTO PUBLIC (int i, int j) {x = i; y = j; }} clase my2048Panel extiende 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}; @SupessWarnings ("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 (nuevo color (197,183,129)); G.FillRoundrect (xindex [i], yindex [j], wid, wid, wid/5, wid/5); }} // pintar rectángulo para (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); Fuente de fuente = nueva fuente ("TimesRoman", Font.Bold, 50); G.SetFont (fuente); 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 && stritsflag == false) {strithflag = true; Gamesuccess (); }}}}}}}} Class GameOverpone extiende jpanel {public GameSoverPane (int w, int h) {setSize (w, h); // setOpaque (falso); } @Suppleswarnings ("deprecation") public void pintarComponent (Graphics g) {super.paintComponent (g); Fuente de fuente = nueva fuente ("TimesRoman", Font.Bold, 80); G.SetFont (fuente); FontMetrics fm = Toolkit.getDefaultToolkit (). GetFontMetrics (Font); int width = fm.StringWidth ("Game Over"); int altura = fm.getheight (); G.SetColor (nuevo color (255,0,0)); G.DrawString ("¡Juego Over!", GetWidth ()/2-Width/2, Getheight ()/2-Height/2); }} Class SuccessPane extiende JPanel {public SuccessPane (int w, int h) {setSize (w, h); // setOpaque (falso); } public void PaintComponent (Graphics g) {super.PaintComponent (g); Fuente de fuente = nueva fuente ("TimesRoman", Font.Bold, 80); G.SetFont (fuente); @SupessWarnings ("Deprecation") FontMetrics fm = Toolkit.getDefaultToolkit (). GetFontMetrics (Font); int width = fm.StringWidth ("¡éxito!"); int altura = fm.getheight (); G.SetColor (nuevo color (255,0,0)); G.DrawString ("Success!", GetWidth ()/2-width/2, getheight ()/2-height/2); }} El logotipo de clase se extiende jpanel {lo public logotipo (int w, int h) {setSize (w, h); } @Suppleswarnings ("no usado") public void pintarComponent (Graphics g) {super.PaintComponent (g); Fuente de fuentes = nueva fuente ("TimesRoman", Font.Bold, 60); G.SetFont (fuente); @SupessWarnings ("Deprecation") FontMetrics fm = Toolkit.getDefaultToolkit (). GetFontMetrics (Font); int width = fm.StringWidth ("2048"); int altura = fm.getheight (); G.SetColor (nuevo color (255,0,0)); G.DrawString ("2048", 20, getheight ()/2+20); }} public class GoBackListener implementa ActionListener {@SupessWarnings ("RawTypes") public Void ActionPerformed (ActionEvent E) {if (savelist.size () == 0) {GoBackButton.setVisible (falso); devolver; } 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 (); repintado (); }} public class RESETListener implementa ActionListener {public void ActionPerformed (ActionEvent E) {refreshBest (); para (int i = 0; i <4; i ++) {for (int j = 0; j <4; j ++) {rset [i] [j] = null; }} scorelabel.settext ("0"); repintado (); getarandomrect (); getarandomrect (); }} // El applet init public void init () {contenedor cp = getContentPane (); cp.setLayout (nulo); cp.setFocusable (verdadero); cp.addkeylistener (KL); Fuente Font = nueva fuente ("TimesNewman", Font.Bold, 30); Jlabel sl = new JLabel (); sl.setLayout (nuevo GridLayout (2,1)); Jlabel sllb = new JLabel ("puntajes"); sllb.setFont (fuente); Scorelabel = new JLabel ("0"); Scorelabel.setFont (fuente); sl.add (SLLB); sl.add (Scorelabel); int best = 0; intente {archivo archivo = nuevo archivo ("bestRecord"); if (file.exists ()) {randomAccessFile F = new RandomACSessFile (archivo, "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 (nuevo GridLayout (2,1)); Jlabel jl = new JLabel ("mejor"); jl.setFont (fuente); Jlabel jl1 = new JLabel (""+mejor); jl1.setFont (fuente); BSL.Add (JL); BSL.Add (JL1); myP = nuevo my2048Panel (); Logotipo logo = nuevo logotipo (0,0); GoBackButton = new JButton ("Undero"); GobackButton.setFont (fuente); GoBackButton.AddactionListener (nuevo GoBackListener ()); GobackButton.Addkeylistener (KL); JButton JB = new JButton ("Restablecer"); JB.SetFont (fuente); 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 (logotipo); cp.add (myp); cp.add (GobackButton); cp.add (JB); Archivo f = nuevo archivo ("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 (); }} @SupplesSwarnings ("sin verificar") Public Game2048 () {// savethStep (); para (int i = 0; i <7; i ++) {cmap.put (etiqueta [i], clo [i]); }} // Moveleft public void Moveleft (bandera booleana) {ClearList (List); para (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]); }}} para (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]. if (checkMode == false) {int sum = Integer.ParseInt (scorelabel.gettext ()); sum+= list [i] [j] .Value; scorelabel.settext (""+suma); } list [i] [j+1] = null; j ++; }}} if (ischange ()) {if (checkMode == false) {copySet (rset, list); repintado (); Moveleft (falso); } cambio = true; } else {repint (); }} // Moveright public void Moveright (Boolean Flag) {ClearList (List); para (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]); }}} para (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]. if (checkMode == false) {int sum = Integer.ParseInt (scorelabel.gettext ()); sum+= list [i] [j] .Value; scorelabel.settext (""+suma); } list [i] [j-1] = null; J--; }}} if (ischange ()) {if (checkMode == false) {copySet (rset, list); repintado (); Moveright (falso); } cambio = true; } else {repint (); }} // MoveUp public void MoveUp (Boolean Flag) {ClearList (List); para (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]); }}} para (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]. if (checkMode == false) {int sum = Integer.ParseInt (scorelabel.gettext ()); sum+= list [i] [j] .Value; scorelabel.settext (""+suma); } list [i+1] [j] = null; i ++; }}} if (ischange ()) {if (checkMode == false) {copySet (rset, list); repintado (); MoveUp (falso); } cambio = true; } else {repint (); }} // MoverDown public void MovedOwn (bandera booleana) {ClearList (list); para (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]); }}} para (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*.value*. if (checkMode == false) {int sum = Integer.ParseInt (scorelabel.gettext ()); sum+= list [i] [j] .Value; scorelabel.settext (""+suma); } list [i-1] [j] = null; i--; }}} if (ischange ()) {if (checkMode == false) {copySet (rset, list); repintado (); MovedOwn (falso); } cambio = true; } else {repint (); }} // Otras funciones privadas void copyset (rectObject [] [] dst, rectObject [] [] src) {for (int i = 0; i <4; i ++) {para (int j = 0; j <4; j ++) {dst [i] [j] = src [i] [j]; }}} // Detectar si rset es diferente de la lista o no 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] verdadero; } 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; }}} // Obtenga un rectángulo aleatorio @SupplesSwarnings ({"sin verificar", "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 (nuevo punto (i, j)); }}}} if (list.size () == 0 &&! adirable ()) {gameOver (); devolver; } Rand rand = new Random (); int index = rand.nextint (list.size ()); Punto loc = (punto) list.get (índice); índice = 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; }} // detectar si hay otros pasos o no public boolean adirable () {checkMode = true; cambio = falso; Moveleft (verdadero); Moveright (verdadero); MovedOwn (verdadero); MoveUp (verdadero); Checkmode = false; if (cambio == 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"); Fuente de fuente = nueva fuente ("TimesRoman", Font.Bold, 30); JB1.SetOpAque (falso); JB1.setFont (fuente); JButton JB2 = new JButton ("Cerrar"); jb2.setsize (jb1.getSize ()); JB2.SetOpaque (falso); jb2.setFont (fuente); jb1.addactionListener (new ActionListener () {public Void ActionPerformed (ActionEvent E) {scorElabel.setText ("0"); myp.remove (jl); clearList (rset); myp.validate (); getarandomRect (); getArandomRect (); repaint (); gameflag = floal (floal (fall. }); 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 SuccesPane (myp.getWidth (), myp.getheight ()); jl.SetOpaque (falso); Jl.setBounds (0, 0, 700, 700); JButton JB1 = new JButton ("Continuar"); Fuente de fuente = nueva fuente ("TimesRoman", Font.Bold, 30); JB1.SetOpAque (falso); JB1.setFont (fuente); JButton JB2 = new JButton ("Cerrar"); jb2.setsize (jb1.getSize ()); JB2.SetOpaque (falso); jb2.setFont (fuente); 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 (); } @Suppleswarnings ("sin verificar") public void saveTheStep () {if (savelist.size () <20) {@supplesswarnings ("rawtypes") arrayList arr = new ArrayList (); int stork = Integer.ParseInt (scorelabel.gettext ()); arr.add (puntaje); 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 (); savethStep (); }} 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; Archivo f = nuevo archivo ("bestRecord"); Archivo RandomAccessFile; if (f.exists ()) {file = new RandomAccessFile (f, "RW"); best = file.readInt (); file.seek (0); } else {file = new RandomAccessFile (F, "RW"); } //System.out.println("L mejor puntaje es "+mejor); int cur = integer.parseInt (scorelabel.gettext ()); if (cur> best) {file.writeInt (cur); } file.close (); } Catch (FileNotFoundException e1) {e1.printstackTrace (); } catch (ioException e2) {e2.printstackTrace (); }} @SupessWarnings ("Resource") public static void saverecord () {try {randomAccessFile file = new RandomAccessFile (nuevo archivo ("Lastrecord"), "rw"); int stork = 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 hight) {jframe frame = new jframe (title (applet)); Frame.addwindowlistener (nuevo WindowAdapter () {public void WindowClosing (WindowsEvent E) {RefreshBest (); Saverecord (); //system.out.println("the Score es "+scorelabel.gettext ());}}); Frame.setDefaultCloseOperation (jframe.exit_on_close); Frame.getContentPane (). Add (Applet); Frame.setsize (ancho, altura); Applet.init (); Applet.start (); Frame.setVisible (verdadero); } public static void main (string [] args) {run (nuevo juego2048 (), 900, 800); }}PD: Aquí recomendamos otros dos juegos 2048 para su referencia (implementación de JS)
Juegos en línea 2048:
http://tools.vevb.com/games/game2048
Versión digital de mini juego en línea 2048:
http://tools.vevb.com/games/game2048num
Para obtener más información sobre los algoritmos de Java, los lectores interesados en este sitio pueden ver los temas: "Estructura de datos Java y tutorial de algoritmo", "Resumen de las puntas de nodo de operación de Java DOM", "Resumen de Java Archivo y TIPS de operación de directorio" y "Summary of Java Cache Operation Tips" TIPS ""
Espero que este artículo sea útil para la programación Java de todos.