asteroids.java

来自「很有趣的射击游戏」· Java 代码 · 共 1,251 行 · 第 1/3 页

JAVA
1,251
字号
/************************************************************************************************Asteroids.java  Usage:  <applet code="Asteroids.class" width=w height=h></applet>  Keyboard Controls:  S            - Start Game    P           - Pause Game  Cursor Left  - Rotate Left   Cursor Up   - Fire Thrusters  Cursor Right - Rotate Right  Cursor Down - Fire Retro Thrusters  Spacebar     - Fire Cannon   H           - Hyperspace  M            - Toggle Sound  D           - Toggle Graphics Detail************************************************************************************************/import java.awt.*;import java.net.*;import java.util.*;import java.applet.Applet;import java.applet.AudioClip;/************************************************************************************************  The AsteroidsSprite class defines a game object, including it's shape, position, movement and  rotation. It also can detemine if two objects collide.************************************************************************************************/class AsteroidsSprite {  // Fields:  static int width;    // Dimensions of the graphics area.  static int height;  Polygon shape;                 // Initial sprite shape, centered at the origin (0,0).  boolean active;                // Active flag.  double  angle;                 // Current angle of rotation.  double  deltaAngle;            // Amount to change the rotation angle.  double  currentX, currentY;    // Current position on screen.  double  deltaX, deltaY;        // Amount to change the screen position.  Polygon sprite;                // Final location and shape of sprite after applying rotation and                                 // moving to screen position. Used for drawing on the screen and                                 // in detecting collisions.  // Constructors:  public AsteroidsSprite() {    this.shape = new Polygon();    this.active = false;    this.angle = 0.0;    this.deltaAngle = 0.0;    this.currentX = 0.0;    this.currentY = 0.0;    this.deltaX = 0.0;    this.deltaY = 0.0;    this.sprite = new Polygon();  }  // Methods:  public void advance() {    // Update the rotation and position of the sprite based on the delta values. If the sprite    // moves off the edge of the screen, it is wrapped around to the other side.    this.angle += this.deltaAngle;    if (this.angle < 0)      this.angle += 2 * Math.PI;    if (this.angle > 2 * Math.PI)      this.angle -= 2 * Math.PI;    this.currentX += this.deltaX;    if (this.currentX < -width / 2)      this.currentX += width;    if (this.currentX > width / 2)      this.currentX -= width;    this.currentY -= this.deltaY;    if (this.currentY < -height / 2)      this.currentY += height;    if (this.currentY > height / 2)      this.currentY -= height;  }  public void render() {    int i;    // Render the sprite's shape and location by rotating it's base shape and moving it to    // it's proper screen position.    this.sprite = new Polygon();    for (i = 0; i < this.shape.npoints; i++)      this.sprite.addPoint((int) Math.round(this.shape.xpoints[i] * Math.cos(this.angle) + this.shape.ypoints[i] * Math.sin(this.angle)) + (int) Math.round(this.currentX) + width / 2,                 (int) Math.round(this.shape.ypoints[i] * Math.cos(this.angle) - this.shape.xpoints[i] * Math.sin(this.angle)) + (int) Math.round(this.currentY) + height / 2);  }  public boolean isColliding(AsteroidsSprite s) {    int i;    // Determine if one sprite overlaps with another, i.e., if any vertice    // of one sprite lands inside the other.    for (i = 0; i < s.sprite.npoints; i++)      if (this.sprite.inside(s.sprite.xpoints[i], s.sprite.ypoints[i]))        return true;    for (i = 0; i < this.sprite.npoints; i++)      if (s.sprite.inside(this.sprite.xpoints[i], this.sprite.ypoints[i]))        return true;    return false;  }}/************************************************************************************************  Main applet code.************************************************************************************************/public class Asteroids extends Applet implements Runnable {  // Thread control variables.  Thread loadThread;  Thread loopThread;  // Constants  static final int DELAY = 50;             // Milliseconds between screen updates.  static final int MAX_SHIPS = 3;           // Starting number of ships per game.  static final int MAX_SHOTS =  6;          // Maximum number of sprites for photons,  static final int MAX_ROCKS =  8;          // asteroids and explosions.  static final int MAX_SCRAP = 20;  static final int SCRAP_COUNT = 30;        // Counter starting values.  static final int HYPER_COUNT = 60;  static final int STORM_PAUSE = 30;  static final int UFO_PASSES  =  3;  static final int MIN_ROCK_SIDES =  8;     // Asteroid shape and size ranges.  static final int MAX_ROCK_SIDES = 12;  static final int MIN_ROCK_SIZE  = 20;  static final int MAX_ROCK_SIZE  = 40;  static final int MIN_ROCK_SPEED =  2;  static final int MAX_ROCK_SPEED = 12;  static final int BIG_POINTS    =  25;     // Points for shooting different objects.  static final int SMALL_POINTS  =  50;  static final int UFO_POINTS    = 250;  static final int MISSLE_POINTS = 500;  static final int NEW_SHIP_POINTS = 5000;  // Number of points needed to earn a new ship.  static final int NEW_UFO_POINTS  = 2750;  // Number of points between flying saucers.  // Background stars.  int     numStars;  Point[] stars;  // Game data.  int score;  int highScore;  int newShipScore;  int newUfoScore;  boolean loaded = false;  boolean paused;  boolean playing;  boolean sound;  boolean detail;  // Key flags.  boolean left  = false;  boolean right = false;  boolean up    = false;  boolean down  = false;  // Sprite objects.  AsteroidsSprite   ship;  AsteroidsSprite   ufo;  AsteroidsSprite   missle;  AsteroidsSprite[] photons    = new AsteroidsSprite[MAX_SHOTS];  AsteroidsSprite[] asteroids  = new AsteroidsSprite[MAX_ROCKS];  AsteroidsSprite[] explosions = new AsteroidsSprite[MAX_SCRAP];  // Ship data.  int shipsLeft;       // Number of ships left to play, including current one.  int shipCounter;     // Time counter for ship explosion.  int hyperCounter;    // Time counter for hyperspace.  // Photon data.  int[] photonCounter = new int[MAX_SHOTS];    // Time counter for life of a photon.  int   photonIndex;                           // Next available photon sprite.  // Flying saucer data.  int ufoPassesLeft;    // Number of flying saucer passes.  int ufoCounter;       // Time counter for each pass.  // Missle data.  int missleCounter;    // Counter for life of missle.  // Asteroid data.  boolean[] asteroidIsSmall = new boolean[MAX_ROCKS];    // Asteroid size flag.  int       asteroidsCounter;                            // Break-time counter.  int       asteroidsSpeed;                              // Asteroid speed.  int       asteroidsLeft;                               // Number of active asteroids.  // Explosion data.  int[] explosionCounter = new int[MAX_SCRAP];  // Time counters for explosions.  int   explosionIndex;                         // Next available explosion sprite.  // Sound clips.  AudioClip crashSound;  AudioClip explosionSound;  AudioClip fireSound;  AudioClip missleSound;  AudioClip saucerSound;  AudioClip thrustersSound;  AudioClip warpSound;  // Flags for looping sound clips.  boolean thrustersPlaying;  boolean saucerPlaying;  boolean misslePlaying;  // Values for the offscreen image.  Dimension offDimension;  Image offImage;  Graphics offGraphics;  // Font data.  Font font = new Font("Helvetica", Font.BOLD, 12);  FontMetrics fm;  int fontWidth;  int fontHeight;  // Applet information.  public String getAppletInfo() {    return("Asteroids, Copyright 1998 by Mike Hall.");  }  public void init() {    Graphics g;    Dimension d;    int i;    // Take credit.    System.out.println("Asteroids, Copyright 1998 by Mike Hall.");    // Find the size of the screen and set the values for sprites.    g = getGraphics();    d = size();    AsteroidsSprite.width = d.width;    AsteroidsSprite.height = d.height;    // Generate starry background.    numStars = AsteroidsSprite.width * AsteroidsSprite.height / 5000;    stars = new Point[numStars];    for (i = 0; i < numStars; i++)      stars[i] = new Point((int) (Math.random() * AsteroidsSprite.width), (int) (Math.random() * AsteroidsSprite.height));    // Create shape for the ship sprite.    ship = new AsteroidsSprite();    ship.shape.addPoint(0, -10);    ship.shape.addPoint(7, 10);    ship.shape.addPoint(-7, 10);    // Create shape for the photon sprites.    for (i = 0; i < MAX_SHOTS; i++) {      photons[i] = new AsteroidsSprite();      photons[i].shape.addPoint(1, 1);      photons[i].shape.addPoint(1, -1);      photons[i].shape.addPoint(-1, 1);      photons[i].shape.addPoint(-1, -1);    }    // Create shape for the flying saucer.    ufo = new AsteroidsSprite();    ufo.shape.addPoint(-15, 0);    ufo.shape.addPoint(-10, -5);    ufo.shape.addPoint(-5, -5);    ufo.shape.addPoint(-5, -9);    ufo.shape.addPoint(5, -9);    ufo.shape.addPoint(5, -5);    ufo.shape.addPoint(10, -5);    ufo.shape.addPoint(15, 0);    ufo.shape.addPoint(10, 5);    ufo.shape.addPoint(-10, 5);    // Create shape for the guided missle.    missle = new AsteroidsSprite();    missle.shape.addPoint(0, -4);    missle.shape.addPoint(1, -3);    missle.shape.addPoint(1, 3);    missle.shape.addPoint(2, 4);    missle.shape.addPoint(-2, 4);    missle.shape.addPoint(-1, 3);    missle.shape.addPoint(-1, -3);    // Create asteroid sprites.    for (i = 0; i < MAX_ROCKS; i++)      asteroids[i] = new AsteroidsSprite();    // Create explosion sprites.    for (i = 0; i < MAX_SCRAP; i++)      explosions[i] = new AsteroidsSprite();    // Set font data.    g.setFont(font);    fm = g.getFontMetrics();    fontWidth = fm.getMaxAdvance();    fontHeight = fm.getHeight();    // Initialize game data and put us in 'game over' mode.    highScore = 0;    sound = true;    detail = true;    initGame();    endGame();  }  public void initGame() {    // Initialize game data and sprites.    score = 0;    shipsLeft = MAX_SHIPS;    asteroidsSpeed = MIN_ROCK_SPEED;    newShipScore = NEW_SHIP_POINTS;    newUfoScore = NEW_UFO_POINTS;    initShip();    initPhotons();    stopUfo();    stopMissle();    initAsteroids();    initExplosions();    playing = true;    paused = false;  }  public void endGame() {    // Stop ship, flying saucer, guided missle and associated sounds.    playing = false;    stopShip();    stopUfo();    stopMissle();  }  public void start() {    if (loopThread == null) {      loopThread = new Thread(this);      loopThread.start();    }    if (!loaded && loadThread == null) {      loadThread = new Thread(this);      loadThread.start();    }  }  public void stop() {    if (loopThread != null) {      loopThread.stop();      loopThread = null;    }    if (loadThread != null) {      loadThread.stop();      loadThread = null;    }  }  public void run() {    int i, j;    long startTime;    // Lower this thread's priority and get the current time.    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);    startTime = System.currentTimeMillis();    // Run thread for loading sounds.    if (!loaded && Thread.currentThread() == loadThread) {      loadSounds();

⌨️ 快捷键说明

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