偶爾幫同學作一個拼圖游戲
不如拿出來共享一下
主要利用了Graphics中的
public abstract boolean drawImage(Image img
int dx
int dy
int dx
int dy
int sx
int sy
int sx
int sy
Color bgcolor
ImageObserver observer)
方法(Draws as much of the specified area of the specified image as is currently available
import java
import java
import java
import java
import javax
import java
import javax
public class Pintu extends JFrame{
private Image image
private Point point = new Point(
private int[][] map = {{
private int sx
private Canvas canvas; //加載圖片容器
private Graphics gs
private boolean isRunning = false; //游戲是否正在進行
private JButton start = new JButton(
private JButton show = new JButton(
private JTextArea showTime = new JTextArea(
private JTextArea showStep = new JTextArea(
private JPanel panel = new JPanel(); //裝在上面
private int steps =
public Pintu(String title) { //構造方法
super(title);
try { //異常拋出
image = ImageIO
} catch (IOException ex) {
ex
}
initScreen(); //初始化canvas
buff = new BufferedImage(
gb = buff
sx = image
sy = image
setLayout(new BorderLayout());
add(panel
add(canvas
panel
panel
panel
panel
panel
showTime
showStep
showTime
showStep
setSize(
setResizable(false);
setDefaultCloseOperation(JFrame
}
void initScreen() {
canvas = new Canvas() {
public void paint(Graphics g) { //覆寫canvas的paint 方法
gs = getGraphics(); //得到Canvas的Graphics
if (isRunning) {
drawScreen();
} else {
g
g
}
}
};
canvas
//覆寫mousePressed 方法
public void mousePressed(MouseEvent me) {
if (!isRunning) return; // 如果未運行
int x = me
int fx = (int) point
int canMove = Math
if (canMove !=
map[fx][fy] = map[x][y]; //點擊圖片坐標 賦給第九塊圖片
map[x][y] =
point
drawScreen(); //重繪屏幕
showStep
}
});
//為Start按鈕添加事件
start
public void actionPerformed(ActionEvent ae) {
initMap();
drawScreen();
isRunning = true;
steps =
showStep
show
}
});
//為show按鈕添加事件
show
public void actionPerformed(ActionEvent ae) {
if (show
drawScreen();
isRunning = true;
show
} else {
gs
isRunning = false;
show
}
}
});
}
void initMap() {
long time = System
java
int temp
//隨機交換圖片
for (int i =
x
x
y
y
temp = map[x
map[x
map[x
}
//標記
outer:
for (int i =
for (int j =
if (map[i][j] ==
point
break outer;
}
}
void drawScreen() {
int sx
int t
gb
gb
for (int x =
for (int y =
if(map[x][y] !=
// 目的地址
dx
dx
// 源地址
t
sx
sx
gb
}
gs
}
public static void main(String[] args) {
Pintu pintu = new Pintu(
new Thread(pintu)
pintu
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27054.html