java游戏-碰到矩形边界时反弹-swing界面

时间:2021-03-24 17:31:36

 

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class Hufan extends JFrame{
	static HuPanel hp;
	static Hufan hu;
	public static void main(String[] args) {
		hu=new Hufan();
	}
	public Hufan(){
		hp=new HuPanel();
		this.addKeyListener(hp);
		this.add(hp);
		this.setSize(500, 400);
		this.setLocation(400, 300);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}
}
class HuPanel extends JPanel implements KeyListener{
	Rect rect;
	HuRect huRect;
	public HuPanel(){
		rect=new Rect(20,40);
		huRect=new HuRect(180,290);
		Thread t=new Thread(rect);
		t.start();
	}
	public void paint(Graphics g){
		super.paint(g);
		g.drawRect(0, 0, 400, 300);
		g.setColor(Color.red);
		g.fillRect(rect.x, rect.y, 20,20);
		g.setColor(Color.blue);
		g.fillRect(huRect.x, huRect.y, 80, 10);
	}
	@Override
	public void keyPressed(KeyEvent e) {
		switch(e.getKeyCode()){
		case KeyEvent.VK_LEFT:
			if(huRect.x>0){
				huRect.x-=huRect.speed;
			}
			break;
		case KeyEvent.VK_RIGHT:
			if(huRect.x<320){
				huRect.x+=huRect.speed;
			}
			break;
		}
		this.repaint();
	}
	public void keyReleased(KeyEvent arg0) {}
	public void keyTyped(KeyEvent arg0) {}
}
class Rect implements Runnable{//方块类
	int x;
	int y;
	int speedX=3;//x轴移动速度
	int speedY=3;//y轴移动速度
	boolean kaiGuan=true;
	public Rect(int x,int y){
		this.x=x;
		this.y=y;
	}
	public void run() {
		while(this.kaiGuan){
			x=x+speedX;
			y=y+speedY;
			if(x<=0||x>=380){
				speedX=-speedX;//到达左右边界时,x轴移动速度取反
			}
			if(y<=0){
				speedY=-speedY;//到达左右边界时,y轴移动速度取反
			}
			if(y>=280){
				this.kaiGuan=false;
			}
			int xx=Hufan.hp.huRect.x;
			int yy=Hufan.hp.huRect.y;
			if(x>=xx&&x<=xx+80&&y+20>=yy&&y+20<=yy+10){//方块与矩形相碰检测
				speedY=-speedY;
			}
			try {
				Thread.sleep(30);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Hufan.hu.hp.repaint();
		}
	}
}
class HuRect extends Rect{//下面的矩形类
	int speed=5;
	public HuRect(int x, int y) {
		super(x, y);
	}
}