Hello everyone, Im kinda having some trouble with my code and was hoping you guys could help me out.

Here's what its supposed to do:

have asteroids, shoot bullets, move, and have hyperspace (just a little warp to a random point on the screen)

Here's what it does:

the ship is visible HOWEVER, its stuck (it can slightly rotate) so it cant move, no asteroids show up and no bullets come out, and hyperspace doesnt work. Nasically it does everything its not supposed to do.

thanks for the help in advanced

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.applet.Applet;

/******************************************************************************
  The Sprite class defines a game object, including it's shape,
  position, movement and rotation.
******************************************************************************/

class Sprite 
{

  // Fields:

  static int width;          // Dimensions of the graphics area.
  static int height;

  Polygon shape;             // Base sprite shape, centered at the origin (0,0).
  
  double deltaAngle;
  boolean active;
  double  angle;             // Current angle of rotation.
  double  x, y;              // 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 translation to get screen
                             // position. Used for drawing on the screen and in
                             // detecting collisions.

  // Constructor:

  public Sprite() 
  {

    this.shape = new Polygon();
	this.active = false;
    this.angle = 0.0;
	this.deltaAngle = 0.0;
    this.x = 0.0;
    this.y = 0.0;
    this.deltaX = 0.0;
    this.deltaY = 0.0;
    this.sprite = new Polygon();
  }

  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.

   
    double tempx = x;
    x += deltaX;
    if (x < -width / 2) 
	{
	//deltaX=-deltaX;	  //bounce		
	//x = tempx; //stick
      x += width;  //wrap
    }
    if (x > width / 2) 
	{
	//deltaX=-deltaX;	  //bounce
	//x = tempx;   //stick
      x -= width;  //wrap
    }
    double tempy = y;
    y -= deltaY;
    if (y < -height / 2) 
	{
	//deltaY=-deltaY;    //bounce
//	y=tempy;      //stick
      y += height;  //wrap
    }
    if (y > height / 2) 
	{
	//deltaY=-deltaY;    //bounce
//	y=tempy;      //stick
      y -= height;  //wrap
    }
    
  }

  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.x) + 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.y) + height / 2);
  }
  
   public boolean isColliding(Sprite 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.contains(s.sprite.xpoints[i], s.sprite.ypoints[i]))
        return true;
    for (i = 0; i < this.sprite.npoints; i++)
      if (s.sprite.contains(this.sprite.xpoints[i], this.sprite.ypoints[i]))
        return true;
    return false;
  }
}

/******************************************************************************
  Main applet code.

<applet code="Asteroids5.class" width="500" height="500">
</applet>

******************************************************************************/

public class Asteroids5 extends Applet implements Runnable, KeyListener 
{

  Thread loopThread;

  static final int DELAY = 20;             // Milliseconds between screen and
  static final int FPS   = 50;                // the resulting frame rate.
    //Math.round(1000 / DELAY);
	
  static final int MAX_SHOTS =  8;          // Maximum number of sprites
  static final int MAX_ROCKS =  8;          // for photons, asteroids and

  static final int SCRAP_COUNT  = 2 * FPS;  // Timer counter starting values
  static final int HYPER_COUNT  = 3 * FPS;  // calculated using number of
  static final int STORM_PAUSE  = 2 * FPS;

  static final int    MIN_ROCK_SIDES =   6; // Ranges for asteroid shape, size
  static final int    MAX_ROCK_SIDES =  16; // speed and rotation.
  static final int    MIN_ROCK_SIZE  =  20;
  static final int    MAX_ROCK_SIZE  =  40;
  static final double MIN_ROCK_SPEED =  40.0 / FPS;
  static final double MAX_ROCK_SPEED = 240.0 / FPS;

  static final int MAX_SHIPS = 3;           // Starting number of ships for
                                            // each game.
  static final int NEW_SHIP_POINTS = 5000;

  // Ship's rotation and acceleration rates and maximum speed.

  static final double SHIP_ANGLE_STEP = Math.PI/60; //Math.PI / FPS;//0.06283. . . 
  static final double SHIP_SPEED_STEP = 0.2;//15.0 / FPS;//0.3
  static final double MAX_SHIP_SPEED  = 7;//1.25 * 240.0 / FPS;//6.0
  
  static final int FIRE_DELAY = 50;         // Minimum number of milliseconds
                                            // required between photon shots.
	
  static final int BIG_POINTS    =  25;     // Points scored for shooting
  static final int SMALL_POINTS  =  50;     // various objects.

   // Game data.

  int score;
  int highScore;
  int newShipScore;

  // Flags for game state and options.

  boolean playing;
  boolean paused;
  
  // Key flags.

  boolean left  = false;
  boolean right = false;
  boolean up    = false;
  boolean down  = false;
  
  // Sprite objects.

  Sprite   ship;
  Sprite[] photons    = new Sprite[MAX_SHOTS];
  Sprite[] asteroids  = new Sprite[MAX_ROCKS];

  // Ship data.

  int shipsLeft;       // Number of ships left in game, including current one.
  int shipCounter;     // Timer counter for ship explosion.
  int hyperCounter;    // Timer counter for hyperspace.

  // Photon data.

  int   photonIndex;    // Index to next available photon sprite.
  long  photonTime;     // Time value used to keep firing rate constant.

  
  // Asteroid data.

  boolean[] asteroidIsSmall = new boolean[MAX_ROCKS];    // Asteroid size flag.
  int       asteroidsCounter;                            // Break-time counter.
  double    asteroidsSpeed;                              // Asteroid speed.
  int       asteroidsLeft;                               // Number of active asteroids.

  
  // Data for the screen font.

  Font font      = new Font("SansSerif", Font.BOLD, 12);
  FontMetrics fm = getFontMetrics(font);
  int fontWidth  = fm.getMaxAdvance();
  int fontHeight = fm.getHeight();

  // Off screen image.

  Dimension offDimension;
  Image     offImage;
  Graphics  offGraphics;

  public void init() 
  {

    Dimension d = getSize();
	int i;
    
    addKeyListener(this);
	requestFocus();
   
    // Save the screen size.

    Sprite.width = d.width;
    Sprite.height = d.height;
	
	// Create shape for the ship sprite.

    ship = new Sprite();
    ship.shape.addPoint(0, -10);
    ship.shape.addPoint(7, 10);
    ship.shape.addPoint(-7, 10);
	
	// Create shape for each photon sprites.

    for (i = 0; i < MAX_SHOTS; i++) 
	{
      photons[i] = new Sprite();
      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 asteroid sprites.

    for (i = 0; i < MAX_ROCKS; i++)
      asteroids[i] = new Sprite();

	highScore = 0;
    initGame();
    endGame();
  
  }
  
   public void initGame() 
   {

    // Initialize game data and sprites.

    score = 0;
    shipsLeft = MAX_SHIPS;
    asteroidsSpeed = MIN_ROCK_SPEED;
    newShipScore = NEW_SHIP_POINTS;
    initShip();
    initPhotons();
    initAsteroids();
    playing = true;
	paused = false;
    photonTime = System.currentTimeMillis();
  }

  public void endGame() 
  {

    // Stop ship, flying saucer, guided missle and associated sounds.

    playing = false;
    stopShip();
  }

  public void start() 
  {

    if (loopThread == null) 
	{
      loopThread = new Thread(this);
      loopThread.start();
    }
  }

  public void stop() 
  {

    if (loopThread != null) 
	{
      loopThread = null;
    }
  }

  
  
  public void run() 
  {
    // This is the main loop
	
	init();
	
	
   
    while (Thread.currentThread() == loopThread) 
	{

		initShip();
	  if(!paused)
	  {
        // Move and process all sprites.
	
        updateShip();
        updatePhotons();
        updateAsteroids();

        // Check the score and advance high score, add a new ship or start the
        // flying saucer as necessary.

        if (score > highScore)
          highScore = score;
        if (score > newShipScore) 
		{
          newShipScore += NEW_SHIP_POINTS;
          shipsLeft++;
        }
	   }

        // If all asteroids have been destroyed create a new batch.

        if (asteroidsLeft <= 0)
            if (--asteroidsCounter <= 0)
              initAsteroids();

      // Update the screen and set the timer for the next loop.

      repaint();
      try 
	  {
        Thread.sleep(20);
      }
      catch (InterruptedException e) 
	  {
        break;
      }
    }
  }

  public void initShip() 
  {

    // Reset the ship sprite at the center of the screen.

    ship.active = true;
    ship.angle = 0.0;
    ship.deltaAngle = 0.0;
    ship.x = 0.0;
    ship.y = 0.0;
    ship.deltaX = 0.0;
    ship.deltaY = 0.0;
    ship.render();
  }

  public void updateShip() 
  {

    double dx, dy, speed;
	
    // Rotate the ship if left or right cursor key is down.

    if (left) 
	{
      ship.angle += SHIP_ANGLE_STEP;
      if (ship.angle > 2 * Math.PI)
        ship.angle -= 2 * Math.PI;
    }
    if (right) 
	{
      ship.angle -= SHIP_ANGLE_STEP;
      if (ship.angle < 0)
        ship.angle += 2 * Math.PI;
    }

    // Fire thrusters if up or down cursor key is down.

    dx = SHIP_SPEED_STEP * -Math.sin(ship.angle);
    dy = SHIP_SPEED_STEP *  Math.cos(ship.angle);
    if (up) 
	{
      ship.deltaX += dx;
      ship.deltaY += dy;
    }
    if (down) 
	{
        ship.deltaX -= dx;
        ship.deltaY -= dy;
    }

    // Don't let ship go past the speed limit.

    if (up || down) 
	{
      speed = Math.sqrt(ship.deltaX * ship.deltaX + ship.deltaY * ship.deltaY);
      if (speed > MAX_SHIP_SPEED) 
	  {
        dx = MAX_SHIP_SPEED * -Math.sin(ship.angle);
        dy = MAX_SHIP_SPEED *  Math.cos(ship.angle);
        if (up)
          ship.deltaX = dx;
        else
          ship.deltaX = -dx;
        if (up)
          ship.deltaY = dy;
        else
          ship.deltaY = -dy;
      }
    }

    // Move the ship. If it is currently in hyperspace, advance the countdown.

    if (ship.active) 
	{
      ship.advance();
      ship.render();
      if (hyperCounter > 0)
        hyperCounter--;
   // Ship is exploding, advance the countdown or create a new ship if it is
    // done exploding. The new ship is added as though it were in hyperspace.
    // (This gives the player time to move the ship if it is in imminent
    // danger.) If that was the last ship, end the game.

    else
      if (--shipCounter <= 0)
        if (shipsLeft > 0) 
		{
          initShip();
          hyperCounter = HYPER_COUNT;
        }
        else
          endGame();
    }
   }
 
 public void stopShip() 
 {

    ship.active = false;
    shipCounter = SCRAP_COUNT;
    if (shipsLeft > 0)
      shipsLeft--;
  }

 
  public void initPhotons() 
  {

    int i;

    for (i = 0; i < MAX_SHOTS; i++)
      photons[i].active = false;
    photonIndex = 0;
  }

  public void updatePhotons()
  {

    int i;

    // Move any active photons. Stop it when its counter has expired.

    for (i = 0; i < MAX_SHOTS; i++)
      if (photons[i].active) 
	  {
        //if (!photons[i].advance())
          photons[i].render();
	  }
        else
          photons[i].active = false;
      
  }
 
  public void initAsteroids()
  {

    int i, j;
    int s;
    double theta, r;
    int x, y;

    // Create random shapes, positions and movements for each asteroid.

    for (i = 0; i < MAX_ROCKS; i++) 
	{

      // Create a jagged shape for the asteroid and give it a random rotation.

      asteroids[i].shape = new Polygon();
      s = MIN_ROCK_SIDES + (int) (Math.random() * (MAX_ROCK_SIDES - MIN_ROCK_SIDES));
      for (j = 0; j < s; j ++) 
	  {
        theta = 2 * Math.PI / s * j;
        r = MIN_ROCK_SIZE + (int) (Math.random() * (MAX_ROCK_SIZE - MIN_ROCK_SIZE));
        x = (int) -Math.round(r * Math.sin(theta));
        y = (int)  Math.round(r * Math.cos(theta));
        asteroids[i].shape.addPoint(x, y);
      }
      asteroids[i].active = true;
      asteroids[i].angle = 0.0;

      // Place the asteroid at one edge of the screen.

      if (Math.random() < 0.5) 
	  {
        asteroids[i].x = -Sprite.width / 2;
        if (Math.random() < 0.5)
          asteroids[i].x = Sprite.width / 2;
        asteroids[i].y = Math.random() * Sprite.height;
      }
      else 
	  {
        asteroids[i].x = Math.random() * Sprite.width;
        asteroids[i].y = -Sprite.height / 2;
        if (Math.random() < 0.5)
          asteroids[i].y = Sprite.height / 2;
      }

      // Set a random motion for the asteroid.

      asteroids[i].deltaX = Math.random() * asteroidsSpeed;
      if (Math.random() < 0.5)
        asteroids[i].deltaX = -asteroids[i].deltaX;
      asteroids[i].deltaY = Math.random() * asteroidsSpeed;
      if (Math.random() < 0.5)
        asteroids[i].deltaY = -asteroids[i].deltaY;

      asteroids[i].render();
      asteroidIsSmall[i] = false;
    }

    asteroidsCounter = STORM_PAUSE;
    asteroidsLeft = MAX_ROCKS;
    if (asteroidsSpeed < MAX_ROCK_SPEED)
      asteroidsSpeed += 0.5;
  }
  
   public void updateAsteroids() 
   {

    int i, j;

    // Move any active asteroids and check for collisions.

    for (i = 0; i < MAX_ROCKS; i++)
      if (asteroids[i].active) 
	  {
        asteroids[i].advance();
        asteroids[i].render();

        // If hit by photon, kill asteroid and advance score. If asteroid is
        // large, make some smaller ones to replace it.

        for (j = 0; j < MAX_SHOTS; j++)
          if (photons[j].active && asteroids[i].active && asteroids[i].isColliding(photons[j])) 
		  {
            asteroidsLeft--;
            asteroids[i].active = false;
            photons[j].active = false;
            if (!asteroidIsSmall[i]) 
			{
              score += BIG_POINTS;
            }
            else
              score += SMALL_POINTS;
          }

        // If the ship is not in hyperspace, see if it is hit.

        if (ship.active && hyperCounter <= 0 &&
            asteroids[i].active && asteroids[i].isColliding(ship)) 
			{

               stopShip();
            }
       }
   }
 
  public void keyPressed(KeyEvent e) 
  {
  
    // Check if any cursor keys have been pressed and set flags.

    if (e.getKeyCode() == KeyEvent.VK_LEFT)
      left = true;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT)
      right = true;
    if (e.getKeyCode() == KeyEvent.VK_UP)
      up = true;
    if (e.getKeyCode() == KeyEvent.VK_DOWN)
      down = true;
        
  }

  public void keyReleased(KeyEvent e) 
  {

    char c;
	
    // Check if any cursor keys where released and set flags.

    if (e.getKeyCode() == KeyEvent.VK_LEFT)
      left = false;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT)
      right = false;
    if (e.getKeyCode() == KeyEvent.VK_UP)
      up = false;
    if (e.getKeyCode() == KeyEvent.VK_DOWN)
      down = false;

	 if (e.getKeyChar() == ' ' && ship.active) 
	 {
      photonTime = System.currentTimeMillis();
      photonIndex++;
      if (photonIndex >= MAX_SHOTS)
        photonIndex = 0;
      photons[photonIndex].active = true;
      photons[photonIndex].x = ship.x;
      photons[photonIndex].y = ship.y;
      photons[photonIndex].deltaX = 30 * -Math.sin(ship.angle);
      photons[photonIndex].deltaY = 30 *  Math.cos(ship.angle);
    }
	
	 // Allow upper or lower case characters for remaining keys.

    c = Character.toLowerCase(e.getKeyChar());

    // 'H' key: warp ship into hyperspace by moving to a random location and
    // starting counter.

    if (c == 'h' && ship.active && hyperCounter <= 0) 
	{
      ship.x = Math.random() * Sprite.width;
      ship.y = Math.random() * Sprite.height;
      hyperCounter = HYPER_COUNT;
    }
	  
  }

  public void keyTyped(KeyEvent e) 
  {}

  public void update(Graphics g) 
  {
    paint(g);
  }

  public void paint(Graphics g) 
  {

    Dimension d = getSize();
	int i;
	int c;
	String s;
   
    // Create the off screen graphics context, if none exists.

    if (offGraphics == null || d.width != offDimension.width || d.height != offDimension.height) 
	{
      offDimension = d;
      offImage = createImage(d.width, d.height);
      offGraphics = offImage.getGraphics();
    }
	
	 // Draw photon bullets.

    offGraphics.setColor(Color.white);
    for (i = 0; i < MAX_SHOTS; i++)
      if (photons[i].active)
        offGraphics.drawPolygon(photons[i].sprite);
		
	
    // Draw the asteroids.

    for (i = 0; i < MAX_ROCKS; i++)
      //if (asteroids[i].active)
	  {
        offGraphics.setColor(Color.white);
        offGraphics.drawPolygon(asteroids[i].sprite);
        offGraphics.drawLine(asteroids[i].sprite.xpoints[asteroids[i].sprite.npoints - 1], asteroids[i].sprite.ypoints[asteroids[i].sprite.npoints - 1],
                             asteroids[i].sprite.xpoints[0], asteroids[i].sprite.ypoints[0]);
	  }

    // Fill in background 

    offGraphics.setColor(Color.black);
    offGraphics.fillRect(0, 0, d.width, d.height);
   
     // Draw the ship, counter is used to fade color to white on hyperspace.

    //c = 255 - (255 / HYPER_COUNT) * hyperCounter;

	  offGraphics.setColor(Color.white); 
      //offGraphics.setColor(new Color(c, c, c));
      offGraphics.drawPolygon(ship.sprite);
      offGraphics.drawLine(ship.sprite.xpoints[ship.sprite.npoints - 1], ship.sprite.ypoints[ship.sprite.npoints - 1],
                           ship.sprite.xpoints[0], ship.sprite.ypoints[0]);
	
	
	
	offGraphics.setFont(font);
    offGraphics.setColor(Color.white);

    offGraphics.drawString("Score: " + score, fontWidth, fontHeight);
    offGraphics.drawString("Ships: " + shipsLeft, fontWidth, d.height - fontHeight);
    s = "High: " + highScore;
    
    // Copy the off screen buffer to the screen.

    g.drawImage(offImage, 0, 0, this);
  }
}

ok i fixed why it wouldnt move, stupid mistake, i had a bit one to many initializers in my main loop function but now it resets its position after a like 3-5 seconds >.>

lol next update, saw that i didnt set the variable = 0 for hyperspace but still does the same thing......

What is supposed to happen when you open your code in the appletviewer?

play a game of asteroids just simpler. I only need to shoot move and have hyperspace and have some destroyable rocks floatin around

What is supposed to happen when you open your code in the appletviewer?

There is a triangular shape in the middle of the black screen. Nothing moves. The top of the triangle moves a little when an arrow key is pressed.
?????

yea the only reason why that happened was because line 316 needs to be initGame(); instead of init();

but your supposed to have asteroids moving around on the screen, the triangle should move and shoot bullets and by pressing 'h' you should be able to warp to a random point on the screen oh and its space to shoot. Its just a normal asteroids game.

I changed the call to init() to initGame() in the run() method and no change.

ok i sent u a pm with the changes i had made (sending it to you only cuz the code is really long

let me knoe if u got

Still nothing changed.

Ok got some reactions.
What is the problem with the code?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.