Code Sketch


bixuu
By: Mhalsakant School
Category: Programming
import java.awt.{BasicStroke, BorderLayout, Color, Dimension, Font, GradientPaint, Graphics, Graphics2D, Polygon, RenderingHints}
import java.awt.event.{ActionEvent, ActionListener, KeyAdapter, KeyEvent, MouseAdapter, MouseEvent, WindowAdapter, WindowEvent}
import java.awt.geom.Ellipse2D
import javax.swing.{BorderFactory, JButton, JFrame, JLabel, JPanel, JTextField, SwingConstants, SwingUtilities, Timer, WindowConstants}
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.HashSet

object PhantomEclipse3DRealmOfShadows {
  def main(args: Array[String]): Unit = {
    SwingUtilities.invokeLater(new Runnable {
      override def run(): Unit = {
        val frame = new PhantomEclipse3DFrame()
        frame.setVisible(true)
      }
    })
  }
}

class PhantomEclipse3DFrame extends JFrame("TITANVERSE: AGE OF LEGENDS - PHANTOM ECLIPSE 3D") {
  setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
  setResizable(true)
  setMinimumSize(new Dimension(920, 640))
  setSize(1180, 780)
  setLocationRelativeTo(null)

  var currentGame: PhantomEclipse3DGame = null

  def showLogin(): Unit = {
    val login = new PhantomEclipse3DLogin((playerName: String) => startGame(playerName))
    setContentPane(login)
    revalidate()
    repaint()
  }

  def startGame(playerName: String): Unit = {
    if (currentGame != null) currentGame.stopGame()
    val game = new PhantomEclipse3DGame(playerName, () => {
      if (currentGame != null) currentGame.stopGame()
      currentGame = null
      showLogin()
    })
    currentGame = game
    setContentPane(game)
    revalidate()
    repaint()
    game.startGame()
  }

  addWindowListener(new WindowAdapter {
    override def windowClosing(e: WindowEvent): Unit = {
      if (currentGame != null) currentGame.stopGame()
    }
  })

  showLogin()
}

class PhantomEclipse3DLogin(onStart: String => Unit) extends JPanel {
  setPreferredSize(new Dimension(1100, 740))
  setLayout(null)
  setBackground(new Color(9, 7, 23))

  val titleLabel = new JLabel("PHANTOM ECLIPSE", SwingConstants.CENTER)
  titleLabel.setFont(new Font("Serif", Font.BOLD,  fiftyFont()))
  titleLabel.setForeground(new Color(238, 225, 255))
  titleLabel.setBounds(180, 125, 740, 76)
  add(titleLabel)

  val subtitleLabel = new JLabel("3D-STYLE SHADOW REALMS  |  TITANVERSE EVENT 07", SwingConstants.CENTER)
  subtitleLabel.setFont(new Font("SansSerif", Font.BOLD, 18))
  subtitleLabel.setForeground(new Color(183, 151, 255))
  subtitleLabel.setBounds(180, 205, 740, 34)
  add(subtitleLabel)

  val storyLabel = new JLabel("Explore the cursed kingdom, collect 12 Moon Sigils and break the Eternal Eclipse.", SwingConstants.CENTER)
  storyLabel.setFont(new Font("SansSerif", Font.PLAIN, 16))
  storyLabel.setForeground(new Color(207, 197, 227))
  storyLabel.setBounds(130, 263, 840, 32)
  add(storyLabel)

  val nameLabel = new JLabel("ENTER YOUR EXPLORER NAME", SwingConstants.CENTER)
  nameLabel.setFont(new Font("SansSerif", Font.BOLD, 16))
  nameLabel.setForeground(new Color(230, 214, 255))
  nameLabel.setBounds(350, 348, 400, 30)
  add(nameLabel)

  val nameField = new JTextField("Shadow Explorer")
  nameField.setFont(new Font("SansSerif", Font.PLAIN, 20))
  nameField.setHorizontalAlignment(SwingConstants.CENTER)
  nameField.setBounds(350, 386, 400, 46)
  add(nameField)

  val startButton = new JButton("ENTER THE 3D SHADOW REALM")
  startButton.setFont(new Font("SansSerif", Font.BOLD, 17))
  startButton.setForeground(Color.WHITE)
  startButton.setBackground(new Color(104, 63, 177))
  startButton.setFocusPainted(false)
  startButton.setBounds(350, 458, 400, 54)
  startButton.addActionListener(new ActionListener {
    override def actionPerformed(e: ActionEvent): Unit = {
      val chosen = nameField.getText.trim
      if (chosen.length > 0) onStart(chosen)
    }
  })
  add(startButton)

  val controlsLabel = new JLabel("WASD: MOVE   ARROWS: TURN   SPACE: DASH   F: LANTERN PULSE   E: INTERACT", SwingConstants.CENTER)
  controlsLabel.setFont(new Font("SansSerif", Font.PLAIN, 13))
  controlsLabel.setForeground(new Color(173, 164, 195))
  controlsLabel.setBounds(100, 590, 900, 30)
  add(controlsLabel)

  val safetyLabel = new JLabel("Offline Swing game  |  Close the window to exit  |  No external files required", SwingConstants.CENTER)
  safetyLabel.setFont(new Font("SansSerif", Font.PLAIN, 12))
  safetyLabel.setForeground(new Color(128, 121, 151))
  safetyLabel.setBounds(150, 624, 800, 26)
  add(safetyLabel)

  def fiftyFont(): Int =  fiftySizeValue()
  def fiftySizeValue(): Int =  fiftyConstant()
  def fiftyConstant(): Int = 50

  override def paintComponent(g: Graphics): Unit = {
    super.paintComponent(g)
    val g2 = g.asInstanceOf[Graphics2D]
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
    g2.setPaint(new GradientPaint(0, 0, new Color(10, 7, 31), 0, getHeight, new Color(29, 13, 47)))
    g2.fillRect(0, 0, getWidth, getHeight)
    var i = 0
    while (i < 70) {
      val sx = (i * 137 + 29) % math.max(1, getWidth)
      val sy = (i * 83 + 17) % math.max(1, getHeight)
      val alpha = 70 + (i * 19) % 150
      g2.setColor(new Color(204, 184, 255, alpha))
      g2.fillOval(sx, sy, 2 + (i % 3), 2 + (i % 3))
      i += 1
    }
    g2.setColor(new Color(117, 69, 170, 75))
    g2.fillOval(getWidth / 2 - 190, 20, 380, 380)
  }
}

case class Phantom3DPoint(x: Double, y: Double, z: Double)
case class Phantom3DFace(points: Array[Phantom3DPoint], color: Color, depth: Double)
case class Phantom3DScreenPoint(x: Int, y: Int, depth: Double)

class PhantomEclipse3DGame(playerName: String, onExit: () => Unit) extends JPanel {
  setLayout(new BorderLayout())
  setBackground(Color.BLACK)

  var playerX = 0.0
  var playerZ = 2.0
  var cameraYaw = 0.0
  var playerHealth = 100
  var lanternEnergy = 100
  var dashCooldown = 0
  var pulseTimer = 0
  var shieldTimer = 0
  var eclipseTimer = 0
  var gamePaused = false
  var mapVisible = false
  var winState = false
  var lostState = false
  var animationTime = 0.0
  var currentRealm = 0
  var totalSigils = 0
  var lastMessage = "Find the Moon Sigils. The Eclipse is watching."
  var messageTimer = 180
  val pressedKeys = HashSet[Int]()

  class Sigil(val id: Int, val realm: Int, val x: Double, val z: Double) {
    var collected = false
  }
  class ShadowWisp(var x: Double, var z: Double, val phase: Double) {
    var stunned = 0
  }

  val sigils = ArrayBuffer[Sigil]()
  val wisps = ArrayBuffer[ShadowWisp]()
  val realmNames = Array("MOONLIT VILLAGE", "WHISPERING BLACKWOOD", "ECLIPSE CITADEL")
  val realmStart = Array(0.0, 26.0, 52.0)
  val realmEnd = Array(24.0, 50.0, 78.0)

  def createWorldItems(): Unit = {
    sigils.clear()
    var id = 0
    var realm = 0
    while (realm < 3) {
      val base = realmStart(realm)
      sigils += new Sigil(id, realm, -4.0, base + 6.0); id += 1
      sigils += new Sigil(id, realm, 4.0, base + 10.0); id += 1
      sigils += new Sigil(id, realm, -3.0, base + 15.0); id += 1
      sigils += new Sigil(id, realm, 3.0, base + 19.0); id += 1
      realm += 1
    }
    wisps.clear()
    wisps += new ShadowWisp(6.0, 12.0, 0.4)
    wisps += new ShadowWisp(-6.0, 34.0, 1.7)
    wisps += new ShadowWisp(5.0, 61.0, 2.6)
  }
  createWorldItems()

  val sceneView = new JPanel() {
    setFocusable(true)
    setBackground(new Color(8, 6, 21))
    override def paintComponent(g: Graphics): Unit = {
      super.paintComponent(g)
      drawScene(g.asInstanceOf[Graphics2D], getWidth, getHeight)
    }
  }
  add(sceneView, BorderLayout.CENTER)

  val bottomBar = new JPanel()
  bottomBar.setBackground(new Color(17, 12, 34))
  bottomBar.setBorder(BorderFactory.createEmptyBorder(7, 8, 7, 8))
  def makeButton(label: String, action: () => Unit): JButton = {
    val button = new JButton(label)
    button.setFont(new Font("SansSerif", Font.BOLD, 13))
    button.setForeground(Color.WHITE)
    button.setBackground(new Color(73, 48, 113))
    button.setFocusPainted(false)
    button.setFocusable(false)
    button.addActionListener(new ActionListener {
      override def actionPerformed(e: ActionEvent): Unit = {
        action()
        sceneView.requestFocusInWindow()
        sceneView.repaint()
      }
    })
    bottomBar.add(button)
    button
  }
  makeButton("LANTERN PULSE [F]", () => castLanternPulse())
  makeButton("DASH [SPACE]", () => performDash())
  makeButton("INTERACT [E]", () => interact())
  makeButton("MAP [M]", () => { mapVisible = !mapVisible })
  makeButton("PAUSE [P]", () => { gamePaused = !gamePaused })
  makeButton("EXIT TO LOGIN", () => onExit())
  add(bottomBar, BorderLayout.SOUTH)

  val gameTimer = new Timer(33, new ActionListener {
    override def actionPerformed(e: ActionEvent): Unit = updateGame()
  })

  sceneView.addKeyListener(new KeyAdapter {
    override def keyPressed(e: KeyEvent): Unit = {
      pressedKeys += e.getKeyCode
      if (e.getKeyCode == KeyEvent.VK_SPACE) performDash()
      if (e.getKeyCode == KeyEvent.VK_F) castLanternPulse()
      if (e.getKeyCode == KeyEvent.VK_E) interact()
      if (e.getKeyCode == KeyEvent.VK_M) mapVisible = !mapVisible
      if (e.getKeyCode == KeyEvent.VK_P || e.getKeyCode == KeyEvent.VK_ESCAPE) gamePaused = !gamePaused
      if (e.getKeyCode == KeyEvent.VK_B) onExit()
      sceneView.repaint()
    }
    override def keyReleased(e: KeyEvent): Unit = pressedKeys -= e.getKeyCode
  })

  sceneView.addMouseListener(new MouseAdapter {
    override def mouseClicked(e: MouseEvent): Unit = {
      if (e.getButton == MouseEvent.BUTTON1) castLanternPulse()
    }
  })

  def startGame(): Unit = {
    gameTimer.start()
    sceneView.requestFocusInWindow()
  }

  def stopGame(): Unit = {
    gameTimer.stop()
    pressedKeys.clear()
  }

  def setMessage(text: String): Unit = {
    lastMessage = text
    messageTimer = 160
  }

  def performDash(): Unit = {
    if (!gamePaused && !winState && !lostState && dashCooldown <= 0) {
      val dashDistance = 3.4
      playerX += math.sin(cameraYaw) * dashDistance
      playerZ += math.cos(cameraYaw) * dashDistance
      playerX = math.max(-15.0, math.min(15.0, playerX))
      playerZ = math.max(1.0, math.min(79.0, playerZ))
      dashCooldown = 85
      setMessage("MOON DASH! You slipped through the shadow mist.")
    }
  }

  def castLanternPulse(): Unit = {
    if (!gamePaused && !winState && !lostState && lanternEnergy >= 12) {
      lanternEnergy -= 12
      pulseTimer = 22
      var hit = false
      var i = 0
      while (i < wisps.length) {
        val w = wisps(i)
        val dx = w.x - playerX
        val dz = w.z - playerZ
        val distance = math.sqrt(dx * dx + dz * dz)
        if (distance < 11.0 && math.abs(math.atan2(dx, dz) - cameraYaw) < 1.0) {
          w.stunned = 115
          hit = true
        }
        i += 1
      }
      if (hit) setMessage("LANTERN PULSE! Shadow Wisps are stunned.")
      else setMessage("Lantern Pulse released. Keep exploring!")
    } else if (lanternEnergy < 12) {
      setMessage("Not enough lantern energy. Collect moonlight motes.")
    }
  }

  def interact(): Unit = {
    if (gamePaused || winState || lostState) return
    var nearest: Sigil = null
    var nearestDistance = 1000.0
    var i = 0
    while (i < sigils.length) {
      val s = sigils(i)
      if (!s.collected && s.realm == currentRealm) {
        val dx = s.x - playerX
        val dz = s.z - playerZ
        val d = math.sqrt(dx * dx + dz * dz)
        if (d < nearestDistance) { nearestDistance = d; nearest = s }
      }
      i += 1
    }
    if (nearest != null && nearestDistance < 3.6) {
      nearest.collected = true
      totalSigils += 1
      lanternEnergy = math.min(100, lanternEnergy + 14)
      setMessage("MOON SIGIL COLLECTED! " + totalSigils + "/12")
      return
    }
    val gateZ = realmEnd(currentRealm) - 1.0
    val gateDistance = math.sqrt(playerX * playerX + (gateZ - playerZ) * (gateZ - playerZ))
    if (gateDistance < 5.5) {
      if (countRealmSigils(currentRealm) >= 4) {
        if (currentRealm < 2) {
          currentRealm += 1
          playerZ = realmStart(currentRealm) + 1.5
          playerX = 0.0
          setMessage("REALM UNLOCKED: " + realmNames(currentRealm))
        } else if (totalSigils >= 12) {
          winState = true
          setMessage("ETERNAL ECLIPSE BROKEN! YOU RESTORED THE MOON REALMS!")
        }
      } else {
        setMessage("The gate is sealed. Find all 4 Moon Sigils in this realm.")
      }
    } else {
      setMessage("Move close to a glowing Moon Sigil or the Realm Gate, then press E.")
    }
  }

  def countRealmSigils(realm: Int): Int = {
    var count = 0
    var i = 0
    while (i < sigils.length) {
      if (sigils(i).realm == realm && sigils(i).collected) count += 1
      i += 1
    }
    count
  }

  def updateGame(): Unit = {
    if (!gamePaused && !winState && !lostState) {
      animationTime += 0.04
      eclipseTimer += 1
      if (dashCooldown > 0) dashCooldown -= 1
      if (pulseTimer > 0) pulseTimer -= 1
      if (shieldTimer > 0) shieldTimer -= 1
      if (lanternEnergy < 100 && eclipseTimer % 4 == 0) lanternEnergy = math.min(100, lanternEnergy + 1)
      if (messageTimer > 0) messageTimer -= 1

      if (pressedKeys.contains(KeyEvent.VK_LEFT)) cameraYaw -= 0.045
      if (pressedKeys.contains(KeyEvent.VK_RIGHT)) cameraYaw += 0.045
      var forward = 0.0
      var side = 0.0
      if (pressedKeys.contains(KeyEvent.VK_W) || pressedKeys.contains(KeyEvent.VK_UP)) forward += 0.17
      if (pressedKeys.contains(KeyEvent.VK_S) || pressedKeys.contains(KeyEvent.VK_DOWN)) forward -= 0.14
      if (pressedKeys.contains(KeyEvent.VK_A)) side -= 0.15
      if (pressedKeys.contains(KeyEvent.VK_D)) side += 0.15
      val speedBoost = if (shieldTimer > 0) 1.0 else 1.0
      playerX += (math.sin(cameraYaw) * forward + math.cos(cameraYaw) * side) * speedBoost
      playerZ += (math.cos(cameraYaw) * forward - math.sin(cameraYaw) * side) * speedBoost
      playerX = math.max(-17.0, math.min(17.0, playerX))
      playerZ = math.max(1.0, math.min(79.0, playerZ))

      var i = 0
      while (i < wisps.length) {
        val w = wisps(i)
        if (w.stunned > 0) w.stunned -= 1
        else {
          val dx = playerX - w.x
          val dz = playerZ - w.z
          val d = math.sqrt(dx * dx + dz * dz)
          if (d > 1.8 && d < 20.0) {
            w.x += (dx / math.max(0.1, d)) * 0.035
            w.z += (dz / math.max(0.1, d)) * 0.035
          }
          if (d < 1.5 && shieldTimer <= 0 && eclipseTimer % 50 == 0) {
            playerHealth = math.max(0, playerHealth - 8)
            setMessage("A Shadow Wisp touched you. Find a safe path!")
            if (playerHealth <= 0) lostState = true
          }
        }
        i += 1
      }
    }
    sceneView.repaint()
  }

  def forwardDepth(point: Phantom3DPoint): Double = {
    val dx = point.x - playerX
    val dz = point.z - playerZ
    dx * math.sin(cameraYaw) + dz * math.cos(cameraYaw)
  }

  def sideDepth(point: Phantom3DPoint): Double = {
    val dx = point.x - playerX
    val dz = point.z - playerZ
    dx * math.cos(cameraYaw) - dz * math.sin(cameraYaw)
  }

  def shadeColor(color: Color, amount: Double): Color = {
    val factor = math.max(0.25, math.min(1.35, amount))
    new Color(
      math.max(0, math.min(255, (color.getRed * factor).toInt)),
      math.max(0, math.min(255, (color.getGreen * factor).toInt)),
      math.max(0, math.min(255, (color.getBlue * factor).toInt))
    )
  }

  def addFace(faces: ArrayBuffer[Phantom3DFace], points: Array[Phantom3DPoint], color: Color): Unit = {
    var total = 0.0
    var i = 0
    while (i < points.length) { total += forwardDepth(points(i)); i += 1 }
    faces += Phantom3DFace(points, color, total / math.max(1, points.length))
  }

  def addCube(faces: ArrayBuffer[Phantom3DFace], x: Double, y: Double, z: Double, width: Double, height: Double, depth: Double, base: Color): Unit = {
    val x0 = x - width / 2.0; val x1 = x + width / 2.0
    val y0 = y - height / 2.0; val y1 = y + height / 2.0
    val z0 = z - depth / 2.0; val z1 = z + depth / 2.0
    val p = Array(
      Phantom3DPoint(x0, y0, z0), Phantom3DPoint(x1, y0, z0), Phantom3DPoint(x1, y1, z0), Phantom3DPoint(x0, y1, z0),
      Phantom3DPoint(x0, y0, z1), Phantom3DPoint(x1, y0, z1), Phantom3DPoint(x1, y1, z1), Phantom3DPoint(x0, y1, z1)
    )
    addFace(faces, Array(p(0), p(1), p(2), p(3)), shadeColor(base, 0.56))
    addFace(faces, Array(p(4), p(5), p(6), p(7)), shadeColor(base, 1.15))
    addFace(faces, Array(p(0), p(4), p(7), p(3)), shadeColor(base, 0.72))
    addFace(faces, Array(p(1), p(5), p(6), p(2)), shadeColor(base, 0.88))
    addFace(faces, Array(p(3), p(2), p(6), p(7)), shadeColor(base, 1.30))
    addFace(faces, Array(p(0), p(1), p(5), p(4)), shadeColor(base, 0.42))
  }

  def addPyramid(faces: ArrayBuffer[Phantom3DFace], x: Double, y: Double, z: Double, size: Double, height: Double, color: Color): Unit = {
    val a = Phantom3DPoint(x - size / 2.0, y, z - size / 2.0)
    val b = Phantom3DPoint(x + size / 2.0, y, z - size / 2.0)
    val c = Phantom3DPoint(x + size / 2.0, y, z + size / 2.0)
    val d = Phantom3DPoint(x - size / 2.0, y, z + size / 2.0)
    val top = Phantom3DPoint(x, y + height, z)
    addFace(faces, Array(a, b, top), shadeColor(color, 0.85))
    addFace(faces, Array(b, c, top), shadeColor(color, 1.15))
    addFace(faces, Array(c, d, top), shadeColor(color, 0.72))
    addFace(faces, Array(d, a, top), shadeColor(color, 1.0))
    addFace(faces, Array(a, d, c, b), shadeColor(color, 0.45))
  }

  def addOctahedron(faces: ArrayBuffer[Phantom3DFace], x: Double, y: Double, z: Double, size: Double, color: Color): Unit = {
    val top = Phantom3DPoint(x, y + size, z)
    val bottom = Phantom3DPoint(x, y - size, z)
    val a = Phantom3DPoint(x - size, y, z)
    val b = Phantom3DPoint(x, y, z - size)
    val c = Phantom3DPoint(x + size, y, z)
    val d = Phantom3DPoint(x, y, z + size)
    addFace(faces, Array(top, a, b), shadeColor(color, 1.25))
    addFace(faces, Array(top, b, c), shadeColor(color, 0.95))
    addFace(faces, Array(top, c, d), shadeColor(color, 1.35))
    addFace(faces, Array(top, d, a), shadeColor(color, 0.85))
    addFace(faces, Array(bottom, b, a), shadeColor(color, 0.55))
    addFace(faces, Array(bottom, c, b), shadeColor(color, 0.65))
    addFace(faces, Array(bottom, d, c), shadeColor(color, 0.60))
    addFace(faces, Array(bottom, a, d), shadeColor(color, 0.50))
  }

  def addPortal(faces: ArrayBuffer[Phantom3DFace], x: Double, y: Double, z: Double, tint: Color): Unit = {
    var i = 0
    while (i < 20) {
      val angle = i.toDouble * math.Pi * 2.0 / 20.0
      val px = x + math.cos(angle) * 2.15
      val py = y + math.sin(angle) * 2.75
      addCube(faces, px, py, z, 0.48, 0.48, 0.42, tint)
      i += 1
    }
    addFace(faces, Array(
      Phantom3DPoint(x - 1.9, y - 2.4, z - 0.06),
      Phantom3DPoint(x + 1.9, y - 2.4, z - 0.06),
      Phantom3DPoint(x + 1.9, y + 2.4, z - 0.06),
      Phantom3DPoint(x - 1.9, y + 2.4, z - 0.06)
    ), new Color(tint.getRed, tint.getGreen, tint.getBlue, 92))
  }

  def addTree(faces: ArrayBuffer[Phantom3DFace], x: Double, z: Double, scale: Double, leaf: Color): Unit = {
    addCube(faces, x, 1.5 * scale, z, 0.8 * scale, 3.0 * scale, 0.8 * scale, new Color(54, 39, 51))
    addPyramid(faces, x, 2.1 * scale, z, 3.6 * scale, 4.8 * scale, leaf)
    addPyramid(faces, x, 4.0 * scale, z, 2.8 * scale, 4.0 * scale, shadeColor(leaf, 1.15))
  }

  def addCastle(faces: ArrayBuffer[Phantom3DFace], x: Double, z: Double): Unit = {
    val stone = new Color(56, 45, 79)
    addCube(faces, x, 3.0, z, 10.0, 6.0, 3.0, stone)
    addCube(faces, x - 4.4, 5.0, z + 0.6, 2.5, 10.0, 2.6, new Color(74, 54, 101))
    addCube(faces, x + 4.4, 5.0, z + 0.6, 2.5, 10.0, 2.6, new Color(74, 54, 101))
    addPyramid(faces, x - 4.4, 10.0, z + 0.6, 3.0, 4.0, new Color(46, 32, 68))
    addPyramid(faces, x + 4.4, 10.0, z + 0.6, 3.0, 4.0, new Color(46, 32, 68))
    addPyramid(faces, x, 6.0, z, 10.5, 5.0, new Color(42, 29, 63))
  }

  def buildWorldFaces(): ArrayBuffer[Phantom3DFace] = {
    val faces = ArrayBuffer[Phantom3DFace]()
    var z = 1.0
    while (z < 84.0) {
      val groundColor = if ((z.toInt / 5) % 2 == 0) new Color(25, 22, 38) else new Color(30, 24, 43)
      addFace(faces, Array(
        Phantom3DPoint(-24.0, 0.0, z), Phantom3DPoint(24.0, 0.0, z),
        Phantom3DPoint(24.0, 0.0, z + 5.0), Phantom3DPoint(-24.0, 0.0, z + 5.0)
      ), groundColor)
      addFace(faces, Array(
        Phantom3DPoint(-1.8, 0.025, z), Phantom3DPoint(1.8, 0.025, z),
        Phantom3DPoint(1.8, 0.025, z + 5.0), Phantom3DPoint(-1.8, 0.025, z + 5.0)
      ), new Color(64, 47, 84))
      z += 5.0
    }

    val treeColors = Array(new Color(43, 73, 63), new Color(53, 43, 76), new Color(73, 44, 76))
    var i = 0
    while (i < 12) {
      val tz = 5.0 + i * 6.0
      addTree(faces, -10.0 - (i % 3), tz, 0.8 + (i % 3) * 0.12, treeColors(i % 3))
      addTree(faces, 10.0 + (i % 2), tz + 2.0, 0.9 + (i % 2) * 0.15, treeColors((i + 1) % 3))
      i += 1
    }
    addCastle(faces, 0.0, 72.0)
    addCastle(faces, -12.0, 44.0)
    addCastle(faces, 12.0, 19.0)

    addPortal(faces, 0.0, 3.4, 23.0, new Color(111, 83, 216))
    addPortal(faces, 0.0, 3.4, 49.0, new Color(61, 161, 185))
    addPortal(faces, 0.0, 3.4, 77.0, new Color(205, 126, 255))

    var s = 0
    while (s < sigils.length) {
      val sigil = sigils(s)
      if (!sigil.collected) {
        val bob = math.sin(animationTime * 2.0 + sigil.id) * 0.22
        val color = if (sigil.realm == 0) new Color(193, 160, 255) else if (sigil.realm == 1) new Color(111, 229, 226) else new Color(255, 177, 220)
        addOctahedron(faces, sigil.x, 1.7 + bob, sigil.z, 0.66, color)
      }
      s += 1
    }

    var w = 0
    while (w < wisps.length) {
      val ghost = wisps(w)
      val bob = math.sin(animationTime * 3.0 + ghost.phase) * 0.35
      val ghostColor = if (ghost.stunned > 0) new Color(122, 222, 255) else new Color(172, 107, 233)
      addOctahedron(faces, ghost.x, 1.7 + bob, ghost.z, 0.9, ghostColor)
      addOctahedron(faces, ghost.x, 2.6 + bob, ghost.z, 0.45, shadeColor(ghostColor, 1.2))
      w += 1
    }
    faces
  }

  def projectPoint(point: Phantom3DPoint, width: Int, height: Int): Phantom3DScreenPoint = {
    val forward = math.max(0.18, forwardDepth(point))
    val side = sideDepth(point)
    val focal = math.min(width, height).toDouble * 0.92
    val sx = width.toDouble / 2.0 + (side * focal / forward)
    val sy = height.toDouble * 0.48 - ((point.y - 1.62) * focal / forward)
    Phantom3DScreenPoint(sx.toInt, sy.toInt, forward.toInt)
  }

  def renderFace(g2: Graphics2D, face: Phantom3DFace, width: Int, height: Int): Unit = {
    val xs = new Array[Int](face.points.length)
    val ys = new Array[Int](face.points.length)
    var i = 0
    var visible = true
    while (i < face.points.length) {
      if (forwardDepth(face.points(i)) <= 0.18) visible = false
      val p = projectPoint(face.points(i), width, height)
      xs(i) = p.x
      ys(i) = p.y
      i += 1
    }
    if (visible) {
      val poly = new Polygon(xs, ys, xs.length)
      g2.setColor(face.color)
      g2.fillPolygon(poly)
      g2.setColor(new Color(9, 6, 19, 115))
      g2.setStroke(new BasicStroke(1.0f))
      g2.drawPolygon(poly)
    }
  }

  def drawBackground(g2: Graphics2D, width: Int, height: Int): Unit = {
    g2.setPaint(new GradientPaint(0, 0, new Color(17, 11, 42), 0, height, new Color(9, 7, 20)))
    g2.fillRect(0, 0, width, height)
    val moonX = width * 0.77
    val moonY = height * 0.19
    val moonSize = math.max(55, height / 9)
    g2.setColor(new Color(149, 112, 210, 24))
    g2.fill(new Ellipse2D.Double(moonX - moonSize * 0.8, moonY - moonSize * 0.8, moonSize * 2.6, moonSize * 2.6))
    g2.setColor(new Color(217, 198, 255))
    g2.fillOval(moonX.toInt - moonSize / 2, moonY.toInt - moonSize / 2, moonSize, moonSize)
    g2.setColor(new Color(91, 65, 135, 210))
    g2.fillOval(moonX.toInt - moonSize / 2 + 17, moonY.toInt - moonSize / 2 - 4, moonSize, moonSize)
    var i = 0
    while (i < 90) {
      val sx = (i * 149 + 31) % math.max(1, width)
      val sy = (i * 71 + 12) % math.max(1, (height * 0.48).toInt)
      val alpha = 65 + (i * 23) % 170
      g2.setColor(new Color(218, 201, 255, alpha))
      g2.fillOval(sx, sy, 1 + i % 3, 1 + i % 3)
      i += 1
    }
    g2.setColor(new Color(6, 4, 15, 70))
    g2.fillRect(0, (height * 0.43).toInt, width, (height * 0.57).toInt)
  }

  def drawHud(g2: Graphics2D, width: Int, height: Int): Unit = {
    g2.setFont(new Font("SansSerif", Font.BOLD, 15))
    g2.setColor(new Color(14, 10, 29, 205))
    g2.fillRoundRect(16, 14, 370, 100, 16, 16)
    g2.setColor(new Color(238, 224, 255))
    g2.drawString("EXPLORER: " + playerName, 30, 38)
    g2.drawString("REALM: " + realmNames(currentRealm), 30, 61)
    g2.drawString("MOON SIGILS: " + totalSigils + " / 12", 30, 84)
    g2.setColor(new Color(33, 25, 51, 210))
    g2.fillRoundRect(30, 91, 220, 12, 8, 8)
    g2.setColor(new Color(180, 115, 255))
    g2.fillRoundRect(30, 91, (220.0 * playerHealth / 100.0).toInt, 12, 8, 8)
    g2.setColor(new Color(238, 224, 255))
    g2.drawString("LANTERN " + lanternEnergy + "%", 265, 101)

    g2.setColor(new Color(12, 9, 25, 180))
    g2.fillRoundRect(width - 250, 14, 232, 65, 14, 14)
    g2.setColor(new Color(223, 210, 255))
    g2.drawString("WASD MOVE  |  ARROWS TURN", width - 235, 39)
    g2.drawString("SPACE DASH  |  F PULSE  |  E USE", width - 235, 62)

    val cx = width / 2
    val cy = height / 2
    g2.setColor(new Color(232, 218, 255, 190))
    g2.setStroke(new BasicStroke(2.0f))
    g2.drawLine(cx - 9, cy, cx - 3, cy)
    g2.drawLine(cx + 3, cy, cx + 9, cy)
    g2.drawLine(cx, cy - 9, cx, cy - 3)
    g2.drawLine(cx, cy + 3, cx, cy + 9)

    if (pulseTimer > 0) {
      g2.setColor(new Color(157, 104, 255, 65))
      val radius = (width.min(height) * (0.20 + pulseTimer / 110.0)).toInt
      g2.fillOval(cx - radius, cy - radius, radius * 2, radius * 2)
    }

    if (messageTimer > 0) {
      g2.setFont(new Font("SansSerif", Font.BOLD, 16))
      g2.setColor(new Color(12, 8, 27, 195))
      g2.fillRoundRect(width / 2 - 330, height - 84, 660, 38, 12, 12)
      g2.setColor(new Color(243, 225, 255))
      g2.drawString(lastMessage, width / 2 - 310, height - 59)
    }

    if (mapVisible) drawMiniMap(g2, width, height)
    if (gamePaused || winState || lostState) drawOverlay(g2, width, height)
  }

  def drawMiniMap(g2: Graphics2D, width: Int, height: Int): Unit = {
    val x = width - 192
    val y = height - 190
    g2.setColor(new Color(12, 8, 25, 220))
    g2.fillRoundRect(x, y, 170, 166, 12, 12)
    g2.setColor(new Color(215, 199, 255))
    g2.setFont(new Font("SansSerif", Font.BOLD, 13))
    g2.drawString("SHADOW MAP", x + 16, y + 20)
    g2.setColor(new Color(69, 52, 93))
    g2.fillRoundRect(x + 75, y + 32, 22, 120, 8, 8)
    var i = 0
    while (i < sigils.length) {
      val s = sigils(i)
      if (!s.collected) {
        val px = x + 86 + (s.x * 2.2).toInt
        val py = y + 38 + (s.z * 1.35).toInt
        g2.setColor(new Color(213, 177, 255))
        g2.fillOval(px, py, 5, 5)
      }
      i += 1
    }
    val playerMapY = y + 38 + (playerZ * 1.35).toInt
    val playerMapX = x + 86 + (playerX * 2.2).toInt
    g2.setColor(new Color(116, 255, 215))
    g2.fillOval(playerMapX - 4, playerMapY - 4, 9, 9)
  }

  def drawOverlay(g2: Graphics2D, width: Int, height: Int): Unit = {
    g2.setColor(new Color(5, 3, 12, 210))
    g2.fillRect(0, 0, width, height)
    g2.setColor(new Color(239, 224, 255))
    g2.setFont(new Font("Serif", Font.BOLD, 42))
    val title = if (winState) "ETERNAL ECLIPSE BROKEN" else if (lostState) "THE SHADOWS HAVE WON" else "REALM PAUSED"
    val fm = g2.getFontMetrics
    g2.drawString(title, (width - fm.stringWidth(title)) / 2, height / 2 - 18)
    g2.setFont(new Font("SansSerif", Font.PLAIN, 18))
    val subtitle = if (winState) "The Moon Realms are free. Thank you, " + playerName + "!" else if (lostState) "Press R to restart your expedition or B to return." else "Press P or ESC to continue."
    g2.drawString(subtitle, (width - g2.getFontMetrics.stringWidth(subtitle)) / 2, height / 2 + 24)
  }

  def drawScene(g2: Graphics2D, width: Int, height: Int): Unit = {
    if (width <= 0 || height <= 0) return
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
    drawBackground(g2, width, height)
    val faces = buildWorldFaces()
    val sorted = faces.sortBy((face: Phantom3DFace) => -face.depth)
    var i = 0
    while (i < sorted.length) {
      renderFace(g2, sorted(i), width, height)
      i += 1
    }
    g2.setPaint(new GradientPaint(0, (height * 0.38).toInt, new Color(34, 19, 58, 0), 0, height, new Color(8, 5, 17, 115)))
    g2.fillRect(0, (height * 0.38).toInt, width, (height * 0.62).toInt)
    drawFirstPersonLantern(g2, width, height)
    drawHud(g2, width, height)
  }

  def drawFirstPersonLantern(g2: Graphics2D, width: Int, height: Int): Unit = {
    val x = 44
    val y = height - 125
    g2.setColor(new Color(35, 27, 45, 220))
    g2.fillRoundRect(x + 16, y + 25, 50, 65, 10, 10)
    g2.setColor(new Color(190, 142, 255, 210))
    g2.setStroke(new BasicStroke(4.0f))
    g2.drawRoundRect(x + 22, y + 31, 38, 50, 8, 8)
    g2.setColor(new Color(222, 189, 255, 190))
    g2.fillOval(x + 28, y + 40, 26, 30)
    g2.setColor(new Color(164, 102, 255, 45))
    g2.fillOval(x - 8, y + 5, 100, 100)
  }
}

PhantomEclipse3DRealmOfShadows.main(Array[String]())