连连看java程序package kyodai.map;
import java.awt.*;import javax.swing.*;
import kyodai.*;
/** * 消除连连看方块的类 */public class AnimateDelete implements Runnable { static JButton[] dots; static long delay = 20l; int[] array = new int[44]; //最大距离只可能为2行1列 private int count = 0; private volatile Thread thread;
public AnimateDelete(JButton[] dots) { this.dots = dots; array = new int[0]; }
/** * 初始化 */ public AnimateDelete(int direct, Point a, Point b) { initArray(); calcTwoPoint(direct, a, b); start(); }
/** * direct 方向 * 1表示a, b在同一直线上,b, c在同一竖线上; * 0表示a, b在同一竖线上,b, c在同一直线上 */ public AnimateDelete(int direct, Point a, Point b, Point c) { initArray();
if (direct == 1) { //先横后竖 calcTwoPoint(1, a, b); count--; calcTwoPoint(0, b, c); } else { calcTwoPoint(0, a, b); count--; calcTwoPoint(1, b, c); } start(); }
/** * direct 方向 * 1表示a, b为横线,b, c为竖线, c, d为横线 * 0表示a, b为竖线,b, c为横线,c, d为竖线 */ public AnimateDelete(int direct, Point a, Point b, Point c, Point d) { initArray();
if (direct == 1) { //横、竖、横方式处理 calcTwoPoint(1, a, b); count--; calcTwoPoint(0, b, c); count--; calcTwoPoint(1, c, d); } else { //竖、横、竖方式处理 calcTwoPoint(0, a, b); count--; calcTwoPoint(1, b, c); count--; calcTwoPoint(0, c, d); } start(); }
/** * 计算消除的两点 */ private void calcTwoPoint(int direct, Point a, Point b) { int offset = 0; if (direct == 1) { //横向连接 if (a.y > b.y) { //a点向b点是从右向左在水平线上消除 for (int y = a.y; y >= b.y; y--) { offset = a.x * Setting.COLUMN + y; array[count] = offset; count++; } } else { //a点向b点是从左向右在水平线上消除 for (int y = a.y; y <= b.y; y++) { offset = a.x * Setting.COLUMN + y; array[count] = offset; count++; } } } else { //竖向连接 if (a.x > b.x) { //a点向b点是从下向上垂直消除 for (int x = a.x; x >= b.x; x--) { offset = x * Setting.COLUMN + a.y; array[count] = offset; count++; } } else { //a点向b点是从上向下垂直消除 for (int x = a.x; x <= b.x; x++) { offset = x * Setting.COLUMN + a.y; array[count] = offset; count++; } } } }
/** * 设置动画速度 */ public void setSpeed(int speed) { delay = speed * 10; }
private void initArray() { if (array == null || array.length == 0) { return; }www.lwfree.cn public void test() { if (array == null || array.length == 0) { return; }
for (int i = 0; i < array.length; i++) { if (array[i] != -1) { message("[" + array[i] + "] "); } } System.out.println(); }
public void start() { thread = new Thread(this); thread.start(); }
public void run() { if (count < 2) { return; }
Thread currentThread = Thread.currentThread(); boolean animate = true; while (thread == currentThread && animate) { for (int i = 1; i < count - 1; i++) { dots[array[i]].setEnabled(true); dots[array[i]].setIcon(Kyodai.GuideIcon); try { thread.sleep(delay); } catch (InterruptedException ex) { } }
for (int i = 1; i < count - 1; i++) { dots[array[i]].setIcon(null); dots[array[i]].setEnabled(false); try { thread.sleep(delay); } catch (InterruptedException ex) { } }
dots[array[0]].setIcon(null); dots[array[0]].setEnabled(false); dots[array[count - 1]].setIcon(null); dots[array[count - 1]].setEnabled(false);
animate = false; }
stop(); }
public void stop() { if (thread != null) { thread = null; } }
void message(String str) { System.out.println(str); }}151
连连看java程序package kyodai.map;
import java.awt.Point;
/** * 定义直线的类*/public class Line{
public Point a; public Point b; public int direct;
public Line(){ }
/** * 通过两点和方向构造直线 */ public Line(int direct, Point a, Point b){ this.direct = direct; this.a = a; this.b = b; }}package kyodai.map;
import java.awt.Point;import java.util.Random;import java.util.Vector;
/** * 生成连连看方块的类*/public class Map{
private int level; private int map[][]; int array[]; private int restBlock; private Vector vector; AnimateDelete animate; private boolean test;
public Map(){ level = 28; map = new int[10][17]; array = new int[170]; restBlock = level * 4; vector = new Vector(); test = false; initMap(); }
public Map(int level){ this.level = 28; map = new int[10][17]; array = new int[170]; restBlock = this.level * 4; vector = new Vector(); test = false; this.level = level; restBlock = level * 4; initMap(); }
public void setTest(boolean test){ this.test = test; }
public void setLevel(int level){ this.level = level; restBlock = level * 4; initMap(); }
private void initMap(){ for(int i = 0; i < level; i++){ array[i * 4] = i + 1; array[i * 4 + 1] = i + 1; array[i * 4 + 2] = i + 1; array[i * 4 + 3] = i + 1; }
random(array); for(int i = 0; i < 10; i++){ for(int j = 0; j < 17; j++) map[i][j] = array[i * 17 + j];
}
}
private void random(int array[]){ Random random = new Random(); for(int i = array.length; i > 0; i--){ int j = random.nextInt(i); int temp = array[j]; array[j] = array[i - 1]; array[i - 1] = temp; }
}
public void earse(Point a, Point b){ map[a.x][a.y] = 0; map[b.x][b.y] = 0; restBlock -= 2; }
public int getCount(){ return restBlock <= 0 ? 0 : restBlock; }
public void refresh(){ int count = getCount(); if(count <= 0) return; int temp[] = new int[count]; count = 0; for(int row = 0; row < 10; row++){ for(int col = 0; col < 17; col++) if(map[row][col] > 0){ temp[count] = map[row][col]; count++; }
}
random(temp); count = 0; for(int row = 0; row < 10; row++){ for(int col = 0; col < 17; col++) if(map[row][col] > 0){ map[row][col] = temp[count]; count++; }
}
}
private boolean horizon(Point a, Point b, boolean recorder){ if(a.x == b.x && a.y == b.y) return false; int x_start = a.y <= b.y ? a.y : b.y; int x_end = a.y <= b.y ? b.y : a.y; for(int x = x_start + 1; x < x_end; x++) if(map[a.x][x] != 0) return false;
if(!test && recorder) animate = new AnimateDelete(1, a, b); return true; }
private boolean vertical(Point a, Point b, boolean recorder){ if(a.x == b.x && a.y == b.y) return false; int y_start = a.x <= b.x ? a.x : b.x; int y_end = a.x <= b.x ? b.x : a.x; for(int y = y_start + 1; y < y_end; y++) if(map[y][a.y] != 0) return false;
if(!test && recorder) animate = new AnimateDelete(0, a, b); return true; }
private boolean oneCorner(Point a, Point b){ Point c = new Point(a.x, b.y); Point d = new Point(b.x, a.y); if(map[c.x][c.y] == 0){ boolean method1 = horizon(a, c, false) && vertical(b, c, false); if(method1){ if(!test) animate = new AnimateDelete(1, a, c, b); return method1; } } if(map[d.x][d.y] == 0){ boolean method2 = vertical(a, d, false) && horizon(b, d, false); if(method2 && !test) animate = new AnimateDelete(0, a, d, b); return method2; } else{ return false; } }
private Vector scan(Point a, Point b){ Vector v = new Vector(); Point c = new Point(a.x, b.y); Point d = new Point(b.x, a.y); for(int y = a.y; y >= 0; y--) if(map[a.x][y] == 0 && map[b.x][y] == 0 && vertical(new Point(a.x, y), new Point(b.x, y), false)) v.add(new Line(0, new Point(a.x, y), new Point(b.x, y)));
for(int y = a.y; y < 17; y++) if(map[a.x][y] == 0 && map[b.x][y] == 0 && vertical(new Point(a.x, y), new Point(b.x, y), false)) v.add(new Line(0, new Point(a.x, y), new Point(b.x, y)));
for(int x = a.x; x >= 0; x--) if(map[x][a.y] == 0 && map[x][b.y] == 0 && horizon(new Point(x, a.y), new Point(x, b.y), false)) v.add(new Line(1, new Point(x, a.y), new Point(x, b.y)));
for(int x = a.x; x < 10; x++) if(map[x][a.y] == 0 && map[x][b.y] == 0 && horizon(new Point(x, a.y), new Point(x, b.y), false)) v.add(new Line(1, new Point(x, a.y), new Point(x, b.y)));
return v; }
private boolean twoCorner(Point a, Point b){ vector = scan(a, b); if(vector.isEmpty()) return false; for(int index = 0; index < vector.size(); index++){ Line line = (Line)vector.elementAt(index); if(line.direct == 1){ if(vertical(a, line.a, false) && vertical(b, line.b, false)){ if(!test) animate = new AnimateDelete(0, a, line.a, line.b, b); return true; } } else if(horizon(a, line.a, false) && horizon(b, line.b, false)){ if(!test) animate = new AnimateDelete(1, a, line.a, line.b, b); return true; } }
return false; }
public boolean test(Point a, Point b){ if(map[a.x][a.y] != map[b.x][b.y]) return false; if(a.x == b.x && horizon(a, b, true)) return true; if(a.y == b.y && vertical(a, b, true)) return true; if(oneCorner(a, b)) return true; else return twoCorner(a, b); }
public Line findNext(Point a){ Point b = new Point(); a = findFirst(a); if(a.equals(new Point(-1, -1))) return new Line(0, a, b); for(; !a.equals(new Point(-1, -1)); a = findFirst(a)) for(b = findSecond(a, b); !b.equals(new Point(-1, -1)); b = findSecond(a, b)) if(test(a, b)) return new Line(1, a, b);
return new Line(0, a, b); }
private Point findFirst(Point a){ int offset = 0; if(a != null) offset = a.x * 17 + a.y; if(offset < 0) offset = -1; for(int x = offset + 1; x < 170; x++){ int row = Math.round(x / 17); int col = x - row * 17; if(map[row][col] != 0) return new Point(row, col);www.lwfree.cn(Point a, Point b){ if(a == null) return new Point(-1, -1); if(a.x + a.y < 0) return new Point(-1, -1); if(b == null) b = new Point(0, 0); int offset = Math.max(a.x * 17 + a.y, b.x * 17 + b.y); for(int x = offset + 1; x < 170; x++){ int row = Math.round(x / 17); int col = x - row * 17; if(map[row][col] == map[a.x][a.y]) return new Point(row, col); }
return new Point(-1, -1); }
public int[][] getMap(){ return map; }}
水晶连连看package kyodai.map;
import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.net.*;import kyodai.*;
/** * 生成图形用户界面 */
public class MapUI extends JPanel implements ActionListener, Runnable {
private Map map; private JButton[] dots;
private Point lastPoint = new Point(0, 0); //上一个点的坐标 private boolean isSelected = false; //是否已经选择了一个点
private int score = 0; //记录用户的得分 private ClockAnimate clockAnimate; //同步显示时钟 //AnimateDelete animate; //动画 JButton goTop10;
private ScoreAnimate scoreAnimate; int stepScore = 0; //计算距离的分 int limitTime = 0; //限定寻找的时间(秒)
private boolean isPlaying = false; //当前是否正在游戏中
/** * 构造函数 */ public MapUI(Map map, JButton[] dots) { this.map = map; this.dots = dots;
GridLayout gridLayout = new GridLayout(); this.setLayout(gridLayout); gridLayout.setRows(Setting.ROW); gridLayout.setColumns(Setting.COLUMN); gridLayout.setHgap(2); gridLayout.setVgap(2); this.setLayout(gridLayout); this.setBackground(Kyodai.DarkColor);
for (int row = 0; row < Setting.ROW; row++) { for (int col = 0; col < Setting.COLUMN; col++) { int index = row * Setting.COLUMN + col; dots[index].addActionListener(this); this.add(dots[index]); } } } /** * 设置地图 */ public void setMap(Map map) { this.map = map; }
/** * 获取主界面上的goTop10按钮,以便操作 */ public void setTop10Button(JButton goTop10) { this.goTop10 = goTop10; }
/** * 根据数组来绘置画面 */ private void paint() { for (int row = 0; row < Setting.ROW; row++) { for (int col = 0; col < Setting.COLUMN; col++) { int index = row * Setting.COLUMN + col; if (map.getMap()[row][col] > 0) { dots[index].setIcon(Kyodai.BlocksIcon[map.getMap()[row][col] - 1]); dots[index].setEnabled(true); } else { dots[index].setIcon(null); dots[index].setEnabled(false); } } } }
public void repaint(Graphics g) { paint(); }
/** * 判断当前是否已经没有可消除的方块 */ private boolean validMap(Point a) { if (map.getCount() == 0) { return true; }
Line line = new Line(0, new Point(), new Point()); map.setTest(true); //只测试 line = map.findNext(a); int offset = 0; if (line.direct == 1) { //找到了可消除的 return true; } else { return false; } }
/** * 更新当前显示的分数 */ private void showScore(int l, int c) { if (scoreAnimate == null) { return; } scoreAnimate.setScore(l, c); }
/** * 刷新当前的排列方式 */ public void refresh() { if (!isPlaying) { //不在游戏中,返回 return; } if (map.getCount() == 0) { Kyodai.showHint("还刷,都没了!"); } if (Setting.Sound == 1) { new Sound(Sound.REFRESH); }
if (validMap(new Point( -1, -1))) { score -= Setting.freshScore; showScore(score - 1, score); } else { showScore(score, score + Setting.freshScore); score += Setting.freshScore; }
score -= Setting.freshScore; showScore(score - 1, score);
map.refresh(); paint(); }
/** * 消除两个点 */ void earse(Point a, Point b) { //paint();
int offset; offset = a.x * Setting.COLUMN + a.y; dots[offset].setIcon(null); dots[offset].setEnabled(false);
offset = b.x * Setting.COLUMN + b.y; dots[offset].setIcon(null); dots[offset].setEnabled(false);
//如果地图清除完成,关闭 if (map.getCount() == 0) { int remainTime = limitTime - clockAnimate.getUsedTime(); message("剩余时间 = " + remainTime); if (remainTime > 0) { showScore(score, score + remainTime * Setting.timeScore); score += remainTime * Setting.timeScore; } isPlaying = false; stop(); Kyodai.showHint("时间+ " + remainTime * Setting.timeScore + ",想看看你的排名吗?"); goTop10.setEnabled(true); } else { //test1(map.getDeleteArray()); } }
/** * 自动寻找最佳答案 */ public void findNext(Point a) { if (!isPlaying) { //不在游戏中,返回 return; } if (map.getCount() == 0) { Kyodai.showHint("你找昏了头吧,没了!"); return; } Line line = new Line(0, new Point(), new Point()); map.setTest(true); //告诉map当前只是测试,并不需要进行删除动画 line = map.findNext(a); int offset = 0; if (line.direct == 1) { //找到了可消除的 if (Setting.Sound == 1) { new Sound(Sound.HINT); } offset = line.a.x * Setting.COLUMN + line.a.y; dots[offset].setBorder(Kyodai.Hint); offset = line.b.x * Setting.COLUMN + line.b.y; dots[offset].setBorder(Kyodai.Hint); score -= Setting.hintScore; showScore(score - 1, score); } else { Kyodai.showHint("找不到,请刷新"); } }
/** * 自动找出并消除地图上的两个点 */ public boolean bomb(Point a, boolean showMessage) { if (!isPlaying) { //不在游戏中,返回 return false; } if (map.getCount() == 0) { Kyodai.showHint("你炸昏了头吧,没了!"); return false; } Line line = new Line(0, new Point(), new Point()); map.setTest(false); line = map.findNext(a); int offset = 0; if (line.direct == 1) { //找到了可消除的 if (Setting.Sound == 1) { new Sound(Sound.BOMB); } offset = line.a.x * Setting.COLUMN + line.a.y; dots[offset].setBorder(Kyodai.unSelected); offset = line.b.x * Setting.COLUMN + line.b.y; dots[offset].setBorder(Kyodai.unSelected); map.earse(line.a, line.b); earse(line.a, line.b);
score -= Setting.bombScore; showScore(score - 1, score); return true; } else { if (showMessage) { Kyodai.showHint("炸弹用不了,请刷新!"); } return false; } }
private void message(String str) { Kyodai.showHint(str); }
/** * 自动游戏 */ public void autoPlay() { if (!isPlaying) { //不在游戏中,返回 return; } //如果使用该功能,不计时间分 limitTime = 0;
while (map.getCount() > 0) { if (bomb(new Point( -1, -1), false)) { message("炸弹使用成功!"); } else { message("找不到可用点,刷新……"); refresh(); } } }
/** * 获取系统的计分板 */ public void setScore(ScoreAnimate score) { this.scoreAnimate = score; }
/** * 获取系统的计时板 */ public void setClock(ClockAnimate clock) { this.clockAnimate = clock; }
/** * 事件处理 */ public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); int offset = Integer.parseInt(button.getActionCommand()); int row, col; row = Math.round(offset / Setting.COLUMN); col = offset - row * Setting.COLUMN; //如果上面没有图片 if (map.getMap()[row][col] < 1) { return; } //选择时的声音 if (Setting.Sound == 1) { new Sound(Sound.SELECT); }
if (isSelected) { message("上次已经选择了一个点"); message("上次选择点的坐标为: " + lastPoint.x + ", " + lastPoint.y + " 值为: " + map.getMap()[lastPoint.x][lastPoint.y] + " 位移为: " + (lastPoint.x * Setting.COLUMN + lastPoint.y));
//是上次选择的点 if (lastPoint.x == row && lastPoint.y == col) { message("这次选择的点和上次的是同一点,取消选择状态"); button.setBorder(Kyodai.unSelected); isSelected = false; } else { //判断是否可以消除 message("这次选择的点和上次的点并不相同"); Point current = new Point(row, col); message("这次选择的点的坐标为: " + row + ", " + col + " 值为: " + map.getMap()[row][col] + " 位移为: " + (row * Setting.COLUMN + col)); map.setTest(false); if (map.test(lastPoint, current)) { message("两点可以消除,执行消除"); //消除前先取消当前选择点的边框,因为有可能是提示 dots[row * Setting.COLUMN + col].setBorder(Kyodai.unSelected);
map.earse(current, lastPoint); earse(current, lastPoint); dots[lastPoint.x * Setting.COLUMN + lastPoint.y].setBorder(Kyodai.unSelected); lastPoint = new Point(0, 0); isSelected = false;
showScore(score, score + Setting.correctScore + stepScore); score += Setting.correctScore + stepScore;
if (Setting.Sound == 1) { new Sound(Sound.EARSE); } } else { message("这次选择的点与上次选择的点无解,改变选择为当前点"); dots[lastPoint.x * Setting.COLUMN + lastPoint.y].setBorder(Kyodai.unSelected); button.setBorder(Kyodai.Selected); lastPoint.x = row; lastPoint.y = col; isSelected = true;
score -= Setting.wrongScore; showScore(score - 1, score); } } } else { message("上次并未选择的点,置当前点为选择点"); message("当前点坐标为: " + row + ", " + col + " 值为: " +map.getMap()[row][col] +" 位移为: " + (row * Setting.COLUMN + col)); button.setBorder(Kyodai.Selected); lastPoint.x = row; lastPoint.y = col;www.lwfree.cn Kyodai.showHint("负分还想有排名?下次努力吧!"); }
int level, f1, f2; level = Setting.LevelIndex; f1 = (score - 102) * (score - 102); f2 = (1978 - score) * (1978 - score); return "s=" + score + "&l=" + level + "&f1=" + f1 + "&f2=" + f2; }
public void start() { goTop10.setEnabled(false);
isPlaying = true; limitTime = map.getCount() * Setting.limitScore; message("时限 = " + limitTime); paint(); }
public void run() {
}
public void stop() { clockAnimate.stop(); }}
连连看下载package kyodai;
import java.awt.*;import javax.swing.*;
/** * 处理时间的类 */public class ClockAnimate extends JPanel implements Runnable {
private volatile Thread thread; long startTime = 0l; //开始时间 long usedTime = 0l; //使用时间
Color color = new Color(212, 255, 200); Font font48 = new Font("serif", Font.PLAIN, 28); java.text.DecimalFormat df = new java.text.DecimalFormat("000"); java.text.DecimalFormat df2 = new java.text.DecimalFormat("0");
public ClockAnimate() { this.setMinimumSize(new Dimension(156, 48)); this.setPreferredSize(new Dimension(156, 48)); }
/** * 时间的绘制 */ public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; Dimension d = getSize(); g2.setBackground(new Color(111, 146, 212)); g2.clearRect(0, 0, d.width, d.height); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(color); g2.setFont(font48);
g2.drawString("时间:" + getTime(), 16, 40); }
/** * 取得使用时间格式化后的字符串 */ String getTime() { int sec, ms; long time; time = usedTime; sec = Math.round(time / 1000); time -= sec * 1000; ms = Math.round(time / 100); return (df.format(sec) + "." + df2.format(ms)); }
public void start() { startTime = System.currentTimeMillis(); thread = new Thread(this); thread.start(); }
public void run() { Thread currentThread = Thread.currentThread(); while (thread == currentThread) { long time = System.currentTimeMillis(); usedTime = time - startTime; try { repaint(); thread.sleep(100l); } catch (InterruptedException ex) { } } }
public void stop() { if (thread != null) { thread = null; } }
/** * 取得用户使用的时间 */ public int getUsedTime() { return Math.round(usedTime / 1000); }}
连连看java程序源代码package kyodai;
import javax.swing.*;import java.awt.*;import java.net.*;import java.awt.event.*;import javax.swing.border.*;
import kyodai.map.*;import kyodai.topbar.*;
/** * 连连看主类 */public class Kyodai extends JFrame implements ActionListener {
public static Color DarkColor = new Color(55, 77, 118); //暗色 public static Color LightColor = new Color(111, 146, 212); //亮色 public static ImageIcon[] BlocksIcon = new ImageIcon[39]; //游戏中方块的图标 public static ImageIcon GuideIcon; //连线的图标 public static Border unSelected = BorderFactory.createLineBorder(DarkColor, 1); //未选中时的边框 public static Border Selected = BorderFactory.createLineBorder(Color.white, 1); //选中后的边框 public static Border Hint = BorderFactory.createLineBorder(Color.green, 1); //提示的边框
Dimension faceSize = new Dimension(780, 500); Image icon; private int counter = 0;
JPanel toolBar = new JPanel(); //工具栏 JPanel actionPanel = new JPanel(); //用户操作栏 JPanel contentPanel = new JPanel(); //容器 JPanel statusPanel = new JPanel(); //状态栏 Border emptyBorder = BorderFactory.createEmptyBorder(); //未选中时的边框 JButton startButton = new JButton(); //"开始" JButton refreshButton = new JButton(); //"刷新" JButton hintButton = new JButton(); //"提示" JButton bombButton = new JButton(); //"炸弹" JButton demoButton = new JButton(); //"演示"
JButton setupButton = new JButton(); //设置 JButton helpButton = new JButton(); //帮助 JButton aboutButton = new JButton(); //关于 JButton goTop10 = new JButton("Go top 10"); HelpDialog helpDialog; //帮助对话框 AboutDialog aboutDialog; //关于对话框
public static JTextField statusField = new JTextField( "欢迎使用宝石连连看"); ImageIcon imgStart, imgHint, imgRefresh, imgBomb, imgDemo; ImageIcon imgSetup, imgHelp, imgAbout;
JButton[] dots = new JButton[Setting.ROW * Setting.COLUMN]; Setting setting = new Setting();
MapUI ui; Map map; ClockAnimate clock = new ClockAnimate(); //时钟 ScoreAnimate score = new ScoreAnimate(); //分数 AnimateDelete animateDelete = new AnimateDelete(dots); Music music = new Music();
public Kyodai() { initResource();//初始化系统所需要的资源 map = new Map(); ui = new MapUI(map, dots); initUI();//初始化用户界面 ui.setScore(score); ui.setClock(clock); ui.setTop10Button(goTop10); animateDelete.setSpeed(setting.Animate);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.pack(); this.setSize(faceSize); //设置运行时窗口的位置 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation( (int) (screenSize.width - faceSize.getWidth()) / 2, (int) (screenSize.height - faceSize.getHeight()) / 2); this.setResizable(false); this.setTitle("宝石连连看"); //设置标题 this.setIconImage(icon); //设置程序图标
//设置动画光标 URLClassLoader urlLoader = (URLClassLoader)this.getClass().getClassLoader(); URL url = urlLoader.findResource("images/cursor.gif"); Image animateImage = new ImageIcon(url).getImage(); Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor( animateImage, new Point(0, 0), "cursor"); this.setCursor(cursor); this.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent we) { setting.save(); } } );
if (setting.Music == 1) { music.play(); } }
/** * 初始化系统所需要的资源 */ public void initResource() { URLClassLoader urlLoader = (URLClassLoader)this.getClass().getClassLoader(); URL url;
//程序图标 icon = getImage("images/kyodai16.gif");
for (int i = 0; i < BlocksIcon.length; i++) { BlocksIcon[i] = new ImageIcon(getImage("images/" + (i + 1) + ".gif")); }
imgStart = new ImageIcon(getImage("images/start.gif")); imgRefresh = new ImageIcon(getImage("images/refresh.gif")); imgHint = new ImageIcon(getImage("images/hint.gif")); imgBomb = new ImageIcon(getImage("images/bomb.gif")); imgDemo = new ImageIcon(getImage("images/demo.gif"));
imgSetup = new ImageIcon(getImage("images/setup.gif")); imgHelp = new ImageIcon(getImage("images/help.gif")); imgAbout = new ImageIcon(getImage("images/about.gif"));
GuideIcon = new ImageIcon(getImage("images/dots.gif"));
//初始化方块 for (int i = 0; i < dots.length; i++) { dots[i] = new JButton(); dots[i].setActionCommand("" + i); dots[i].setBorder(unSelected); dots[i].setBackground(DarkColor); }
//读取用户设置 setting.load();
//初始化对话框 helpDialog = new HelpDialog(this); //帮助对话框 aboutDialog = new AboutDialog(this); //关于对话框 }
/** * 初始化用户界面 */ public void initUI() { //界面整体布局 Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED, new Color(45, 92, 162), new Color(43, 66, 97), new Color(45, 92, 162), new Color(84, 123, 200)); BorderLayout borderLayout = new BorderLayout(); toolBar.setBackground(DarkColor); toolBar.setBorder(border); toolBar.setPreferredSize(new Dimension(780, 48)); toolBar.setMinimumSize(new Dimension(780, 48)); toolBar.setLayout(new FlowLayout(FlowLayout.LEFT)); actionPanel.setBackground(LightColor); actionPanel.setBorder(border); actionPanel.setPreferredSize(new Dimension(160, 380)); actionPanel.setMinimumSize(new Dimension(160, 380)); contentPanel.setBackground(DarkColor); contentPanel.setBorder(border); contentPanel.setPreferredSize(new Dimension(620, 380)); contentPanel.setMinimumSize(new Dimension(620, 380));
statusPanel.setBackground(DarkColor); statusPanel.setBorder(border); statusPanel.setPreferredSize(new Dimension(620, 24)); statusPanel.setMinimumSize(new Dimension(620, 24)); statusPanel.setLayout(new BorderLayout());
this.getContentPane().setLayout(borderLayout); this.getContentPane().add(toolBar, BorderLayout.NORTH); this.getContentPane().add(actionPanel, BorderLayout.EAST); this.getContentPane().add(contentPanel, BorderLayout.CENTER); this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
//加入地图 contentPanel.add(ui);
//加入计分 actionPanel.add(score);
//加入开始按钮 actionPanel.add(startButton); startButton.setBorder(emptyBorder); startButton.setIcon(imgStart); startButton.addActionListener(this);
//加入刷新按钮 actionPanel.add(refreshButton); refreshButton.setBorder(emptyBorder); refreshButton.setIcon(imgRefresh); refreshButton.addActionListener(this);
//加入提示按钮 actionPanel.add(hintButton); hintButton.setBorder(emptyBorder); hintButton.setIcon(imgHint); hintButton.addActionListener(this);
//加入炸弹按钮 actionPanel.add(bombButton); bombButton.setBorder(emptyBorder); bombButton.setIcon(imgBomb); bombButton.addActionListener(this);
//加入自动演示 actionPanel.add(demoButton); demoButton.setBorder(emptyBorder); demoButton.setIcon(imgDemo); demoButton.addActionListener(this);
//加入设置 toolBar.add(setupButton); setupButton.setBorder(emptyBorder); setupButton.setIcon(imgSetup); setupButton.addActionListener(this);
//加入帮助 toolBar.add(helpButton); helpButton.setBorder(emptyBorder); helpButton.setIcon(imgHelp); helpButton.addActionListener(this);
//加入关于 toolBar.add(aboutButton); aboutButton.setBorder(emptyBorder); aboutButton.setIcon(imgAbout); aboutButton.addActionListener(this);
//加入时钟 actionPanel.add(clock);
//加入状态栏 statusPanel.add(statusField, BorderLayout.CENTER); statusField.setBorder(unSelected); statusField.setEditable(false); statusField.setForeground(Color.white); statusField.setBackground(DarkColor);
//加入发送按钮 statusPanel.add(goTop10, BorderLayout.EAST); goTop10.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); goTop10.setForeground(Color.white); goTop10.setBackground(DarkColor); goTop10.setFont(new Font("Serif", Font.PLAIN, 11)); goTop10.addActionListener(this); goTop10.setEnabled(false); }
public static void showHint(String str) { statusField.setText(str); }
/** * 通过给定的文件名获得图像 */ Image getImage(String filename) { URLClassLoader urlLoader = (URLClassLoader)this.getClass(). getClassLoader(); URL url = null; Image image = null; url = urlLoader.findResource(filename); image = Toolkit.getDefaultToolkit().getImage(url); MediaTracker mediatracker = new MediaTracker(this); try { mediatracker.addImage(image, 0); mediatracker.waitForID(0); } catch (InterruptedException _ex) { image = null; } if (mediatracker.isErrorID(0)) { image = null; }
return image; }
/** * 事件处理 */ public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if (obj == startButton) { //开始 map = new Map(Setting.Level[setting.LevelIndex]); ui.setMap(map); ui.start(); clock.start(); score.setScore( -1, 0); } else if (obj == refreshButton) { //刷新 ui.refresh(); } else if (obj == hintButton) { //提示 ui.findNext(new Point( -1, -1)); } else if (obj == bombButton) { //炸弹 ui.bomb(new Point( -1, -1), true); } else if (obj == demoButton) { //自动演示 ui.autoPlay(); } else if (obj == aboutButton) { //关于 aboutDialog.show(); } else if (obj == helpButton) { //帮助 //new Help(); helpDialog.show(); } else if (obj == setupButton) { //设置 SetupDialog setupDialog = new SetupDialog(this); //设置对话框 setupDialog.show();
if (setting.Music == 1) { music.play(); } else { music.stop(); }
animateDelete.setSpeed(setting.Animate); } else if (obj == goTop10) { //排名 String name = JOptionPane.showInputDialog(this, "请留下大名:", "过眼云烟"); if (!"".equals(name.trim())) { //如果留了名字 System.out.println("ui.encode()="+ui.encode()); new Top10(this, "nickname=" + name + "&" + ui.encode()); goTop10.setEnabled(false); } } }
public static void main(String args[]) { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); Kyodai kyodai = new Kyodai(); kyodai.show(); }}
javaj连连看源代码package kyodai;
import javax.sound.midi.*;import java.io.*;import java.net.*;
/** * 控制背景音乐 */public class Music implements MetaEventListener, Runnable { private String midiFile = "sound/bg.mid"; private Sequence sequence = null; private Sequencer sequencer; private boolean isPlaying = false; private volatile Thread thread;
public Music() { try { loadMidi(midiFile); } catch (InvalidMidiDataException ex) { } catch (IOException ex) { } }
/** * 读取midi文件 */ public void loadMidi(String filename) throws IOException,InvalidMidiDataException {
URLClassLoader urlLoader = (URLClassLoader)this.getClass().getClassLoader(); URL url = urlLoader.findResource(filename); sequence = MidiSystem.getSequence(url); }
public void play() { if (isPlaying) { //如果已经在播放,返回 return; }
try { sequencer = MidiSystem.getSequencer(); sequencer.open(); sequencer.setSequence(sequence);
sequencer.addMetaEventListener(this); } catch (InvalidMidiDataException ex) { } catch (MidiUnavailableException e) { }
thread = new Thread(this); thread.start(); }
public void stop() { if (isPlaying) { sequencer.stop(); isPlaying = false; } if (thread != null) { thread = null; } }
public void run() { Thread currentThread = Thread.currentThread(); while (currentThread == thread && !isPlaying) { sequencer.start(); isPlaying = true; try { thread.sleep(1000l); } catch (InterruptedException ex) { } } }
public void meta(MetaMessage event) { if (event.getType() == 47) { System.out.println("Sequencer is done playing."); } }}
package kyodai;
import javax.swing.*;import java.awt.*;
/** * 计算和显示所得分数 */public class ScoreAnimate extends JPanel implements Runnable {
private volatile Thread thread; //private boolean isPainting = false; public int lastScore, currentScore; Color color = new Color(255, 255, 0); Font font48 = new Font("serif", Font.BOLD, 42); java.text.DecimalFormat df = new java.text.DecimalFormat("0000");
/** * 构造函数 */ public ScoreAnimate() { this.setMinimumSize(new Dimension(156, 48)); this.setPreferredSize(new Dimension(156, 48)); }
/** * 分数的绘制 */ public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; Dimension d = getSize(); g2.setBackground(new Color(111, 146, 212)); g2.clearRect(0, 0, d.width, d.height); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(color); g2.setFont(font48); g2.drawString("$" + df.format(lastScore), 20, 40); }
public void start() { thread = new Thread(this); thread.start(); }
public void run() { Thread currentThread = Thread.currentThread(); while (thread == currentThread && lastScore < currentScore) { try { lastScore++; repaint(); thread.sleep(50l); } catch (InterruptedException ex) { } } }
public void setScore(int l, int c) { this.lastScore = l; this.currentScore = c; start(); }
public void stop() { if (thread != null) { thread = null; } }}
连连看java程序package kyodai;
import java.io.*;import java.net.*;import java.util.*;
/** * 生成配置文件的类 */
public class Setting { public final static int COLUMN = 17; //表格的列 public final static int ROW = 10; //表格的行 public final static int limitScore = 4; //每个方块限定的时间 public final static int timeScore = 2; //时间奖励的分数 public final static int wrongScore = 1; //选择失败扣分 public final static int freshScore = 8; //刷新功能扣分 public final static int hintScore = 10; //提示功能扣分 public final static int bombScore = 12; //炸弹功能扣分 public final static int correctScore = 10; //成功消除后加分 public final static int MaxBlocks = 156; //最多可能出现的方块个数 public final static int[] Level = { 16, 22, 28, 34, 39}; //Level = N时需要的图标数
public static int Music = 1, Sound = 1, LevelIndex = 2, Animate = 2;
public Setting() { }
/** * 从kyodai.ini文件中读取配置 */ public void load() { Properties pro; FileInputStream read = null;
String Music = "1", Sound = "1", LevelIndex = "2", Animate = "2";
try { read = new FileInputStream("kyodai.ini"); pro = new Properties(); pro.load(read);
Music = pro.getProperty("Music"); Sound = pro.getProperty("Sound"); LevelIndex = pro.getProperty("LevelIndex"); Animate = pro.getProperty("Animate"); read.close(); } catch (IOException ex) { Music = "1"; Sound = "1"; LevelIndex = "2"; Animate = "2"; }
try { this.Music = Integer.parseInt(Music); } catch (NumberFormatException ex1) { this.Music = 1; }
try { this.Sound = Integer.parseInt(Sound); } catch (NumberFormatException ex1) { this.Sound = 1; }
try { this.LevelIndex = Integer.parseInt(LevelIndex); } catch (NumberFormatException ex1) { this.LevelIndex = 1; } this.LevelIndex = this.LevelIndex < 0 ? 0 : this.LevelIndex; this.LevelIndex = this.LevelIndex > 4 ? 4 : this.LevelIndex;
try { this.Animate = Integer.parseInt(Animate); } catch (NumberFormatException ex1) { this.Animate = 1; } this.Animate = this.Animate < 1 ? 1 : this.Animate; this.Animate = this.Animate > 10 ? 10 : this.Animate; }
/** * 将配置保存到kyodai.ini文件中 */ public void save() { Properties pro; FileOutputStream save = null; try { save = new FileOutputStream("kyodai.ini"); pro = new Properties(); pro.setProperty("Music", "" + Music); pro.setProperty("Sound", "" + Sound); pro.setProperty("LevelIndex", "" + LevelIndex); pro.setProperty("Animate", "" + Animate); pro.store(save, "Kyodai\r\n"); save.close(); System.out.println("Music=" + Music); System.out.println("Sound="+ Sound); System.out.println("LevelIndex="+ LevelIndex); System.out.println("Animate="+ Animate);
} catch (IOException ex) { } }}
连连看java程序package kyodai;
import java.io.*;import javax.sound.sampled.*;import java.net.*;
/** * 控制音乐特效 */public class Sound implements Runnable {
String currentName; Object currentSound; Thread thread; String[] filename = { "sound/select.wav", "sound/earse.wav", "sound/bomb.wav", "sound/refresh.wav", "sound/hint.wav"};
public static int SELECT = 0; public static int EARSE = 1; public static int BOMB = 2; public static int REFRESH = 3; public static int HINT = 4;
public Sound(int sound) { if (sound < 0 || sound > 4) { return; }
URLClassLoader urlLoader = (URLClassLoader)this.getClass().getClassLoader(); URL url = urlLoader.findResource(filename[sound]);
try { currentSound = AudioSystem.getAudioInputStream(url); } catch (Exception ex1) { currentSound = null; return; }
if (currentSound instanceof AudioInputStream) { try { AudioInputStream stream = (AudioInputStream) currentSound; AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info( Clip.class,stream.getFormat(), ( (int) stream.getFrameLength() * format.getFrameSize()));
Clip clip = (Clip) AudioSystem.getLine(info); clip.open(stream); currentSound = clip; } catch (Exception ex) { currentSound = null; return; } }
if (currentSound != null) { start(); } }
public void playSound() { if (currentSound instanceof Clip) { Clip clip = (Clip) currentSound; clip.start(); try { thread.sleep(999); } catch (Exception e) { } while (clip.isActive() && thread != null) { try { thread.sleep(99); } catch (Exception e) { break; } }
clip.stop(); clip.close(); } currentSound = null; }
public void start() { thread = new Thread(this); thread.start(); }
public void run() { playSound(); stop(); }
public void stop() { if (thread != null) { thread.interrupt(); } thread = null; }}
连连看java程序package kyodai;
import java.net.*;
import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import javax.swing.event.*;import javax.swing.text.html.*;import java.io.*;
/** * 控制连连看排名 */public class Top10 extends JDialog implements HyperlinkListener { JScrollPane ScrollPane = new JScrollPane(); JEditorPane HelpPane = new JEditorPane(); Border border1; JPanel Panel1 = new JPanel(); JButton Close = new JButton(); Border border2; String param = "";
public Top10(JFrame frame, String param) { super(frame, true); this.param = param; try { jbInit(); } catch (Exception e) { e.printStackTrace(); } //设置运行位置,使对话框居中 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation( (int) (screenSize.width - 560) / 2, (int) (screenSize.height - 360) / 2); this.setResizable(false); this.show(); }
private void jbInit() throws Exception { border2 = BorderFactory.createCompoundBorder( BorderFactory.createLineBorder( Color.lightGray, 1), BorderFactory.createEmptyBorder(2, 10, 2, 10)); this.setSize(new Dimension(560, 360)); this.setTitle("龙虎英雄榜"); border1 = BorderFactory.createEmptyBorder();
URLClassLoader urlLoader = (URLClassLoader)this.getClass().getClassLoader(); URL url = null; //调用排名榜文件 url = urlLoader.findResource("doc/Top.htm"); HelpPane.setPage(url); HelpPane.setEditable(false); HelpPane.addHyperlinkListener(this); ScrollPane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); ScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); ScrollPane.setBorder(border1); Close.setBackground(Color.white); Close.setBorder(border2); Close.setActionCommand("jButton1"); Close.setText("关闭"); Close.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); } } );
Panel1.setBackground(Color.white); this.getContentPane().add(ScrollPane, BorderLayout.CENTER); this.getContentPane().add(Panel1, BorderLayout.SOUTH); ScrollPane.getViewport().add(HelpPane, null); Panel1.add(Close, null); }
/** * 当超文本链接更新时调用 * 负责更新的事件处理函数 */ public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { JEditorPane pane = (JEditorPane) e.getSource(); if (e instanceof HTMLFrameHyperlinkEvent) { HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e; HTMLDocument doc = (HTMLDocument) pane.getDocument(); doc.processHTMLFrameHyperlinkEvent(evt); } else { try { pane.setPage(e.getURL()); } catch (Throwable t) { t.printStackTrace(); } } } }}