package bj.txt.test;
//常量类(游戏项目中的常量)
public class Constant {
public static final int GAME_WIDTH = 500;
public static final int GAME_HEIGHT = 500;
}
package bj.txt.test;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
/*游戏开发中常用的工具类(比如,加载图片等方法)*/
public class GameUtil {
public static Image getImage(String path) {
URL u = GameUtil.class.getClassLoader().getResource(path);
BufferedImage img = null;
try {
img = ImageIO.read(u);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return img;
}
}
package bj.txt.test;
import java.awt.Graphics;
import java.awt.Image;
public class GameFrame05 extends MyFrame{
// 加载图片
Image img = GameUtil.getImage("images/台球.png");
private double x = 100, y = 100;
private double speed = 10;
private double degree = 3.14 / 3;// [0,2pi]
// 在窗口里画东西
@Override
public void paint(Graphics g) {
g.drawImage(img, (int) x, (int) y, null);
// 控制速度
if (speed > 0) {
speed -= 0.01;
} else {
speed = 0;
}
x += speed * Math.cos(degree);
y += speed * Math.sin(degree);
if (y > 500-48 || y < 48) {
degree = -degree;
}
if (x < 0 || x > 500-48 ) {
degree = Math.PI - degree;
}
}
public static void main(String[] args) {
GameFrame05 gf = new GameFrame05();
gf.lauchFrame();
}
}
package bj.txt.test;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
public class MyFrame extends Frame{
/* 加载窗口 */
public void lauchFrame(){
setSize(Constant.GAME_WIDTH,Constant.GAME_HEIGHT);//设置窗口大小
setLocation(100,100);//设置窗口位置
setVisible(true);//窗口可见
new PaintThread().start();
//关闭窗口
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
}
// 定义一个重画窗口的线程类,内部类
class PaintThread extends Thread {
public void run() {
while (true) {
repaint();// 重画窗口
try {
Thread.sleep(40);// 1s = 1000ms
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MyFrame gf = new MyFrame();
gf.lauchFrame();
}
}