原标题:自己写游戏——东渡教你用Java编写2048完整代码
2048作为一款益智类的小游戏,相信很多人都玩过,小编今天就教教大家怎么用Java代码给它完美重现,下面是用eclipse开发的2048完整代码。
1、编写流程大致可以分为下面3个部分:
1、定义程序的调用
2、完成游戏的场景(窗口格)
3、游戏规则(玩法判定)
话不多说,直接上代码。
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.*;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.*;
import javax.swing.JTextField;
public class Copy2048 extends JFrame{
private JPanel scoresPane;
private JPanel mainPane;
private JLabel labelMaxScores ;
private JLabel labelScores;
private JLabel tips;//提示操作标签
private JTextField textMaxScores;
private JLabel textScores;
private JLabel[][] texts;
private Icon icon2;
private int times = 16;//记录剩余空方块数目
private int scores = 0;//记录分数
private int l1,l2,l3,l4,l5;//用于判断游戏是否失败
2、游戏场景即窗口格的设置
Font font = new Font("", Font.BOLD,14);//设置字体类型和大小
Font font2 = new Font("", Font.BOLD,30);
Random random = new Random();
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
try{
Copy2048 frame = new Copy2048();
frame.setVisible(true);
//Thread thread = new Thread(frame);
//thread.start();
}
catch(Exception e1){
e1.printStackTrace();
}
}
});
}
/**
* 构造方法
*/
public Copy2048(){
super();
setResizable(false);//禁止调整窗体大小
getContentPane().setLayout(null);//设置空布局
setBounds(500, 50, 500, 615);
setDefaultCloseOperation(