Exemple #1
0
  /**
   * This method actually notifies which enemies need to update their paths
   *
   * @param inMiddleOfWave
   * @param enemy
   */
  private void updateEnemyPaths(boolean inMiddleOfWave, Enemy enemy) {
    if (inMiddleOfWave) {
      Log.i("Updating path", "Updating path");
      enemy.setNeedToUpdatePath(true);

      for (Enemy child : enemy.childArray) {
        child.setNeedToUpdatePath(true);
      }

    } else {

      Path p = null;
      Enemy en = null;
      for (Enemy e : currentWave.getEnemies()) {
        if (e.getClass() != BeachballEnemy.class) {
          p = aStarHelper.getPath(e);
          en = e;
          break;
        }
      }

      // We have a wave full of beach-ball enemies
      if (en == null) return;

      if (p == null) {
        removeCurrentTower(true);
        p = aStarHelper.getPath(en);
      }

      for (Enemy e : currentWave.getEnemies()) {
        if (e.getClass() != BeachballEnemy.class) e.setPath(p.deepCopy());
        else aStarHelper.getPath(e);
      }
    }
  }
Exemple #2
0
  public Wave findSurfableWave(int waveIndex) {
    int searchWaveIndex = 0;
    long currentTime = _robot.getTime();

    for (int x = 0; x < _waves.size(); x++) {
      Wave w = (Wave) _waves.get(x);
      double distanceToWaveSource = ScanLog.myLocation().distance(w.sourceLocation);
      double distanceToWave = distanceToWaveSource - w.distanceTraveled(currentTime);

      if (w.firingWave && !w.processedBulletHit && distanceToWave > w.bulletVelocity()) {

        if (searchWaveIndex == waveIndex) {
          //					drawCircle(w.sourceLocation,
          //						w.distanceTraveled(currentTime + 1), Color.green);
          //					drawLine(w.sourceLocation,
          //						DUtils.project(w.sourceLocation, w.absBearingRadians,
          //								w.distanceTraveled(currentTime + 1)),
          //							Color.blue);
          return w;
        } else {
          searchWaveIndex++;
        }
      }
    }

    return null;
  }
Exemple #3
0
  public double getBinScore(Wave w, Point2D.Double targetLocation) {
    double binScore = 0;

    GuessFactorWindowSet gfWindow = w.guessFactorWindow(targetLocation);
    int lowIndex = w.guessFactorIndex(gfWindow.guessFactorLow);
    int highIndex = w.guessFactorIndex(gfWindow.guessFactorHigh);

    binScore +=
        _highStatBuffers.getWindowScore(
            w.targetScan, w.targetScan.getInverseScan(), w.bulletPower, BINS, lowIndex, highIndex);
    binScore +=
        _lowStatBuffers.getWindowScore(
            w.targetScan, w.targetScan.getInverseScan(), w.bulletPower, BINS, lowIndex, highIndex);

    if (_flattenerEnabled) {
      binScore +=
          _extraFlatStatBuffers.getWindowScore(
              w.targetScan,
              w.targetScan.getInverseScan(),
              w.bulletPower,
              BINS,
              lowIndex,
              highIndex);
    }

    return binScore;
  }
Exemple #4
0
  /*
  	public void onPaint(Graphics2D g) {
  		Iterator i = _renderables.iterator();
  		while(i.hasNext()){
  			Renderable r = (Renderable) i.next();
  			r.render(g);
  		}
  		_renderables.clear();
  	}
  */
  public Wave processBulletReturnFiringWave(Bullet bullet, long currentTime) {

    int tightMatchDistanceThreshold = 50;
    Wave hitWave =
        DUtils.findClosestWave(
            _waves,
            new Point2D.Double(bullet.getX(), bullet.getY()),
            _robot.getTime(),
            DUtils.ANY_WAVE,
            DUtils.FIRING_WAVE,
            tightMatchDistanceThreshold);

    if (hitWave == null) {
      return NO_WAVE_FOUND;
    }

    for (int x = 0; x < _bulletHitRegisters.size(); x++) {
      BulletHitRegister bhr = (BulletHitRegister) _bulletHitRegisters.get(x);

      bhr.registerBulletHit(bullet, hitWave, currentTime);
    }

    hitWave.processedBulletHit = true;

    return hitWave;
  }
Exemple #5
0
  /** @return all the units in the game state */
  public List<Unit> getUnits() {
    List<Unit> units = new ArrayList<Unit>();
    Lane[] lanes = map.getLanes();
    for (Lane l : lanes) {
      Wave[] waves = l.getWaves();
      for (Wave w : waves) {
        Unit[] us = w.getUnits();
        for (Unit u : us) {
          units.add(u);
        }
      }
    }

    Collections.sort(
        units,
        new Comparator<Unit>() {

          @Override
          public int compare(Unit o1, Unit o2) {
            if (o1.getCollisionStrategy() instanceof Ground
                && o2.getCollisionStrategy() instanceof Flying) return -1;
            else if (o2.getCollisionStrategy() instanceof Ground
                && o1.getCollisionStrategy() instanceof Flying) return 1;
            else return 0;
          }
        });

    return units;
  }
 /** returns the factor index for the statistics array */
 public static int getFactorIndex(Wave wave, Point2D.Double target) {
   double offsetAngle = (absoluteBearing(wave.getOrigin(), target) - wave.getAngle());
   double factor =
       Utils.normalRelativeAngle(offsetAngle)
           / maxEscapeAngle(wave.getVelocity())
           * wave.getDirection();
   return computeBin(factor);
 }
Exemple #7
0
  public void onHitByBullet(HitByBulletEvent e) {
    ScanLog.onHitByBullet(e);

    Wave hitWave = processBulletReturnFiringWave(e.getBullet(), e.getTime());

    if (hitWave != NO_WAVE_FOUND) {
      double thisHit =
          (hitWave.targetScan.getDistance() / TYPICAL_DISTANCE)
              * (hitWave.escapeAngleRange() / TYPICAL_ESCAPE_RANGE);
      _weightedEnemyShotsHit += thisHit;
      _weightedEnemyShotsHitThisRound += thisHit;
    }
  }
Exemple #8
0
  public Wave findNonSurfableWave(double minDistanceToWave) {
    long currentTime = _robot.getTime();

    for (int x = 0; x < _waves.size(); x++) {
      Wave w = (Wave) _waves.get(x);
      double distanceToWaveSource = ScanLog.myLocation().distance(w.sourceLocation);
      double distanceToWave = distanceToWaveSource - w.distanceTraveled(currentTime);

      if (!w.firingWave && distanceToWave > minDistanceToWave) {
        return w;
      }
    }

    return null;
  }
Exemple #9
0
  /**
   * Removes a tower from the field
   *
   * @param Tower t
   */
  public void removeTower(final ITower t, boolean removeTile) {
    TMXTile tile =
        tmxLayer.getTMXTileAt(
            t.getEntity().getX() + GameMap.getTileSize() / 2,
            t.getEntity().getY() + GameMap.getTileSize() / 2);

    if (blockedTileList.contains(tile) && removeTile) {
      blockedTileList.remove(tile);
    }
    activity.runOnUpdateThread(
        new Runnable() {

          @Override
          public void run() {
            t.getEntity().detachSelf();
            SubMenuManager.getReticle(t).detachSelf();
            t.getEntity().clearEntityModifiers();
            t.getEntity().clearUpdateHandlers();
          }
        });
    if (towers.contains(t)) {
      towers.remove(t);
    }

    // if the user manually deleted the tower, we need to adjust for that for the paths of the
    // enemies
    if (aStarHelper.isNavigating())
      for (Enemy e : currentWave.getEnemies()) updateEnemyPaths(true, e);
    else updateEnemyPaths(false, null);
  }
Exemple #10
0
  /**
   * When placing a tower on the field, this checks if the path needs to be updated for each enemy
   *
   * @param current
   * @param inMiddleOfWave
   */
  private void updateAffectedEnemies(TMXTile current, boolean inMiddleOfWave) {
    List<Enemy> enemies = currentWave.getEnemies();
    Path p;
    float pX;
    float pY;
    outer:
    for (Enemy enemy : enemies) {
      if (enemy == null) continue;
      p = enemy.getPath();
      for (int i = 0; i < p.getCoordinatesX().length; i++) {
        pX = p.getCoordinatesX()[i];
        pY = p.getCoordinatesY()[i];

        TMXTile tile = this.tmxLayer.getTMXTileAt(pX - enemy.getOffsetX(), pY - enemy.getOffsetY());
        if (current.equals(tile)) {
          updateEnemyPaths(inMiddleOfWave, enemy);
          if (!inMiddleOfWave) break outer;
          else break;
        }
      }
    }

    if (inMiddleOfWave) {
      Enemy dummy = new Enemy();
      dummy.setUserData("dummy");
      Path path = aStarHelper.getPath(dummy);

      if (path == null) {
        removeCurrentTower(true);
      }
    }
  }
Exemple #11
0
  public void onScannedRobot(ScannedRobotEvent e) {
    oldRobotLocation.setLocation(robotLocation);
    robotLocation.setLocation(getX(), getY());
    enemyAbsoluteBearing = getHeadingRadians() + e.getBearingRadians();
    enemyDistance = e.getDistance();
    oldEnemyLocation.setLocation(enemyLocation);
    toLocation(enemyAbsoluteBearing, enemyDistance, robotLocation, enemyLocation);

    deltaBearing =
        Utils.normalRelativeAngle(
            absoluteBearing(oldRobotLocation, enemyLocation)
                - absoluteBearing(oldRobotLocation, oldEnemyLocation));

    currentAimFactors =
        aimFactors[aimDirectionSegment()][
            Math.min(
                (int) (enemyDistance / (getBattleFieldWidth() / DISTANCE_SEGMENTS)),
                DISTANCE_SEGMENTS - 1)][
            Math.min(
                (int) (enemyLocation.getY() / (getBattleFieldHeight() / VERTICAL_SEGMENTS)),
                VERTICAL_SEGMENTS - 1)];

    setTurnGunRightRadians(
        Utils.normalRelativeAngle(
            enemyAbsoluteBearing
                + maxEnemyBearing * sign(deltaBearing) * mostVisitedFactor()
                - getGunHeadingRadians()));

    if (getEnergy() > 3.1) {
      Bullet bullet = setFireBullet(3);
      if (bullet != null) {
        Wave wave = new Wave();
        wave.wTime = getTime();
        wave.bearingDelta = deltaBearing;
        wave.oldRLocation.setLocation(robotLocation);
        wave.oldELocation.setLocation(enemyLocation);
        wave.wAimFactors = currentAimFactors;
        addCustomEvent(wave);
      }
    }

    setAhead(getY() > enemyLocation.getY() ? -50 : 50);

    setTurnRadarRightRadians(
        Utils.normalRelativeAngle(enemyAbsoluteBearing - getRadarHeadingRadians()) * 2);
  }
Exemple #12
0
  public void checkActiveWaves() {
    long currentTime = _robot.getTime();
    Point2D.Double myLocation = ScanLog.myLocation();

    for (int x = 0; x < _waves.size(); x++) {
      Wave w = (Wave) _waves.get(x);
      if (w.processedWaveBreak) {
        if (w.wavePassed(myLocation, currentTime, Wave.INACTIVE_WAVE_OFFSET)) {
          _waves.remove(x--);
        }
      } else {
        if (w.wavePassed(myLocation, currentTime)) {
          processWave(w);
        }
      }
    }
  }
Exemple #13
0
 /**
  * Checks to see if the wave has commenced. Should only fire once per wave even though there are 2
  * distinct ways to end a wave. If the wave has ended, it calls the method to initialize the next
  * wave.
  */
 public void seeIfWaveFinished() {
   if (!initializedNewWave) {
     if ((deadEnemies + aStarHelper.getNumberOfEnemiesFinished()
         == currentWave.getEnemies().size())) {
       initializedNewWave = true;
       waveFinished = true;
       endInWaveUpdateHandlers();
       initializeNextWave();
     }
   }
 }
Exemple #14
0
  public void processWave(Wave w) {
    GuessFactorWindowSet gfWindow = w.guessFactorWindow(ScanLog.myLocation());
    int gfBin = w.guessFactorIndex(gfWindow.guessFactor);
    int gfBinLow = w.guessFactorIndex(gfWindow.guessFactorLow);
    int gfBinHigh = w.guessFactorIndex(gfWindow.guessFactorHigh);
    BotScan enemyScan = w.targetScan.getInverseScan();

    for (int x = 0; x < _waveRegisters.size(); x++) {
      WaveRegister wr = (WaveRegister) _waveRegisters.get(x);

      wr.registerWaveHit(
          w.targetScan,
          enemyScan,
          w.bulletPower,
          gfWindow.guessFactor,
          gfBin,
          gfBinLow,
          gfBinHigh,
          w.firingWave,
          w.fireTime,
          w.orientation,
          w.escapeAngleRange());
    }

    w.processedWaveBreak = true;
  }
Exemple #15
0
  /** Initializes paths and move modifiers of all enemies in the next wave */
  public void initializeNextWave() {

    Log.i("Init wave", "here");

    // If the previous wave was eliminated even before all enemies technically started, the time
    // handler
    // that handles their first move modifier would never get unregistered, putting the game in
    // limbo
    this.unregisterUpdateHandler(waveGenerator.getTimeHandler());

    if (startButton.getCurrentTileIndex() > 1)
      startButton.setCurrentTileIndex(startButton.getCurrentTileIndex() - 2);

    // The player wins the game!!
    if (waveCount == 70 && lives != 0) {
      displayWinScreen();
      return;
    }

    waveGenerator.initWave(waveCount);
    currentWave = waveGenerator.get(waveCount);
    enemies = (CopyOnWriteArrayList<Enemy>) currentWave.getEnemies();
    waveCount++;
    panel.setWaveText(waveCount);

    this.aStarHelper.finishWave();
    this.deadEnemies = 0;

    /** Just for debugging */
    for (Enemy enemy : currentWave.getEnemies()) {
      if (enemy == null) continue;
      enemy.setUserData(null);
      enemy.returnHealthToNormal();
    }
    for (ITower tower : towers) {
      tower.onWaveEnd();
    }
  }
 public Screen() {
   myWave = new Wave();
   tt = new RadiationTower(500, 600);
   y = new RadiationTower(1000, 600);
   x = new Automaton_1000(600, 500);
   theMinion = new Red(new ImageIcon("MINIONPURPLEFRONT.gif"));
   theWave = myWave.getWave();
   mm = new Minion(new ImageIcon("MINIONFRONT.gif"));
   // b = new Bullet(mm, tt);
   t = new javax.swing.Timer(10, new Listener()); // adjust speed by changing the int parameter
   t
       .start(); // by altering when you call this method you can choose the start of the minion
                 // pathing!
   // t.stop(); how to stop the javax.swing.Timer
   //         a = new javax.swing.Timer(10, new BulletListener());
   //         a.start();
   thread.start();
 }
 public static Wave random() {
   Wave[] vals = Wave.values();
   return vals[Util.randomIntRange(0, vals.length)];
 }
 @Settable
 public void setWorld(GameWorld w) {
   super.setGameWorld(w);
 }
Exemple #19
0
  @Override
  public void tick(Graphics2D g, Input p1, Input p2, Sound s) {

    // Menu
    if (gameState == 0) {
      // Song
      sound.loadSound("Resources/Sounds/Menu.wav");
      sound.runLoop();

      // background
      g.setColor(Color.BLACK);
      g.fillRect(0, 0, WIDTH, HEIGHT);

      // title
      g.setColor(Color.GREEN);
      g.setFont(new Font("Arial", Font.BOLD, 100));
      centerText("DARKLIGHT 2", g, WIDTH / 2, 180);

      // selection
      g.setColor(Color.RED);
      if (gameState == 0) {
        // Song
        sound.loadSound("Resources/Sounds/Menu.wav");
        sound.runLoop();

        // background
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // title
        g.setColor(Color.GREEN);
        g.setFont(new Font("Arial", Font.BOLD, 100));
        centerText("DARKLIGHT 2", g, WIDTH / 2, 180);

        // selection
        g.setColor(Color.RED);
        if (button == 0) {

          // PLAY
          g.fillRect(WIDTH / 2 - 160, 240, 320, 90);
          if (justPressed(p1, Button.U)) {
            button = 2;
          }
          if (justPressed(p1, Button.D)) {
            button = 1;
          }
          if (justPressed(p1, Button.A) || justPressed(p1, Button.B) || justPressed(p1, Button.C)) {
            inv[0] = wep1;
            gameState = 1;
            sound.reset();
            sound.stop();
          }
        } else if (button == 1) {

          // LEADERBOARDS
          g.fillRect(WIDTH / 2 - 160, 340, 320, 90);
          if (justPressed(p1, Button.U)) {
            button = 0;
          }
          if (justPressed(p1, Button.D)) {
            button = 2;
          }
          if (justPressed(p1, Button.A) || justPressed(p1, Button.B) || justPressed(p1, Button.C)) {
            gameState = 5;
          }
        } else {
          // EXIT
          g.fillRect(WIDTH / 2 - 160, 440, 320, 90);
          if (justPressed(p1, Button.U)) {
            button = 1;
          }
          if (justPressed(p1, Button.D)) {
            button = 0;
          }
          if (justPressed(p1, Button.A) || justPressed(p1, Button.B) || justPressed(p1, Button.C)) {
            System.exit(0);
          }
        }

        // option boxes
        g.setColor(Color.GREEN);
        g.fillRect(WIDTH / 2 - 150, 250, 300, 70);
        g.fillRect(WIDTH / 2 - 150, 350, 300, 70);
        g.fillRect(WIDTH / 2 - 150, 450, 300, 70);
        // option box text
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.PLAIN, 30));
        centerText("PLAY", g, WIDTH / 2, 295);
        centerText("LEADERBOARD", g, WIDTH / 2, 395);
        centerText("EXIT", g, WIDTH / 2, 495);

        //			g.setColor(Color.YELLOW);
        //			g.fillRect(WIDTH/2 - 352, 20, 704, 192);
      }
    }
    // Game
    if (gameState == 1) {
      arena.draw(g);

      // Sound
      sound.loadSound("Resources/Sounds/ambient.wav");
      sound.runLoop();

      //			// offset borders
      //			g.setColor(Color.RED);
      //			g.drawRect(0, 0, arena.xOffsetBorder, HEIGHT);								// left
      //			g.drawRect(WIDTH - arena.xOffsetBorder, 0, arena.xOffsetBorder, HEIGHT);	// right
      //			g.drawRect(0, 0, WIDTH, arena.yOffsetBorder);								// top
      //			g.drawRect(0, HEIGHT - arena.yOffsetBorder, WIDTH, arena.yOffsetBorder);	// bottom

      if (wave.falling) {
        count = 0;
        gameState = 2;
      }

      // wave
      wave.newWave(g, arena, player);
      wave.maintain(g, arena, player, swordSpec);

      // If enemy spots, play battle sound
      for (Enemy enemy : wave.enemies.values()) {
        if (enemy.spottedPlayer) {

          // Check to play noise
          int temp = (int) (Math.random() * 150);
          if (temp <= 1) {
            // Check for Ghoul or Golem
            if (enemy.type <= 60) {
              // Play Ghoul sound
              monster.loadSound("Resources/Sounds/ghoul.wav");
              monster.run();
            }

            if (enemy.type > 85) {
              // Play golem sound
              monster.loadSound("Resources/Sounds/golem.wav");
              monster.run();
            }
          }

          battle.loadSound("Resources/Sounds/Game Song.wav");
          battle.runLoop();
          break;
        }
      }

      // Stop battle sound, new wave
      if (wave.waveStart && wave.wave != 0) {
        battle.stop();
        battle.reset();
      }

      // player
      player.draw(g);
      player.movement(p1, arena);
      player.weapon = weapon;
      basicAttack(g, p1);
      specialAttack(g, p1);
      weaponPickup(g, p1, arena);
      weaponSwap(p1);

      if (player.health <= 0) {
        gameState = 3;
        sound.stop();
        sound.reset();
        battle.stop();
        battle.reset();
      }

      if (justPressed(p1, Button.C)) {
        wave.enemies.clear();
      }

      g.setColor(Color.BLACK);
      g.fillRect(0, 0, (int) (player.x - 256), HEIGHT);
      g.fillRect((int) (player.x + 256), 0, (int) (WIDTH - player.x - 255), HEIGHT);
      g.fillRect(0, 0, WIDTH, (int) (player.y - 256));
      g.fillRect(0, (int) (player.y + 256), WIDTH, (int) (HEIGHT - player.y - 255));
      g.drawImage(TextureLoader.light, (int) (player.x - 256), (int) (player.y - 256), null);

      // HUD
      int floor = (wave.wave % 10 == 0) ? (wave.wave + 9) / 10 : (wave.wave + 10) / 10;
      int currentWave = (wave.wave % 10 == 0) ? 10 : wave.wave % 10;
      g.setColor(Color.WHITE);
      g.setFont(new Font("Arial", Font.BOLD, 20));
      g.drawString("Floor " + floor + " | Wave " + currentWave, 5, 20);
      g.setFont(new Font("Arial", Font.PLAIN, 10));
      g.drawString("Remaining enemies: " + wave.enemies.size(), 5, 30);

      g.setColor(Color.DARK_GRAY);
      g.fillRect(347, 531, 330, 10);
      g.fillRect(347, 541, 10, 20);
      g.fillRect(507, 541, 10, 20);
      g.fillRect(667, 541, 10, 20);
      g.fillRect(347, 561, 330, 15);
      g.setColor(Color.GREEN);
      if (player.health <= 100) {
        g.fillRect(357, 541, (int) (150 * (player.health / 100)), 20);
      } else {
        g.fillRect(357, 541, 150, 20);
        g.setColor(Color.ORANGE);
        g.fillRect(357, 541, (int) (150 * ((player.health - 100) / 100)), 20);
      }
      g.setColor(Color.BLUE);
      g.fillRect(
          517 + (int) (150 - (150 * (player.mana / 100))),
          541,
          (int) (150 * (player.mana / 100)),
          20);

      g.dispose();
    }

    // Floor switching
    if (gameState == 2) {
      g.setColor(new Color(0, 0, 0, 4 * count));
      g.fillRect(0, 0, WIDTH, HEIGHT);
      count++;
      if (count == 60) {
        arena = new Arena();
        player.x = WIDTH / 2;
        player.y = HEIGHT / 2;
        wave.falling = false;
        wave.hole = false;
        wave.transition.reset();
        wave.waveStart = true;
        wave.difficulty *= 1.1;
        gameState = 1;
      }
    }

    // Game Over
    if (gameState == 3) {

      // Sound
      sound.loadSound("Resources/Sounds/Death.wav");
      sound.runOnce();

      g.setColor(Color.RED);
      g.setFont(new Font("Arial", Font.BOLD, 150));
      centerText("GAME OVER", g, WIDTH / 2, HEIGHT / 2);
      wait++;
      yourScore = wave.score;
      waveNum = (wave.wave % 10 == 0) ? 10 : wave.wave % 10;
      if (justPressed(p1, Button.A) || justPressed(p1, Button.B) || justPressed(p1, Button.C)) {

        sound.stop();
        sound.reset();
        gameState = 0;
        reset();
      }

      if (wait == 3000) {
        sound.stop();
        sound.reset();
        gameState = 0;
        reset();
      }
    }
    // Enter Your initials
    if (gameState == 4) {
      g.setColor(Color.BLACK);
      g.fillRect(0, 0, WIDTH, HEIGHT);
      g.setColor(Color.RED);
      g.setFont(new Font("Arial", Font.PLAIN, 45));
      centerText("Enter Your Initials", g, (Game.WIDTH / 2), (Game.HEIGHT / 4));
      centerText("Press C to enter", g, (Game.WIDTH / 2), (Game.HEIGHT / 2 + 100));
      g.drawString(abcs[i], (Game.WIDTH / 2) - 55, (Game.HEIGHT / 2));
      g.drawString(abcs[j], (Game.WIDTH / 2), (Game.HEIGHT / 2));
      g.drawString(abcs[k], (Game.WIDTH / 2) + 55, (Game.HEIGHT / 2));
      name = abcs[i] + abcs[j] + abcs[k];

      if (active1) g.fillRect((Game.WIDTH / 2) - 55, (Game.HEIGHT / 2) + 5, 35, 5);
      if (active2) g.fillRect((Game.WIDTH / 2) + 5, (Game.HEIGHT / 2) + 5, 35, 5);
      if (active3) g.fillRect((Game.WIDTH / 2) + 55, (Game.HEIGHT / 2) + 5, 35, 5);

      if (!pressedBefore) {
        if (p1.pressed(Button.U)
            || p1.pressed(Button.D)
            || p1.pressed(Button.L)
            || p1.pressed(Button.R)
            || p1.pressed(Button.A)
            || p1.pressed(Button.B)
            || p1.pressed(Button.C)) {
          pressedBefore = true;
        } else {
          pressedBefore = false;
        }
      } else {
        if (!p1.pressed(Button.U)
            && !p1.pressed(Button.D)
            && !p1.pressed(Button.L)
            && !p1.pressed(Button.R)
            && !p1.pressed(Button.A)
            && !p1.pressed(Button.B)
            && !p1.pressed(Button.C)) {
          pressedBefore = false;
        } else {
          return;
        }
      }
      if (p1.pressed(Button.C)) {
        storeScores.main();
        reset();
        gameState = 5;
      }
      if (active1) {

        if (p1.pressed(Button.U)) {
          i += 1;
          if (i > abcs.length - 1) i = 0;
        }
        if (p1.pressed(Button.D)) {
          i -= 1;
          if (i < 0) i = abcs.length - 1;
        }
        if (p1.pressed(Button.L)) {
          active1 = false;
          active3 = true;
        }
        if (p1.pressed(Button.R)) {
          active1 = false;
          active2 = true;
        }
        return;
      }
      if (active2) {

        if (p1.pressed(Button.U)) {
          j += 1;
          if (j > abcs.length - 1) j = 0;
        }
        if (p1.pressed(Button.D)) {
          j -= 1;
          if (j < 0) j = abcs.length - 1;
        }
        if (p1.pressed(Button.L)) {
          active2 = false;
          active1 = true;
        }
        if (p1.pressed(Button.R)) {
          active2 = false;
          active3 = true;
        }
        return;
      }
      if (active3) {

        if (p1.pressed(Button.U)) {
          k += 1;
          if (k > abcs.length - 1) k = 0;
        }
        if (p1.pressed(Button.D)) {
          k -= 1;
          if (k < 0) k = abcs.length - 1;
        }
        if (p1.pressed(Button.L)) {
          active3 = false;
          active2 = true;
        }
        if (p1.pressed(Button.R)) {
          active3 = false;
          active1 = true;
        }
        return;
      }
    }

    // high scores
    if (gameState == 5) {
      storeScores.Read();
      g.setColor(Color.BLACK);
      g.fillRect(0, 0, WIDTH, HEIGHT);
      g.setColor(Color.RED);
      g.setFont(new Font("Arial", Font.PLAIN, 35));
      centerText("High Scores", g, (Game.WIDTH / 2), (Game.HEIGHT / 16));
      g.drawLine(0, Game.HEIGHT / 16 + 8, 1200, Game.HEIGHT / 16 + 8);
      g.drawString("Enemies killed", Game.WIDTH / 2 + 150, Game.HEIGHT / 16 + 60);
      g.drawString("Wave", Game.WIDTH / 2, Game.HEIGHT / 16 + 60);
      g.drawString("Floor", Game.WIDTH / 2 - 210, Game.HEIGHT / 16 + 60);
      int height = -80;
      for (int l = 0; l < 10; l++) {
        g.drawString(storeScores.nameList.get(l), Game.WIDTH / 2 - 400, Game.HEIGHT / 8 - height);
        height = height - 40;
      }
      // g.drawString(storeScores, Game.WIDTH / 2, Game.HEIGHT / 2);
      wait++;
      if (wait == 1005) {
        sound.stop();
        sound.reset();
        wait = 0;
        yourScore = 0;
        waveNum = 0;
        i = 0;
        j = 0;
        k = 0;
        floorNum = 0;
        gameState = 0;
      }
    }

    updateKeyState(p1);
  }
Exemple #20
0
  public double checkDanger(
      RobotState startState,
      int movementOption,
      boolean previouslyMovingClockwise,
      int surfableWaveIndex,
      int recursionLevels) {

    if (surfableWaveIndex >= recursionLevels) {
      return 0;
    }

    boolean predictClockwiseOrNot;
    if (movementOption == CLOCKWISE_OPTION) {
      predictClockwiseOrNot = true;
    } else if (movementOption == COUNTERCLOCKWISE_OPTION) {
      predictClockwiseOrNot = false;
    } else {
      predictClockwiseOrNot = previouslyMovingClockwise;
    }

    Wave surfWave = findSurfableWave(surfableWaveIndex);

    if (surfWave == null) {
      if (surfableWaveIndex == FIRST_WAVE) {
        double nonSurfableWaveDistance = 150;
        surfWave = findNonSurfableWave(nonSurfableWaveDistance);
      }

      if (surfWave == null) {
        return NO_SURFABLE_WAVES;
      }
    }
    /*
    		Color drawColor = Color.white;
    		if (surfableWaveIndex != 0 || movementOption == STOP_OPTION) {
    			drawColor = Color.blue;
    		}
    */
    double waveHitInterceptOffset = surfWave.bulletVelocity() + BOT_HALF_WIDTH;
    double wavePassedInterceptOffset = surfWave.bulletVelocity();
    RobotState predictedState = startState;
    RobotState dangerState = startState;

    boolean wavePassed = false;
    boolean waveHit = false;

    double maxVelocity = (movementOption == STOP_OPTION) ? 0 : 8;

    do {
      double orbitAbsBearing =
          DUtils.absoluteBearing(surfWave.sourceLocation, predictedState.location);
      double orbitDistance = surfWave.sourceLocation.distance(predictedState.location);
      double attackAngle = _currentDistancer.attackAngle(orbitDistance, _desiredDistance);
      boolean clockwiseSmoothing = predictClockwiseOrNot;

      if (orbitDistance < _smoothAwayDistance) {
        clockwiseSmoothing = !clockwiseSmoothing;
      }

      predictedState =
          DUtils.nextPerpendicularWallSmoothedLocation(
              predictedState.location,
              orbitAbsBearing,
              predictedState.velocity,
              maxVelocity,
              predictedState.heading,
              attackAngle,
              clockwiseSmoothing,
              predictedState.time,
              DUtils.battleField,
              DUtils.battleFieldWidth,
              DUtils.battleFieldHeight,
              _wallStick,
              DUtils.OBSERVE_WALL_HITS);

      if (!waveHit
          && surfWave.wavePassed(
              predictedState.location, predictedState.time, waveHitInterceptOffset)) {

        dangerState = predictedState;
        waveHit = true;
      }

      if (!wavePassed
          && surfWave.wavePassed(
              predictedState.location, predictedState.time, wavePassedInterceptOffset)) {

        wavePassed = true;
      }
    } while (!wavePassed);

    //		drawPoint(predictedState.location, drawColor);

    double danger = getBinScore(surfWave, dangerState.location);
    danger *= DUtils.bulletDamage(surfWave.bulletPower);

    double currentDistanceToWaveSource = ScanLog.myLocation().distance(surfWave.sourceLocation);
    double currentDistanceToWave =
        currentDistanceToWaveSource - surfWave.distanceTraveled(_robot.getTime());
    double timeToImpact = currentDistanceToWave / DUtils.bulletVelocity(surfWave.bulletPower);

    if (_flattenerEnabled) {
      danger /= DUtils.square(timeToImpact);
    } else {
      danger /= timeToImpact;
    }

    double nextCounterClockwiseDanger =
        checkDanger(
            predictedState,
            COUNTERCLOCKWISE_OPTION,
            predictClockwiseOrNot,
            surfableWaveIndex + 1,
            recursionLevels);
    double nextStopDanger =
        checkDanger(
            predictedState,
            STOP_OPTION,
            predictClockwiseOrNot,
            surfableWaveIndex + 1,
            recursionLevels);
    double nextClockwiseDanger =
        checkDanger(
            predictedState,
            CLOCKWISE_OPTION,
            predictClockwiseOrNot,
            surfableWaveIndex + 1,
            recursionLevels);

    danger += Math.min(nextCounterClockwiseDanger, Math.min(nextStopDanger, nextClockwiseDanger));
    //		danger += Math.min(nextCounterClockwiseDanger, nextClockwiseDanger);

    if (surfableWaveIndex == FIRST_WAVE) {
      double predictedDistanceToWaveSource =
          surfWave.sourceLocation.distance(predictedState.location);
      double predictedDistanceToEnemy = ScanLog.enemyLocation().distance(predictedState.location);

      double shorterDistance = Math.min(predictedDistanceToWaveSource, predictedDistanceToEnemy);
      double distancingDangerBase = Math.max(currentDistanceToWaveSource / shorterDistance, .99);
      double distancingDangerExponent =
          shorterDistance > _fearDistance
              ? NORMAL_DISTANCING_EXPONENT
              : FEARFUL_DISTANCING_EXPONENT;

      danger *= Math.pow(distancingDangerBase, distancingDangerExponent);
    }

    return danger;
  }
 @Settable
 public void setGameObjectQueue(GameObjectQueue objects) {
   super.setObjectQueue(objects);
 }
Exemple #22
0
  // ***********************************************************
  // CONSTRUCTOR
  // ***********************************************************
  public GameScene(MapType type) {
    instance = this;

    gameMap = new GameMap(type);

    // Zoom-Camera configuration
    this.setOnAreaTouchTraversalFrontToBack();
    this.mScrollDetector = new SurfaceScrollDetector(this);

    activity = TowerDefenseActivity.getSharedInstance();
    resourceManager = ResourceManager.getInstance();

    if (MultiTouch.isSupported(activity)) {
      this.mPinchZoomDetector = new PinchZoomDetector(this);
    } else {
      this.mPinchZoomDetector = null;
    }

    this.setOnSceneTouchListener(this);
    this.setOnSceneTouchListenerBindingOnActionDownEnabled(true);

    fingerOnSceneCount = 0;
    zooming = false;

    String map = "";

    if (type == MapType.DESERT) map = "tmx/new_desert_path.tmx";
    else if (type == MapType.GRASS) map = "tmx/grass_path.tmx";
    else if (type == MapType.TUNDRA) map = "tmx/tundra_path.tmx";

    try {
      final TMXLoader tmxLoader =
          new TMXLoader(
              activity.getAssets(),
              activity.getEngine().getTextureManager(),
              TextureOptions.BILINEAR_PREMULTIPLYALPHA,
              activity.getVertexBufferObjectManager(),
              new ITMXTilePropertiesListener() {
                @Override
                public void onTMXTileWithPropertiesCreated(
                    final TMXTiledMap pTMXTiledMap,
                    final TMXLayer pTMXLayer,
                    final TMXTile pTMXTile,
                    final TMXProperties<TMXTileProperty> pTMXTileProperties) {}
              });
      this.mTMXTiledMap = tmxLoader.loadFromAsset(map);
    } catch (final TMXLoadException e) {
      Debug.e(e);
    }

    gameMap.setMap(mTMXTiledMap);

    tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
    tmxLayer.setIgnoreUpdate(true);
    this.attachChild(tmxLayer);

    mCamera = activity.getCamera();
    this.mCamera.setBounds(
        0, (mCamera.getHeight() - tmxLayer.getHeight()), tmxLayer.getWidth(), tmxLayer.getHeight());
    this.mCamera.setBoundsEnabled(true);

    float camera_width = activity.getCamera().getWidth();
    float camera_height = activity.getCamera().getHeight();
    if (camera_width / tmxLayer.getHeight() >= camera_height / tmxLayer.getWidth())
      maxZoom = camera_width / (tmxLayer.getHeight() * 2);
    else maxZoom = camera_height / (tmxLayer.getWidth() * 2);

    // 2-dimensional array of tiles
    TMXTile[][] tiles = tmxLayer.getTMXTiles();

    startTile = null;
    endTile = null;
    outer:
    for (int i = 0; i < tiles.length; i++) {
      for (int j = 0; j < tiles[0].length; j++) {

        int[] start = gameMap.getStartTile();
        int[] end = gameMap.getEndTile();

        if (i == start[0] && j == start[1]) {
          startTile = tiles[i][j];
        } else if (i == end[0] && j == end[1]) {
          endTile = tiles[i][j];
          break outer;
        }
      }
    }

    money = 60;
    lives = 20;

    // Initializes the HUD
    panel = new BottomPanel(mCamera, gameMap);
    this.attachChild(panel);

    TowerTile.initializeMap();

    TowerTile turretTile = new TowerTile(resourceManager.getTurretTowerRegion());
    panel.placeTowerAccess(turretTile, 1);

    TowerTile iceTile = new TowerTile(resourceManager.getIceTowerRegion());
    panel.placeTowerAccess(iceTile, 2);

    TowerTile dartTile = new TowerTile(resourceManager.getDartTowerRegion());
    panel.placeTowerAccess(dartTile, 3);

    TowerTile spikeTile = new TowerTile(resourceManager.getSpikeTowerRegion());
    panel.placeTowerAccess(spikeTile, 4);

    TowerTile flameTile = new TowerTile(resourceManager.getFlameTowerRegion());
    panel.placeTowerAccess(flameTile, 5);

    startButton =
        new AnimatedSprite(
            0.0f,
            0.0f,
            resourceManager.getStartButtonRegion(),
            activity.getVertexBufferObjectManager()) {
          @Override
          public boolean onAreaTouched(
              TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {

            if (readyToPressAgain) {
              startCurrentWave();

              readyToPressAgain = false;
              this.registerUpdateHandler(
                  new TimerHandler(
                      1.0f,
                      new ITimerCallback() {

                        @Override
                        public void onTimePassed(TimerHandler pTimerHandler) {
                          readyToPressAgain = true;
                          unregisterUpdateHandler(pTimerHandler);
                        }
                      }));
            }

            panel.detachTowerTextDescription();

            return true;
          }
        };

    startButton.setScale(0.473372781f);
    panel.placeStartButton(startButton);

    // Getting texture regions for submenu items
    SubMenuManager.getDeleteRegion(resourceManager.getDeleteOptionRegion());
    SubMenuManager.getUpgradeRegion(resourceManager.getUpgradeOptionRegion());
    SubMenuManager.getReticalRegion(resourceManager.getTowerSightRegion());

    // Initializing tower array
    towers = new ArrayList<ITower>();

    downCoords = new Vector2();

    blockedTileList = new ArrayList<TMXTile>();

    aStarHelper = new AStarPathHelper(mTMXTiledMap, endTile);
    waveGenerator = new WaveHelper();
    waveCount = 0;
    deadEnemies = 0;

    waveFinished = true;
    initializedNewWave = false;

    // Sets up paths/move modifiers of enemies in the first wave
    initializeNextWave();

    FlameTower.initialize(resourceManager.getFlameParticleRegion());

    Log.i(
        "Info",
        "Dead Enemies: "
            + deadEnemies
            + " Finished Enemies: "
            + aStarHelper.getNumberOfEnemiesFinished()
            + " Current Wave Length: "
            + currentWave.getEnemies().size());

    speedFactor = 0.5f;
    readyToPressAgain = true;

    // collisionDetect = new TimerHandler((float)0.0125/speedFactor, true, new ITimerCallback() {

    collisionDetect =
        new TimerHandler(
            0.025f,
            true,
            new ITimerCallback() {

              @Override
              public void onTimePassed(TimerHandler pTimerHandler) {
                collisionDetect();
              }
            });

    enemyQueues =
        new TimerHandler(
            0.3f,
            true,
            new ITimerCallback() {
              @Override
              public void onTimePassed(TimerHandler pTimerHandler) {
                addEnemiesToTowerQueues();
              }
            });

    disableBackButton = false;
  }