⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ballapplet.java

📁 java游戏编程导学系列二 使用说明 所有范例
💻 JAVA
字号:
package breakout;

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.net.URL;


/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class BallApplet extends JApplet implements Runnable{
  private boolean isStandalone = false;
  //设置字体
  Font largefont = new Font("Helvetica",Font.BOLD,24);
  Font smallfont = new Font("Helvetica",Font.BOLD,14);

  Dimension d;
  FontMetrics fmsmall,fmlarge;//设置字符缓冲
  Graphics goff;
  Image img;
  Thread theThread;           //定义小球的线程

  boolean ingame = false;     //判断游戏是否在玩
  int score,                  //游戏得分
      ballx,                  //小球的x位置
      bally,                  //小球的y位置
      batpos,                 //球拍的位置
      batdpos = 0,
      balldx=0,
      balldy = 0,
      dxval,
      ballsleft,
      count;
  boolean showtitle = true;    //显示题目
  boolean[] showbrick;         //显示砖块
  int bricksperline;           //每行的砖块数
  final int borderwidth = 5,
      batwidth = 20,
      ballsize = 5,            //球的大小
      batheight = 5,           //球拍的宽度
      scoreheight = 20,        //得分区域宽度
      screendelay = 300,
      brickwidth =15,          //砖块的厚度
      brickheight = 8,         //砖块的宽度
      brickspace = 2,
      backcol = 0x102040,      //背景颜色
      numlines = 4,            //行数
      startline = 32;          //开始的行
  AudioClip au;

  public String getAppletInfo(){
    return ("BreakBall");
  }

  //Construct the applet
  public BallApplet() {
  }
  //Initialize the applet
  public void init() {
    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }

    d= size();
    bricksperline=(d.width-2*borderwidth)/(brickwidth + brickspace);
    d.width = bricksperline * (brickwidth+ brickspace) + (2*borderwidth);

    showbrick = new boolean[bricksperline*numlines];
    GameInit();
    try {
          URL url = Class.forName("breakout.BallApplet").getResource("move.au");
          au = getAudioClip(url);
        }
        catch (Exception e) {
          e.printStackTrace();
        }

  }
  //Component initialization
  private void jbInit() throws Exception {
    this.setSize(new Dimension(400,300));
  }

  //Main method
  public static void main(String[] args) {
    BallApplet applet = new BallApplet();
    applet.isStandalone = true;
    JFrame frame = new JFrame();

    frame.setDefaultCloseOperation(3);
    frame.setTitle("弹球");
    frame.getContentPane().add(applet, BorderLayout.CENTER);
    applet.init();
    applet.start();
    frame.setSize(400,320);
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
    frame.setVisible(true);
    frame.setFocusable(true);
    frame.requestFocus();
  }

  //static initializer for setting look & feel
  private void GameInit() {
    batpos = (d.width-batwidth)/2;
    ballx = (d.width-ballsize)/2;
    bally = (d.height-ballsize-scoreheight-2*borderwidth);
    score = 0;
    ballsleft = 100;
    dxval = 2;
    if(Math.random()<0.5) balldx = dxval;
    else balldx = -dxval;
      balldy = -dxval;
    count =screendelay;
    batdpos = 0;
    InitBricks();
  }

  private void InitBricks() {
    int i;
    for(i = 0;i<numlines*bricksperline;i++){
      showbrick[i] = true;
    }
  }
  public void paint(Graphics g){
    String s;

    g.setFont(smallfont);
    fmsmall = g.getFontMetrics();
    g.setFont(largefont);
    fmlarge = g.getFontMetrics();

    if(goff == null && d.width>0 && d.height>0){
      img = createImage(d.width,d.height);
      goff = img.getGraphics();
    }
    if(goff == null || img == null)return ;
    goff.setColor(new Color(backcol));
    goff.fillRect(0,0,d.width,d.height);

    if (ingame) {
      playGame();
    }
    else {
      ShowIntroScreen();
    }
    g.drawImage(img,0,0,this);

  }
  public void processKeyEvent(KeyEvent e){
    int nKeyCode = e.getKeyChar();
    //System.out.println(nKeyCode);
    switch (nKeyCode) {
      case 97:
        batdpos = -3;
        repaint();
        break;
      case 100:
        batdpos = 3;
        repaint();
        break;
      case 119:
        stop();
        au.play();
        break;
      case 115:
        start();
        au.play();
        break;

    }
  }
  private void ShowIntroScreen() {

    MoveBall();
    CheckBat();
    CheckBricks();
    BatDummyMove();
    DrawPlayField();
    DrawBricks();
    ShowScore();
    goff.setFont(largefont);
    goff.setColor(new Color(96,128,255));
    count--;
    if(count <=0){
      count =screendelay;showtitle =!showtitle;
    }
  }

  public void DrawBricks() {
    int i,j;
    boolean nobricks = true;
    int colordelta = 255/(numlines - 1);

    for(j=0;j<numlines;j++){
      for(i = 0; i< bricksperline; i++){
        if(showbrick[j* bricksperline + i]){
          nobricks = false;
          goff.setColor(new Color(255,j*colordelta,255-j*colordelta));
          goff.fillRect(borderwidth + i*(brickwidth + brickspace),
                        startline + j*(brickheight+brickspace),
                        brickwidth,
                        brickheight);
        }
      }
    }
    if(nobricks){
      InitBricks();
      if(ingame)score+=100;
    }
  }

  public void MoveBall() {

    ballx += balldx;
    bally += balldy;
    if(bally <= borderwidth){
      balldy =-balldy;
      bally = borderwidth;
    }
    if(bally >=(d.height-ballsize-scoreheight)){
      if(ingame){
        ballsleft--;
        if(ballsleft <= 0)ingame = false;
      }
      ballx = batpos + (batwidth - ballsize)/2;
      bally = startline + numlines*(brickheight+brickspace);
      balldy = dxval;
      balldx = 0;
    }
    if(ballx >= (d.width-borderwidth-ballsize)){
      balldx = -balldx;
      ballx = d.width-borderwidth-ballsize;
    }
    if(ballx<= borderwidth){
      balldx = -balldx;
      ballx = borderwidth;
    }
  }

  public void CheckBat() {
    batpos += batdpos;

    if(batpos < borderwidth)batpos = borderwidth;
    else if (batpos >(d.width-borderwidth-batwidth))
      batpos = (d.width-borderwidth - batwidth);
    if(bally >= (d.height-scoreheight-2*borderwidth-ballsize) &&
       bally<(d.height-scoreheight-2*borderwidth) &&
       (ballx+ballsize) >= batpos &&
       ballx <= (batpos + batwidth)){
      bally = d.height-scoreheight-ballsize-borderwidth*2;
      balldy = -dxval;
      balldx = CheckBatBounce(balldx,ballx - batpos);
    }
  }

  public void CheckBricks() {
    int i,j,x,y;
    int xspeed = balldx;
    if(xspeed <0) xspeed =-xspeed;
    int ydir = balldy;

    if(bally <(startline - ballsize)||bally > (startline+numlines*(brickspace + brickheight)))
      return;
    for(j=0;j<numlines;j++){
      for(i = 0;i<bricksperline;i++){
        if(showbrick[j*bricksperline + i]){
          y = startline + j*(brickspace + brickheight);
          x = borderwidth + i* (brickspace + brickwidth);
          if(bally >= (y - ballsize) && bally<(y+ brickheight)&&
             ballx >= (x - ballsize) && ballx<(x+ brickwidth)){
            showbrick[j*bricksperline + i] =false;
            score +=(numlines-j);
            au.play();
            if(ballx >=(x-ballsize) && ballx<=(x-ballsize +3)){
              //左边
              balldx = -xspeed;
            }else if(ballx <= (x+brickwidth -1) && ballx >= (x+ brickwidth -4)){
              //右边
              balldx = xspeed;
            }
            balldy = -ydir;
          }
        }
      }
    }
  }

  public void BatDummyMove() {
  }

  public void DrawPlayField() {
    goff.setColor(Color.white);
    goff.fillRect(0,0,d.width,borderwidth);
    goff.fillRect(0,0,borderwidth,d.height);
    goff.fillRect(d.width-borderwidth,0,borderwidth,d.height);
    goff.fillRect(batpos,d.height-2*borderwidth-scoreheight,batwidth,batheight);
    //goff.f
    goff.fillRect(ballx,bally,ballsize,ballsize);
  }



  private void playGame() {
    MoveBall();
    CheckBat();
    CheckBricks();
    DrawPlayField();
    DrawBricks();
    ShowScore();
  }

  public int CheckBatBounce(int dy, int delta) {
    int sign;
    int stepsize,i = -ballsize,j =0;
    stepsize=(ballsize + batwidth)/8;

    if(dy>0)sign = 1;
      else sign = -1;
    while(i< batwidth && delta>i){
      i += stepsize;
      j++;
    }
    switch(j){
      case 0:
      case 1:
        return -4;
      case 2:
        return -3;
      case 7:
        return 3;
      case 3:
      case 6:
        return sign * 2;
      case 4:
      case 5:
        return sign * 1;
      default:
        return 4;
    }

  }

  public void ShowScore() {
    String s;
    goff.setFont(smallfont);
    goff.setColor(Color.white);
    s ="得分:"+score;
    goff.drawString(s,40,d.height-5);
    s ="生命:"+ballsleft;
    goff.drawString(s,d.width-40-fmsmall.stringWidth(s),d.height-5);

  }

  public void run(){

    ingame = true;

    this.requestFocus();
    long starttime;
    Graphics g;
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    g = getGraphics();
     while (true){
       starttime = System.currentTimeMillis();
       try{
         paint(g);
         starttime += 20;
         Thread.sleep(Math.max(0,starttime-System.currentTimeMillis()));
       }catch(InterruptedException e){
         break;
       }
     }
  }
  public void start(){
    requestFocus();
    if(theThread == null){
      theThread = new Thread(this);
      theThread.start();
    }
  }
  public void stop(){
    if(theThread != null){
      theThread.stop();
      theThread = null;
    }
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -