弹球游戏实现原理:
隔一定时间(小于1秒)重新绘制图像,因为Graphics类是一个抽象类,创建子类的时候需要把所有涉及的方法都得重写,所以这里使用的是创建Canvas的子类,只需要重写它的paint()方法来实现。这里我们用了键盘监听事件、Timer类等。
游戏说明:
该弹球游戏中的小球会随着时间增加速度且速度最多是横向速度和垂直速度为10。当小球的y坐标(垂直坐标)大于球拍的y坐标(垂直坐标)即判断游戏结束。控制台显示的是小球的x方向的速度和y方向的速度。
1 import java.awt.*; 2 import java.util.Random; 3 import javax.swing.Timer; 4 import java.awt.event.*; 5 public class PinBall 6 { 7 private Frame f=new Frame("弹球游戏"); 8 Random rand=new Random(); 9 //桌面的宽度以及高度 10 private final int TABLE_WIDTH=300; 11 private final int TABLE_HEIGHT=400; 12 //球拍的宽度以及高度以及水平位置、垂直位置 13 private final int RACKET_WIDTH=60; 14 private final int RACKET_HEIGHT=20; 15 private int racketX=rand.nextInt(24)*10; 16 private int racketY=300; 17 //小球的大小、运行速度、坐标 18 private final int BALL_SIZE=16; 19 private int ySpeed=1; 20 private double xyRate=1; 21 private int xSpeed=(int)(xyRate*ySpeed); 22 private int ballX=rand.nextInt(284); 23 private int ballY=1; 24 //创建画布 25 private MyCanvas tableArea=new MyCanvas(); 26 //定义时间类 27 Timer timer; 28 //游戏是否结束的旗标 29 private boolean isLose=false; 30 //设置游戏等级 31 private int time_times=1; 32 public void init(){ 33 tableArea.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT)); 34 f.add(tableArea); 35 //定义键盘监听器 36 KeyAdapter keyProcessor=new KeyAdapter() 37 { 38 public void keyPressed(KeyEvent ke){ 39 if(ke.getKeyCode()==KeyEvent.VK_LEFT){ 40 if(racketX>0) 41 racketX-=10; 42 } 43 if(ke.getKeyCode()==KeyEvent.VK_RIGHT){ 44 if(racketX<TABLE_WIDTH-RACKET_WIDTH) 45 racketX+=10; 46 } 47 } 48 49 }; 50 f.addKeyListener(keyProcessor); 51 //tableArea.addKeyListener(keyProcessor); 52 ActionListener taskPerformer=evt-> 53 { 54 //小球碰到左边框或右边框 55 if(ballX<=0||ballX>=TABLE_WIDTH-BALL_SIZE){ 56 xSpeed=-xSpeed; 57 } 58 if(ballY>racketY-BALL_SIZE&&(ballX<racketX||ballX>racketX+RACKET_WIDTH-BALL_SIZE)){ 59 timer.stop(); 60 isLose=true; 61 tableArea.repaint(); 62 }else if(ballY<=0||(ballY>=racketY-BALL_SIZE&&ballX>racketX&&ballX<=racketX+RACKET_WIDTH)){ 63 ySpeed=-ySpeed; 64 } 65 ballY+=ySpeed; 66 ballX+=xSpeed; 67 tableArea.repaint(); 68 if((xSpeed<10&&xSpeed>-10)&&(ySpeed<10&&ySpeed>-10)){ 69 time_times++; 70 } 71 if(time_times==10){ 72 if(xSpeed>0){ 73 xSpeed++; 74 }else{ 75 xSpeed--; 76 } 77 if(ySpeed>0){ 78 ySpeed++; 79 }else{ 80 ySpeed--; 81 } 82 time_times-=10; 83 System.out.println(xSpeed+" "+ySpeed); 84 } 85 }; 86 timer=new Timer(100,taskPerformer); 87 timer.start(); 88 f.pack(); 89 f.setVisible(true); 90 } 91 class MyCanvas extends Canvas 92 { 93 public void paint(Graphics g){ 94 if(isLose){ 95 g.setColor(new Color(255,0,0)); 96 g.setFont(new Font("Times",Font.BOLD,30)); 97 g.drawString("游戏结束",50,200); 98 }else{ 99 g.setColor(new Color(240,240,80)); 100 g.fillOval(ballX,ballY,BALL_SIZE,BALL_SIZE); 101 g.setColor(new Color(80,80,200)); 102 g.fillRect(racketX,racketY,RACKET_WIDTH,RACKET_HEIGHT); 103 } 104 } 105 } 106 public static void main(String[] args) 107 { 108 new PinBall().init(); 109 } 110 }
时间: 2024-10-10 13:48:41