Java弹球游戏
导入Java . awt . dimension;
导入Java . awt . graphics;
导入Java . awt . graphics 2d;
导入Java . awt . rendering hints;
导入Java . awt . event . mouse event;
导入Java . awt . event . mousemotionlistener;
导入Java . awt . image . buffered image;
导入javax . swing . jframe;
导入javax . swing . jpanel;
公共类CopyOfBallCrash实现Runnable {
公共静态void main(final String[] args) {
新线程(新CopyOfBallCrash())。start();
}
私有final int?宽度= 400;
私有final int?身高= 700;
private int mouse_X,mouse _ Y;
private final buffered image off screen = new buffered image(宽度,高度,
BufferedImage。TYPE _ 4 byte _ ABGR);
私有final JPanel panel = new JPanel();
私人最终形状球?=新形状(100,100,1,1,20);
私人最终形状rect?=新形状(0,100,20);
public CopyOfBallCrash() {
final JFrame frame = new JFrame();
frame . setdefaultcloseoperation(JFrame。EXIT _ ON _ CLOSE);
panel.setPreferredSize(新维度(宽度,高度));
ball.setBounds(宽度,高度);
rect.setBounds(宽度,高度);
frame . setcontentpane(panel);
panel . addmousemotionlistener(new MouseMotionListener(){
@覆盖
public void mouse dragged(final mouse event e){ }
@覆盖
public void mouseMoved(最终MouseEvent e) {
mouse _ X = e . getx();
mouse _ Y = e . gety();
}
});
frame . pack();
frame . set visible(true);
}
公共空白绘画(最终图形g) {
final graphics 2d g2d = off screen . create graphics();
g2d . setrenderinghint(rendering hints。KEY _抗锯齿,
呈现提示。VALUE _ ANTIALIAS _ ON);
g2d.fillRect(0,0,width,height);
g2d . set color(color . blue);
rect.drawRect(g2d,mouse _ X);
g2d . set color(color . red);
ball.drawOval(g2d,rect);
If (Shape.isLose) g2d.drawString("你输了!!!", 100, 300);
g2d . dispose();
g.drawImage(offscreen,0,0,null);
}
@覆盖
公共无效运行(){
while(真)
paint(panel . get graphics());
}
}
类别形状{
public int宽度、高度;
public int x,y,vx,vy,r,w,h;
公共静态布尔isLose
公共形状(最终整数x,最终整数y,最终整数vx,最终整数vy,最终整数r) {
super();
this.x = x
this.y = y
this.vx = vx
this.vy = vy
this.r = r
}
公共形状(最终整数x,最终整数w,最终整数h) {
super();
this.x = x
this.w = w
this.h = h
}
public final void set bounds(final int width,final int height) {
this.width =宽度;
this.height =高度;
}
公共最终无效drawOval(最终图形2D g2d,最终形状shape) {
if(y+h & gt;=高度){
isLose = true
返回;
}
if(x+VX & lt;= 0 | | x+VX+w & gt;=宽度)VX =-VX;
if(y+vy & lt;= 0)vy =-vy;
if (isCrashOutside(shape.x,shape.y,shape.w,shape . h)& amp;& ampy+w & gt;= shape.y)
vy =-vy;
x+= VX;
y+= vy;
g2d.fillOval(x,y,r,r);
}
public final void drawRect(final graphics 2d g2d,final int mouseX) {
y =身高-h;
if(x+w & lt;宽度和尺寸。& ampx & ltmouseX)x++;
if(x & gt;0 & amp& ampx & gtmouseX)x-;
g2d.fillRect(x,y,w,h);
}
public final boolean iscrashouter(final int x,final int y,final int w,
最终整数h) {
return(this . x & gt;x?this.x & lt= w+x:x & lt;= r + this.x)
& amp& amp(this.y & gty?this.y & lt= h+y:y & lt;= r+this . y);
}
}