Cet article décrit le jeu 2048 mis en œuvre par Java. Partagez-le pour votre référence, comme suit:
Jetons un coup d'œil à l'effet de course:
Le code spécifique est le suivant:
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, en bas = 1, gauche = 2, à droite = 3; Final statique privé int wid = 150, sp = 10; @SuppressWarnings ("inutilisé") Scores INT privés = 0; JLABEL STATIQUE privé; Changement booléen privé, CheckMode = false, gameOverflag = false, successflag = false; private int [] label = {2,4,8,16,32,64,128}; Couleur privée [] CLO = {nouvelle couleur (200 200 200), nouvelle couleur (228 228,160), nouvelle couleur (214,163,92), nouvelle couleur (234,124,72), nouvelle couleur (240,84,77), nouvelle couleur (255,68,53), nouvelle couleur (200,200,64)}; @SuppressWarnings ("RawTypes") Carte privée cmap = new HashMap (); RectObject statique public [] [] RSET = nouveau rectObject [4] [4]; public rectObject [] [] list = new rectObject [4] [4]; My2048panel privé Myp; @SuppressWarnings ("RawTypes") private LinkedList Savelist = new LinkedList (); Le soldat JBUTTON GOBACKBUTTON; KeyListener kl = new KeyListener () {public void keypblied (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 (); } casser; case keyevent.vk_down: change = false; Moundown (vrai); if (change == true) {getarandomrect (); // SavetheStep (); } casser; case keyevent.vk_left: change = false; moweleft (true); if (change == true) {getarandomrect (); // SavetheStep (); } casser; case keyevent.vk_right: change = false; Moveright (vrai); if (change == true) {getarandomrect (); // SavetheStep (); } casser; } // SavetheStep (); } public void keyTyped (keyEvent e) {} public void keyrelent (keyEvent e) {}}; class rectObject {private int Value; public rectObject () {value = 0; } public rectObject (rectObject obj) {value = obj.value; } public boolean equals (objet inobj) {rectObject obj = (rectObject) inobj; if (obj.value == valeur) {return true; } return false; }} point de classe {int x; int y; Point public (int i, int j) {x = i; y = j; }} class My2048Panel étend 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 ("Deprécation") 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 (colore.white); G.DrawroundRect (xindex [i], yindex [j], wid, wid, wid / 5, wid / 5); g.setColor (nouvelle couleur (197,183,129)); G.FillroundRect (xindex [i], yindex [j], wid, wid, wid / 5, wid / 5); }} // peinture rectangle for (int i = 0; i <4; i ++) {for (int j = 0; j <4; j ++) {if (rset [i] [j]! = null) {g.setColor (colore.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 = NOUVEAU FONT ("Timesroman", Font.Bold, 50); g.setfont (police); 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 (); }}}}}}} classe GameOverpone étend jpanel {public gameOverpane (int w, int h) {setSize (w, h); // setOpaque (false); } @SuppressWarnings ("Deprécation") public void PaintComponent (Graphics G) {super.paintComponent (G); FONT FONT = NOUVEAU FONT ("Timesroman", Font.Bold, 80); g.setfont (police); Fontmetrics fm = toolkit.getDefaultToolkit (). GetFontmetrics (Font); int width = fm.stringwidth ("jeu sur"); int hauteur = fm.getheight (); g.setColor (nouvelle couleur (255,0,0)); G.Drawstring ("Game Over!", getWidth () / 2-Width / 2, getheight () / 2-height / 2); }} classe SuccessPane étend jpanel {public SuccessPane (int w, int h) {setSize (w, h); // setOpaque (false); } public void peintComponent (graphiques g) {super.paintComponent (g); FONT FONT = NOUVEAU FONT ("Timesroman", Font.Bold, 80); g.setfont (police); @SuppressWarnings ("Deprécation") Fontmetrics FM = Toolkit.getDefaultToolkit (). GetFontmetrics (FONT); int width = fm.stringWidth ("Success!"); int hauteur = fm.getheight (); g.setColor (nouvelle couleur (255,0,0)); G.Drawstring ("Success!", GetWidth () / 2-Width / 2, Getheight () / 2-Height / 2); }} classe Logo étend jpanel {public logo (int w, int h) {setSize (w, h); } @SuppressWarnings ("inutilisé") public void PaintComponent (graphiques g) {super.paintComponent (g); FONT FONT = NOUVEAU FONT ("Timesroman", Font.Bold, 60); g.setfont (police); @SuppressWarnings ("Deprécation") Fontmetrics FM = Toolkit.getDefaultToolkit (). GetFontmetrics (FONT); int largeur = fm.stringWidth ("2048"); int hauteur = fm.getheight (); g.setColor (nouvelle couleur (255,0,0)); G.Drawstring ("2048", 20, Getheight () / 2 + 20); }} classe publique GOBACKListener implémente ActionListener {@SuppressWarnings ("RawTypes") public void ActionPerformed (ActionEvent e) {if (Savelist.size () == 0) {gobackbutton.setVisible (false); retour; } 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 (); repeindre(); }} classe publique ResetListener implémente 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"); repeindre(); getarandomrect (); getarandomrect (); }} // L'applet init public void init () {contener cp = getContentPane (); cp.setLayout (null); cp.setFocausable (true); cp.addkeyListener (KL); FONT FONT = NOUVEAU 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 (fichier, "rw"); meilleur = 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 ("meilleur"); jl.setfont (police); JLabel jl1 = new JLabel ("" + meilleur); jl1.setfont (font); bsl.add (jl); BSL.ADD (JL1); myp = new my2048panel (); Logo logo = nouveau logo (0,0); GOBACKBUTTON = NOUVEAU JBUTTON ("UNDO"); GOBACKBUTTON.SETFONT (FONT); gobackbutton.addactionListener (new goBackListener ()); gobackbutton.addkeyListener (KL); Jbutton jb = new JButton ("réinitialiser"); jb.setfont (police); 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); Fichier f = nouveau fichier ("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]); }} // moweleft public void moweleft (booléen drapeau) {clearlist (list); pour (int i = 0; i <4; i ++) {int k = 0; pour (int j = 0; j <4; j ++) {if (rset [i] [j]! = null) {list [i] [k ++] = new rectObject (rset [i] [j]); }}} pour (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 ("" + sum); } list [i] [j + 1] = null; j ++; }}} if (ischange ()) {if (checkMode == false) {copySet (rset, list); repeindre(); moweleft (false); } change = true; } else {repeain (); }} // moveright public void moveright (booléen drapeau) {clearlist (list); pour (int i = 0; i <4; i ++) {int k = 3; pour (int j = 3; j> -1; j -) {if (rset [i] [j]! = null) {list [i] [k -] = new rectObject (rset [i] [j]); }}} pour (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 ("" + sum); } list [i] [j-1] = null; J-; }}} if (ischange ()) {if (checkMode == false) {copySet (rset, list); repeindre(); Moveright (false); } change = true; } else {repeain (); }} // MovUp public void movup (booléan drapeau) {clearlist (list); pour (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]); }}} pour (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]. 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); repeindre(); Movup (false); } change = true; } else {repeain (); }} // MovDown Public void Soumown (booléen drapeau) {clearlist (list); pour (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]); }}} pour (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]. if (checkMode == false) {int sum = Integer.ParseInt (scoreLabel.getText ()); sum + = list [i] [j] .value; scoreLabel.setText ("" + sum); } list [i-1] [j] = null; je--; }}} if (ischange ()) {if (checkMode == false) {copySet (rset, list); repeindre(); Moundown (false); } change = true; } else {repeain (); }} // Autres fonctions 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]; }}} // détecter si RSET est différent de la liste ou non booléen privé isChange () {pour (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]. vrai; } 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; }}} // Obtenez un rectangle aléatoire @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 (nouveau point (i, j)); }}}} if (list.size () == 0 &&! adirable ()) {gameOver (); retour; } 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; }} // détecter s'il y a d'autres étapes ou non booléan public adirable () {checkMode = true; change = false; moweleft (true); Moveright (vrai); Moundown (vrai); 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 = NOUVEAU 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 (); repental (); repental; gameOverflag = false; réfresque;); 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 ("continuer"); FONT FONT = NOUVEAU 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 (); repent ();}}); 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 (); }} Title de chaîne statique publique (objet O) {String t = o.getClass (). ToString (); if (t.indexof ("class")! = - 1) {t = t.SubString (6); } return t; } public static void rafreshbest () {try {int best = 0; Fichier f = nouveau fichier ("bestRecord"); Fichier RandomAccessFile; if (f.exists ()) {file = new randomaccessfile (f, "rw"); meilleur = file.readInt (); file.seek (0); } else {file = new randomaccessfile (f, "rw"); } //System.out.println(" le meilleur score est "+ meilleur); 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 (nouveau fichier ("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 largeth, int height) {jframe frame = new JFrame (title (applet)); frame.addwindowListener (new WindowAdapter () {public void windowClosing (windowEvent e) {Refreshbest (); SaveRecord (); //System.out.println(" la partition est "+ scoreLabel.getText ());}}); frame.setDefaultCloseOperation (jframe.exit_on_close); frame.getContentPane (). Add (applet); frame.SetSize (largeur, hauteur); applet.init (); applet.start (); frame.setVisible (true); } public static void main (String [] args) {run (new Game2048 (), 900, 800); }}PS: Ici, nous recommandons deux autres jeux 2048 pour votre référence (implémentation JS)
Jeux en ligne 2048:
http://tools.vevb.com/games/game2048
Version numérique en ligne 2048 Mini Game:
http://tools.vevb.com/games/game2048num
Pour plus d'informations sur les algorithmes Java, les lecteurs qui sont intéressés par ce site peuvent afficher les sujets: "Structure de données Java et tutoriel d'algorithme", "Résumé des conseils de nœud de Dom Operation Java", "Résumé du fichier Java et des conseils d'opération de répertoire" et "Résumé des conseils d'opération Java Cache"
J'espère que cet article sera utile à la programmation Java de tous.