import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import javax.swing.Timer;
public class PinBall {
//桌面的宽度
private final int TABLE_WIDTH=300;
//桌面高度
private final int TABLE_HEIGHT=400;
//球拍的垂直位置
private final int RACKET_Y=340;
//球拍的高度和宽度
private final int RACKET_HEIGHT=20;
private final int RACKET_WIDTH=60;
//小球的大小
private final int BALL_SIZE=16;
private Frame f=new Frame("弹球游戏");
Random rand=new Random();
//小球的纵向运行速度
private int ySpeed=10;
//返回一个-0.5-0.5的比率,用于控制小球的运动方向
private double xyRate=rand.nextDouble()-0.5;
//小球横向的运行速度
private int xSpeed=(int)(ySpeed*xyRate*2);
//ballX和ballY代表小球的坐标
private int ballX=rand.nextInt(200)+20;
private int ballY=rand.nextInt(10)+20;
//racketX代表球拍的水平位置
private int racketX=rand.nextInt(200);
private MyCanvas tableArea=new MyCanvas();
Timer timer;
//游戏是否结束的旗标
private boolean isLose=false;
public void init(){
tableArea.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT));
f.add(tableArea);
KeyAdapter keyProcessor=new KeyAdapter(){
public void keyPressed(KeyEvent ke){
//按下向左、向右键时,球拍水平坐标分别减少、增加
if(ke.getKeyCode()==KeyEvent.VK_LEFT){
if(racketX>0)
{
racketX-=10;
}
if(ke.getKeyCode()==KeyEvent.VK_RIGHT){
if(racketX<TABLE_WIDTH-RACKET_WIDTH){
racketX+=10;
}
}
}
}
};
f.addKeyListener(keyProcessor);
tableArea.addKeyListener(keyProcessor);
//定义每0.1秒执行一次事件监听器
ActionListener taskPerformer=new ActionListener(){
public void actionPerformed(ActionEvent e){
if(ballX<=0||ballX>=TABLE_WIDTH-BALL_SIZE){
xSpeed=-xSpeed;
}
if(ballY>=RACKET_Y-BALL_SIZE&&(ballX<racketX||ballX>racketX+RACKET_WIDTH)){
timer.stop();
//设置游戏是否结束的旗标为true
isLose=true;
tableArea.repaint();
}
else if(ballY<=0||(ballY>=RACKET_Y-BALL_SIZE&&ballX>racketX&&ballX<=racketX+RACKET_WIDTH)){
ySpeed=-ySpeed;
}
ballY+=ySpeed;
ballX+=xSpeed;
tableArea.repaint();
}
};
timer=new Timer(100,taskPerformer);
timer.start();
f.pack();
f.setVisible(true);
}
public static void main(String[] args){
new PinBall().init();
}
class MyCanvas extends Canvas{
public void paint(Graphics g){
if(isLose){
g.setColor(new Color(255,0,0));
g.setFont(new Font("Times",Font.BOLD,30));
g.drawString("游戏已结束!",50,200);
}
//如果游戏还未结束
else{
g.setColor(new Color(240,240,80));
g.fillOval(ballX,ballY, BALL_SIZE, BALL_SIZE);
g.setColor(new Color(80,80,200));
g.fillRect(racketX,RACKET_Y, RACKET_WIDTH, RACKET_HEIGHT);
}
}
}
}
虽然有时那球飞得好像略显违和不过基本功能好像还行,最不解的是我按向右键时貌似没反应,弄了好一会了眼睛都发疼了,被迫睡觉去,发在这希望明天起来能看到有大神帮我找出问题所在,谢谢了哈~
|
|