import javax.imageio.ImageIO; import javax.swing.; import java.awt.; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import java.util.Timer; import java.util.TimerTask;
public class BeatSquirrels {
//创建窗口
private JFrame frame = new JFrame("暴打小松鼠");
//设置分数
int score = 0;
//记录四张图片
BufferedImage image_backGround;
BufferedImage image_squirrels;
//初始化坐标
int r_X = -1;
int r_Y = -1;
private class MyCanvas extends JPanel{
@Override
public void paint(Graphics g) {
//绘制草地背景
g.drawImage(image_backGround,0,0,null);
//绘制分数
g.drawString("分数:"+score,20,20);
//绘制松鼠
Random random = new Random();
r_X = random.nextInt(400);
r_Y = random.nextInt(400);
g.drawImage(image_squirrels,r_X,r_Y,null);
}
}
MyCanvas drawArea = new MyCanvas();
public void init() throws IOException {
//frame.setTitle("暴打小松鼠"); //游戏名
//frame.setLayout(null); //无布局格式 加上这句会让图片无法显示
frame.setSize(500,500); //界面尺寸
frame.setLocationRelativeTo(null); //窗口位于屏幕中央
frame.setResizable(false); //尺寸不可调
//松鼠自动跳转位置
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
frame.repaint();
}
};
timer.schedule(task,2000,1000);
//读取图片
image_backGround = ImageIO.read(new File("D:\\beatingSquirrels\\Image\\花花.jpg"));
image_squirrels = ImageIO.read(new File("D:\\beatingSquirrels\\Image\\松鼠.png"));
//处理鼠标点击
drawArea.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//如果点击了松鼠就重绘
if (r_X <= e.getX() && e.getX() <= r_X + 50
&& r_Y <= e.getY() && e.getY() <= r_Y + 50) {
score++;
drawArea.repaint();
}
}
});
drawArea.setPreferredSize(new Dimension(500,500));
frame.add(drawArea);
//更改鼠标形状
frame.setCursor(Cursor.HAND_CURSOR);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //点x关闭窗口
frame.setVisible(true); //窗口可见
}
public static void main(String[] args) throws IOException {
new BeatSquirrels().init();
}
} //ps:文中的图片如下 游戏很容易实现哦!
|