弹弹球小游戏(Java)
作者:互联网
游戏规则:利用键盘上的->或者<-控制方向,用球拍接住小球,否则游戏结束!
该代码主要利用了GUI的绘图,用Timer保证球拍和小球位置的更新,用适配器KeyAdapter获取用户的指令,参考代码如下,需要改进之处请各位大佬多多指正
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class checkb {
//设置frame
Frame frame=new Frame("欢迎林giegie来到弹弹球小游戏");
private final int TABLE_WIDTH =300;
private final int TABLE_HEIGHT =400;
//设置小球
private final int BALL_SIZE=16;
private int BALLX=120;
private int BALLY=20;
private int SPEEDX=10;
private int SPEEDY=5;
//设置拍子
private final int RACKET_WIDTH=60;
private final int RACKET_HEIGHT=20;
private int RACKETX=120;
private int RACKETY=340;
//结束标志
private boolean isover=false;
//时间对象
private Timer timer;
//画布
private class Mycanvas extends Canvas{
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
//游戏结束、进行时
if(isover){
g.setColor(Color.black);
g.setFont(new Font("Times",Font.BOLD,30));
g.drawString("林giegie败北", 150, 200);
}else{
//画球、球拍
g.fillOval(BALLX, BALLY, BALL_SIZE, BALL_SIZE);
g.fillRect(RACKETX, RACKETY, RACKET_WIDTH, RACKET_HEIGHT);
}
}
}
//组装组件
public void inti(){
class listenere extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
super.keyPressed(e);
int s=e.getKeyCode();
if(RACKETX>=0&&s==KeyEvent.VK_LEFT){
RACKETX-=10;
}
if(RACKETX<=TABLE_WIDTH-RACKET_WIDTH&&s==KeyEvent.VK_RIGHT){
RACKETX+=10;
}
}
}
listenere listener=new listenere();
Mycanvas Mycan=new Mycanvas();
frame.addKeyListener(listener);
Mycan.addKeyListener(listener);
class task implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//小球到达窗口两侧
if(BALLX<=0||BALLX>=TABLE_WIDTH-BALL_SIZE)
SPEEDX=-SPEEDX;
//小球到达顶部
if(BALLY<=0)
SPEEDY=-SPEEDY;
//小球接触到球拍
if(BALLX>RACKETX&&BALLX<RACKETX+RACKET_WIDTH&&BALLY>=RACKETY-BALL_SIZE)
SPEEDY=-SPEEDY;
//球拍没接住小球
if(BALLY>=RACKETY&&(BALLX<RACKETX-BALL_SIZE||BALLX>RACKETX+BALL_SIZE)){
isover=true;
Mycan.repaint();
timer.stop();
}
BALLX+=SPEEDX;
BALLY+=SPEEDY;
Mycan.repaint();
}
}
timer = new Timer(100,new task());
timer.start();
Mycan.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT));
frame.add(Mycan);
//设置frame最佳大小,并可视
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new checkb().inti();
}
}
标签:BALL,Java,int,弹球,private,小游戏,new,frame,SIZE 来源: https://blog.csdn.net/m0_52830830/article/details/121942322