/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pinball;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
/**
*
* @author 91152
*/
public class PinBall2 {
//桌面的高度和宽度
private final int TABLE_WIDTH = 300;
private final int TABLE_HEIGHT = 400;
// 球拍的垂直位置
private final int RACKET_Y = 340;
private int racketX = 0;
// 下面定义球拍的高度和宽度
private final int RACKET_HEIGHT = 20;
private final int RACKET_WIDTH = 60;
private JFrame jf = new JFrame("乒乓");
private JJ p = new JJ();
//判断输赢
private boolean isLost = false;
Random rand = new Random();
private int ballX= rand.nextInt(200)+20;
private int ballY = rand.nextInt(20)+20;
private final int BALL_SIZE = 16;
private int ySpeed = 5;
private int xSpeed = 3;
Timer t;
public void init(){
KeyAdapter ka = new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_LEFT){
if(racketX > 0 ){
racketX -=10;
}
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
if(racketX < TABLE_WIDTH - RACKET_WIDTH ){
racketX +=10;
}
}
}
};
ActionListener as = event ->{
//碰到左右边缘的反弹
if(ballX <=0 || ballX >=TABLE_WIDTH - BALL_SIZE){
xSpeed = -xSpeed;
}
//判断输了
if(ballY >= RACKET_Y - BALL_SIZE &&(
(ballX < racketX || ballX>racketX+RACKET_WIDTH)) ){
t.stop();
isLost = true;
p.repaint();
}
//判断触顶部或底部反弹
else if(ballY<= 0||
ballY>=RACKET_Y - BALL_SIZE &&
ballX>racketX && ballX <= racketX+RACKET_WIDTH){
ySpeed = -ySpeed;
}
ballY +=ySpeed;
ballX +=xSpeed;
p.repaint();
//System.out.println(xSpeed);
};
p.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT));
jf.add(p);
//p.addKeyListener(ka);
jf.addKeyListener(ka);
jf.pack();
t = new Timer(50,as);
t.start();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
public static void main(String[] args){
new PinBall2().init();
}
class JJ extends JPanel{
@Override
public void paint(Graphics g){
super.paint(g);
if(isLost){
g.setFont(new Font("Times", Font.BOLD,30));
g.setColor(Color.GREEN);
g.drawString("游戏已结束", 50, 200);
}else{
g.setColor(Color.BLUE);
g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
g.setColor(Color.red);
g.fillRect(racketX, RACKET_Y, RACKET_WIDTH, RACKET_HEIGHT);
}
}
}
}