Workshop › Scorched Earth-style Artillery › Step 19 of 23

The computer aims

What we are doing

The computer aims by imagining. It tries about 17 angles × 17 powers = almost 300 shots in its head, using the same fly as real shells (with the real wind), and remembers the one that lands closest to you. Then it misses a little on purpose, or it would never miss.

```js
// The computer tries many shots in its head, picks the one landing closest to you, then misses a little.
function computerAim() {
  const me = tanks[1]
  let best = null
  for (let angle = -Math.PI + 0.2; angle < -Math.PI / 2; angle += 0.03) {
    for (let power = 4; power <= MAX_POWER; power += 0.5) {
      const s = { x: me.x + Math.cos(angle) * 14, y: me.y - 8 + Math.sin(angle) * 14, vx: Math.cos(angle) * power, vy: Math.sin(angle) * power }
      let hit = null
      for (let i = 0; i < 400 && !hit; i++) hit = fly(s)
      if (hit === 'away') continue
      const miss = Math.abs(s.x - tanks[0].x)
      if (!best || miss < best.miss) best = { miss, angle, power }
    }
  }
  me.angle = best.angle + (Math.random() - 0.5) * 0.08
  me.power = Math.min(MAX_POWER, best.power + (Math.random() - 0.5) * 0.8)
}

    computerAim()
```

What it means

Your turn

  1. Above update, write computerAim with its comment.
  2. In update, aim before the computer fires.

Skills: Velocity and gravity, Loops

All steps

  1. The ground
  2. Hills
  3. Two tanks
  4. The barrel
  5. The game loop
  6. Aim
  7. Angle and power
  8. Fire!
  9. Flight
  10. Boom
  11. Craters
  12. Falling tanks
  13. Damage
  14. Taking turns
  15. The computer's shot
  16. Hitting a tank
  17. Win or lose
  18. Wind
  19. The computer aims
  20. Aim with the mouse
  21. Drag and let go
  22. The atan2 trap
  23. Build it yourself: a trail