Code Sketch


yoi car
By: Mhalsakant School
Category: Programming
import javax.swing._
import java.awt._
import java.awt.event._
import java.awt.geom._
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.HashSet
import scala.util.Random

// ============================================================
// NEON RUSH 360 - FREE DRIVE EDITION
// Kojo Scala script using Java Swing + Java2D.
// Free steering in any direction; no fixed lanes.
// Visual style: shaded 2.5D / pseudo-3D overhead racing arena.
// ============================================================

SwingUtilities.invokeLater(new Runnable {
  override def run(): Unit = {

    // -------------------- WINDOW --------------------
    val frame = new JFrame("NEON RUSH 360 - Free Drive")
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
    frame.setSize(1180, 790)
    frame.setMinimumSize(new Dimension(900, 650))
    frame.setLocationRelativeTo(null)

    // -------------------- GAME STATE --------------------
    val random = new Random()
    val pressedKeys = HashSet[Int]()

    case class Pickup(var x: Double, var y: Double, kind: String, var active: Boolean)
    case class Rival(var angle: Double, angularSpeed: Double, color: Color)
    case class Cone(x: Double, y: Double)

    val pickups = ArrayBuffer[Pickup]()
    val rivals = ArrayBuffer[Rival]()
    val cones = ArrayBuffer[Cone]()

    var gameState = "menu" // menu, playing, paused, over
    var carX = -95.0
    var carY = -485.0
    var carHeading = 0.0 // radians; 0 = right, PI/2 = down
    var carSpeed = 0.0
    var score = 0
    var coins = 0
    var lives = 3
    var nitro = 100.0
    var boosting = false
    var distance = 0.0
    var level = 1
    var offRoad = false
    var invulnerable = 0.0
    var elapsed = 0.0
    var lastTime = System.nanoTime()
    var bestScore = 0
    var shake = 0.0

    // -------------------- COLORS --------------------
    val grassDark = new Color(8, 45, 42)
    val grassLight = new Color(17, 91, 70)
    val roadDark = new Color(25, 31, 47)
    val cyan = new Color(35, 225, 255)
    val pink = new Color(255, 55, 170)
    val gold = new Color(255, 195, 55)
    val whiteBlue = new Color(220, 245, 255)

    // -------------------- SAVE BEST SCORE --------------------
    val bestFile = new java.io.File(
      System.getProperty("user.home"), ".neon_rush_360_best.txt"
    )

    try {
      if (bestFile.exists()) {
        val source = scala.io.Source.fromFile(bestFile, "UTF-8")
        try bestScore = source.mkString.trim.toInt
        finally source.close()
      }
    } catch {
      case _: Exception => bestScore = 0
    }

    def saveBestScore(): Unit = {
      try {
        val writer = new java.io.PrintWriter(bestFile, "UTF-8")
        try writer.print(bestScore)
        finally writer.close()
      } catch {
        case _: Exception => ()
      }
    }

    // -------------------- WORLD / TRACK GEOMETRY --------------------
    val outerTrack = new Ellipse2D.Double(-1120.0, -690.0, 2240.0, 1380.0)
    val innerTrack = new Ellipse2D.Double(-600.0, -295.0, 1200.0, 590.0)
    val centerLine = new Ellipse2D.Double(-860.0, -492.0, 1720.0, 984.0)

    val roadArea = new Area(outerTrack)
    roadArea.subtract(new Area(innerTrack))

    def clamp(v: Double, lo: Double, hi: Double): Double =
      math.max(lo, math.min(hi, v))

    def distanceBetween(x1: Double, y1: Double, x2: Double, y2: Double): Double = {
      val dx = x1 - x2
      val dy = y1 - y2
      math.sqrt(dx * dx + dy * dy)
    }

    def onRoad(x: Double, y: Double): Boolean = {
      val outer = (x * x) / (1120.0 * 1120.0) + (y * y) / (690.0 * 690.0)
      val inner = (x * x) / (600.0 * 600.0) + (y * y) / (295.0 * 295.0)
      outer <= 1.0 && inner >= 1.0
    }

    def setQuality(g: Graphics2D): Unit = {
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
      g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC)
      g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
    }

    // -------------------- WORLD OBJECTS --------------------
    def initializeWorld(): Unit = {
      pickups.clear()
      rivals.clear()
      cones.clear()

      var i = 0
      while (i < 22) {
        val a = -Math.PI / 2.0 + i * Math.PI * 2.0 / 22.0
        val radiusX = 860.0 + (if (i % 3 == 0) 48.0 else -25.0)
        val radiusY = 492.0 + (if (i % 4 == 0) 26.0 else -12.0)
        val kind = if (i % 5 == 0) "nitro" else "coin"
        pickups += Pickup(math.cos(a) * radiusX, math.sin(a) * radiusY, kind, true)
        i += 1
      }

      // Moving rival cars use continuous positions on the oval track.
      rivals += Rival(-0.80, 0.34, new Color(245, 65, 105))
      rivals += Rival(0.22, 0.27, new Color(155, 95, 255))
      rivals += Rival(1.65, 0.31, new Color(255, 145, 45))
      rivals += Rival(2.65, 0.24, new Color(55, 205, 160))

      // Road cones / barriers at selected track positions.
      val coneAngles = Array(-0.35, 0.60, 1.40, 2.35, 3.05, 4.00, 4.75, 5.50)
      coneAngles.foreach { a =>
        cones += Cone(math.cos(a) * 865.0, math.sin(a) * 497.0)
      }
    }

    initializeWorld()

    // -------------------- DRAWING: BACKGROUND --------------------
    def drawScreenBackground(g: Graphics2D, w: Int, h: Int): Unit = {
      g.setPaint(new GradientPaint(0, 0, new Color(5, 13, 31), 0, h, new Color(16, 39, 58)))
      g.fillRect(0, 0, w, h)

      val glow = new RadialGradientPaint(
        new Point2D.Double(w * 0.50, h * 0.55),
        (w * 0.62).toFloat,
        Array[Float](0.0f, 0.55f, 1.0f),
        Array[Color](new Color(25, 165, 165, 55), new Color(25, 70, 130, 28), new Color(0, 0, 0, 0))
      )
      g.setPaint(glow)
      g.fillRect(0, 0, w, h)
    }

    // -------------------- DRAWING: WORLD --------------------
    def drawWorld(g: Graphics2D): Unit = {
      // Large grass field.
      g.setPaint(new GradientPaint(-900.0f, -700.0f, grassLight, 900.0f, 850.0f, grassDark))
      g.fill(new Rectangle2D.Double(-1900.0, -1450.0, 3800.0, 2900.0))

      // Subtle grass grid / surface texture.
      g.setStroke(new BasicStroke(1.0f))
      var gx = -1800
      while (gx <= 1800) {
        g.setColor(new Color(150, 255, 220, 12))
        g.drawLine(gx, -1400, gx, 1400)
        gx += 100
      }
      var gy = -1400
      while (gy <= 1400) {
        g.setColor(new Color(150, 255, 220, 10))
        g.drawLine(-1800, gy, 1800, gy)
        gy += 100
      }

      // Stadium structures around the race arena.
      var i = 0
      while (i < 28) {
        val a = i * Math.PI * 2.0 / 28.0
        val sx = math.cos(a) * 1280.0
        val sy = math.sin(a) * 790.0
        val post = new RoundRectangle2D.Double(sx - 21.0, sy - 21.0, 42.0, 42.0, 10.0, 10.0)
        g.setColor(new Color(0, 0, 0, 75))
        g.fill(new Ellipse2D.Double(sx - 25.0, sy + 8.0, 52.0, 26.0))
        g.setPaint(new GradientPaint(sx.toFloat, (sy - 25).toFloat, new Color(90, 130, 155), sx.toFloat, (sy + 25).toFloat, new Color(19, 36, 56)))
        g.fill(post)
        g.setColor(if (i % 2 == 0) new Color(35, 230, 255, 180) else new Color(255, 65, 175, 180))
        g.setStroke(new BasicStroke(3.0f))
        g.draw(post)
        g.setColor(new Color(210, 250, 255, 180))
        g.fill(new Ellipse2D.Double(sx - 5.0, sy - 5.0, 10.0, 10.0))
        i += 1
      }

      // Track shadow.
      g.setColor(new Color(0, 0, 0, 105))
      g.fill(new Ellipse2D.Double(-1145.0, -675.0, 2290.0, 1405.0))

      // Asphalt ring.
      g.setPaint(new GradientPaint(-900.0f, -650.0f, new Color(54, 63, 83), 900.0f, 650.0f, roadDark))
      g.fill(roadArea)

      // Road outer and inner borders.
      g.setStroke(new BasicStroke(12.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND))
      g.setColor(new Color(20, 215, 255, 210))
      g.draw(outerTrack)
      g.setColor(new Color(255, 65, 175, 205))
      g.draw(innerTrack)

      // Road shoulder lines.
      g.setStroke(new BasicStroke(3.0f))
      g.setColor(new Color(225, 250, 255, 95))
      g.draw(new Ellipse2D.Double(-1090.0, -660.0, 2180.0, 1320.0))
      g.draw(new Ellipse2D.Double(-630.0, -325.0, 1260.0, 650.0))

      // Dashed center line follows the whole oval circuit.
      val dash = Array[Float](34.0f, 27.0f)
      val phase = ((elapsed * 95.0) % 61.0).toFloat
      g.setStroke(new BasicStroke(7.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, dash, phase))
      g.setColor(new Color(230, 245, 255, 175))
      g.draw(centerLine)

      // Start / finish line across the track at the top.
      var sx = -175
      while (sx < 175) {
        val cell = new Rectangle2D.Double(sx.toDouble, -516.0, 25.0, 48.0)
        g.setColor(if (((sx + 175) / 25) % 2 == 0) Color.WHITE else new Color(12, 20, 35))
        g.fill(cell)
        sx += 25
      }

      // Neon light streaks at track edge.
      g.setStroke(new BasicStroke(2.0f))
      var j = 0
      while (j < 36) {
        val a = j * Math.PI * 2.0 / 36.0
        val x1 = math.cos(a) * 1180.0
        val y1 = math.sin(a) * 720.0
        val x2 = math.cos(a) * 1230.0
        val y2 = math.sin(a) * 750.0
        g.setColor(if (j % 2 == 0) new Color(40, 230, 255, 90) else new Color(255, 55, 180, 90))
        g.draw(new Line2D.Double(x1, y1, x2, y2))
        j += 1
      }
    }

    // -------------------- DRAWING: 3D-STYLE CAR --------------------
    // The car body points upward by default, then rotates to any angle.
    def drawCar(g: Graphics2D, x: Double, y: Double, heading: Double, bodyColor: Color, isPlayer: Boolean, scale: Double): Unit = {
      val cg = g.create().asInstanceOf[Graphics2D]
      cg.translate(x, y)
      cg.rotate(heading + Math.PI / 2.0)
      cg.scale(scale, scale)

      // Soft ground shadow.
      cg.setColor(new Color(0, 0, 0, 125))
      cg.fill(new Ellipse2D.Double(-38.0, -8.0, 76.0, 130.0))

      // Underbody glow.
      val glowColor = if (isPlayer) cyan else bodyColor
      cg.setColor(new Color(glowColor.getRed, glowColor.getGreen, glowColor.getBlue, 65))
      cg.fill(new Ellipse2D.Double(-36.0, -27.0, 72.0, 112.0))

      // Wheels.
      cg.setColor(new Color(3, 5, 10))
      cg.fillRoundRect(-32, -35, 13, 34, 7, 7)
      cg.fillRoundRect(19, -35, 13, 34, 7, 7)
      cg.fillRoundRect(-32, 30, 13, 34, 7, 7)
      cg.fillRoundRect(19, 30, 13, 34, 7, 7)
      cg.setColor(new Color(115, 135, 155))
      cg.fillRoundRect(-29, -29, 7, 23, 4, 4)
      cg.fillRoundRect(22, -29, 7, 23, 4, 4)
      cg.fillRoundRect(-29, 36, 7, 22, 4, 4)
      cg.fillRoundRect(22, 36, 7, 22, 4, 4)

      // Car body silhouette.
      val body = new Path2D.Double()
      body.moveTo(0.0, -65.0)
      body.curveTo(15.0, -62.0, 23.0, -47.0, 25.0, -29.0)
      body.lineTo(30.0, 37.0)
      body.quadTo(29.0, 61.0, 0.0, 66.0)
      body.quadTo(-29.0, 61.0, -30.0, 37.0)
      body.lineTo(-25.0, -29.0)
      body.curveTo(-23.0, -47.0, -15.0, -62.0, 0.0, -65.0)
      body.closePath()

      cg.setPaint(new GradientPaint(-30.0f, -60.0f, bodyColor.brighter(), 30.0f, 62.0f, bodyColor.darker()))
      cg.fill(body)
      cg.setColor(new Color(235, 250, 255, 190))
      cg.setStroke(new BasicStroke(2.0f))
      cg.draw(body)

      // Hood highlights.
      val hood = new Path2D.Double()
      hood.moveTo(-17.0, -52.0)
      hood.quadTo(0.0, -60.0, 17.0, -52.0)
      hood.lineTo(21.0, -28.0)
      hood.lineTo(-21.0, -28.0)
      hood.closePath()
      cg.setColor(new Color(255, 255, 255, 65))
      cg.fill(hood)

      // Front windshield.
      val glass = new RoundRectangle2D.Double(-19.0, -25.0, 38.0, 28.0, 12.0, 12.0)
      cg.setPaint(new GradientPaint(0.0f, -25.0f, new Color(190, 245, 255), 0.0f, 4.0f, new Color(12, 39, 68)))
      cg.fill(glass)
      cg.setColor(new Color(225, 250, 255, 190))
      cg.draw(glass)

      // Rear window.
      val rearGlass = new RoundRectangle2D.Double(-17.0, 27.0, 34.0, 19.0, 9.0, 9.0)
      cg.setPaint(new GradientPaint(0.0f, 27.0f, new Color(45, 105, 145), 0.0f, 46.0f, new Color(8, 24, 47)))
      cg.fill(rearGlass)

      // Roof center reflection.
      cg.setColor(new Color(255, 255, 255, 85))
      cg.setStroke(new BasicStroke(2.0f))
      cg.drawLine(0, -20, 0, 23)

      // Headlights and tail lights.
      cg.setColor(new Color(190, 250, 255, 255))
      cg.fillRoundRect(-21, -59, 12, 7, 4, 4)
      cg.fillRoundRect(9, -59, 12, 7, 4, 4)
      cg.setColor(new Color(255, 45, 90, 255))
      cg.fillRoundRect(-21, 56, 12, 6, 4, 4)
      cg.fillRoundRect(9, 56, 12, 6, 4, 4)

      // Player roof stripe.
      if (isPlayer) {
        cg.setColor(new Color(255, 255, 255, 170))
        cg.setStroke(new BasicStroke(3.0f))
        cg.drawLine(-3, -48, -3, 48)
        cg.setColor(new Color(255, 255, 255, 45))
        cg.fill(new Ellipse2D.Double(-17.0, -2.0, 34.0, 24.0))
      }

      cg.dispose()
    }

    // -------------------- DRAWING: PICKUPS --------------------
    def drawPickup(g: Graphics2D, p: Pickup): Unit = {
      if (p.active) {
        if (p.kind == "coin") {
          g.setColor(new Color(255, 190, 30, 55))
          g.fill(new Ellipse2D.Double(p.x - 30.0, p.y - 30.0, 60.0, 60.0))
          g.setPaint(new GradientPaint(p.x.toFloat - 12.0f, (p.y - 20.0).toFloat, new Color(255, 255, 175), (p.x + 13.0).toFloat, (p.y + 20.0).toFloat, new Color(205, 112, 10)))
          g.fill(new Ellipse2D.Double(p.x - 14.0, p.y - 21.0, 28.0, 42.0))
          g.setColor(new Color(255, 250, 190))
          g.setStroke(new BasicStroke(2.0f))
          g.draw(new Ellipse2D.Double(p.x - 14.0, p.y - 21.0, 28.0, 42.0))
          g.setFont(new Font("Arial", Font.BOLD, 18))
          g.drawString("$", (p.x - 5.0).toInt, (p.y + 6.0).toInt)
        } else {
          g.setColor(new Color(30, 225, 255, 65))
          g.fill(new Ellipse2D.Double(p.x - 34.0, p.y - 34.0, 68.0, 68.0))
          g.setPaint(new GradientPaint(p.x.toFloat, (p.y - 24.0).toFloat, Color.WHITE, p.x.toFloat, (p.y + 24.0).toFloat, new Color(0, 120, 220)))
          g.fillRoundRect((p.x - 17.0).toInt, (p.y - 24.0).toInt, 34, 48, 12, 12)
          g.setColor(cyan)
          g.setStroke(new BasicStroke(3.0f))
          g.drawRoundRect((p.x - 17.0).toInt, (p.y - 24.0).toInt, 34, 48, 12, 12)
          g.setFont(new Font("Arial", Font.BOLD, 22))
          g.drawString("N", (p.x - 8.0).toInt, (p.y + 8.0).toInt)
        }
      }
    }

    // -------------------- DRAWING: CONES --------------------
    def drawCone(g: Graphics2D, c: Cone): Unit = {
      g.setColor(new Color(0, 0, 0, 100))
      g.fill(new Ellipse2D.Double(c.x - 22.0, c.y + 12.0, 48.0, 22.0))
      val body = new Path2D.Double()
      body.moveTo(c.x, c.y - 29.0)
      body.lineTo(c.x + 20.0, c.y + 23.0)
      body.lineTo(c.x - 20.0, c.y + 23.0)
      body.closePath()
      g.setPaint(new GradientPaint(c.x.toFloat - 15.0f, (c.y - 20.0).toFloat, new Color(255, 220, 95), (c.x + 15.0).toFloat, (c.y + 20.0).toFloat, new Color(190, 65, 25)))
      g.fill(body)
      g.setColor(new Color(255, 255, 235))
      g.setStroke(new BasicStroke(4.0f))
      g.drawLine((c.x - 10.0).toInt, (c.y + 2.0).toInt, (c.x + 10.0).toInt, (c.y + 2.0).toInt)
      g.drawLine((c.x - 15.0).toInt, (c.y + 17.0).toInt, (c.x + 15.0).toInt, (c.y + 17.0).toInt)
    }

    // -------------------- HUD --------------------
    def drawHud(g: Graphics2D, w: Int, h: Int): Unit = {
      g.setColor(new Color(3, 8, 22, 205))
      g.fillRoundRect(18, 15, w - 36, 76, 18, 18)
      g.setColor(new Color(55, 220, 255, 135))
      g.setStroke(new BasicStroke(1.5f))
      g.drawRoundRect(18, 15, w - 36, 76, 18, 18)

      g.setFont(new Font("Arial", Font.BOLD, 17))
      g.setColor(Color.WHITE)
      g.drawString("SCORE  " + score, 35, 43)
      g.setColor(gold)
      g.drawString("COINS  " + coins, 175, 43)
      g.setColor(new Color(255, 105, 135))
      g.drawString("LIVES  " + (1 to lives).map(_ => "?").mkString(" "), 300, 43)
      g.setColor(cyan)
      g.drawString("LEVEL  " + level, 435, 43)
      g.setColor(Color.WHITE)
      g.drawString("SPEED  " + math.abs(carSpeed).toInt, 550, 43)

      g.setFont(new Font("Arial", Font.BOLD, 11))
      g.setColor(new Color(200, 220, 240))
      g.drawString("NITRO", w - 190, 34)
      val bx = w - 135
      val by = 23
      g.setColor(new Color(45, 58, 80))
      g.fillRoundRect(bx, by, 105, 13, 8, 8)
      g.setPaint(new GradientPaint(bx.toFloat, by.toFloat, cyan, (bx + 105).toFloat, by.toFloat, new Color(80, 90, 255)))
      g.fillRoundRect(bx, by, (105.0 * nitro / 100.0).toInt, 13, 8, 8)
      g.setColor(new Color(220, 245, 255, 170))
      g.drawRoundRect(bx, by, 105, 13, 8, 8)

      g.setFont(new Font("Arial", Font.PLAIN, 12))
      g.setColor(new Color(200, 215, 235))
      g.drawString("DISTANCE  " + distance.toInt + " m", 35, 70)
      g.drawString("BEST  " + bestScore, 175, 70)
      g.drawString(if (offRoad) "OFF ROAD - SLOW DOWN" else "FREE DRIVE - 360� STEERING", 300, 70)
      g.drawString("P = PAUSE", w - 105, 70)

      // Direction compass.
      val cx = w - 62
      val cy = h - 70
      g.setColor(new Color(4, 10, 25, 160))
      g.fillOval(cx - 32, cy - 32, 64, 64)
      g.setColor(new Color(100, 220, 255, 150))
      g.drawOval(cx - 32, cy - 32, 64, 64)
      val dx = math.cos(carHeading)
      val dy = math.sin(carHeading)
      g.setStroke(new BasicStroke(4.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND))
      g.setColor(gold)
      g.drawLine(cx, cy, (cx + dx * 23).toInt, (cy + dy * 23).toInt)
      g.fillOval((cx + dx * 23 - 4).toInt, (cy + dy * 23 - 4).toInt, 8, 8)
    }

    // -------------------- OVERLAYS --------------------
    def drawOverlay(g: Graphics2D, w: Int, h: Int, title: String, subtitle: String): Unit = {
      g.setColor(new Color(2, 5, 16, 205))
      g.fillRect(0, 0, w, h)

      val box = new RoundRectangle2D.Double(w / 2.0 - 305.0, h / 2.0 - 175.0, 610.0, 350.0, 32.0, 32.0)
      g.setPaint(new GradientPaint(0.0f, (h / 2 - 175).toFloat, new Color(22, 49, 79, 245), 0.0f, (h / 2 + 175).toFloat, new Color(13, 17, 39, 245)))
      g.fill(box)
      g.setColor(new Color(45, 220, 255, 200))
      g.setStroke(new BasicStroke(2.0f))
      g.draw(box)

      g.setFont(new Font("Arial", Font.BOLD, 44))
      g.setColor(Color.WHITE)
      val fm = g.getFontMetrics
      g.drawString(title, (w - fm.stringWidth(title)) / 2, h / 2 - 80)

      g.setFont(new Font("Arial", Font.PLAIN, 16))
      g.setColor(new Color(195, 225, 245))
      val sm = g.getFontMetrics
      g.drawString(subtitle, (w - sm.stringWidth(subtitle)) / 2, h / 2 - 38)

      g.setFont(new Font("Arial", Font.BOLD, 15))
      g.setColor(cyan)
      val line1 = "W / UP = ACCELERATE      S / DOWN = REVERSE"
      g.drawString(line1, (w - g.getFontMetrics.stringWidth(line1)) / 2, h / 2 + 12)
      val line2 = "A / LEFT = STEER LEFT      D / RIGHT = STEER RIGHT"
      g.drawString(line2, (w - g.getFontMetrics.stringWidth(line2)) / 2, h / 2 + 43)
      val line3 = "Q / E = ROTATE IN PLACE      SPACE = NITRO"
      g.drawString(line3, (w - g.getFontMetrics.stringWidth(line3)) / 2, h / 2 + 74)
      g.setColor(gold)
      val line4 = "P = PAUSE      R = RESTART      ESC = PAUSE"
      g.drawString(line4, (w - g.getFontMetrics.stringWidth(line4)) / 2, h / 2 + 105)
      g.setColor(pink)
      val line5 = "PRESS ENTER OR CLICK TO START"
      g.drawString(line5, (w - g.getFontMetrics.stringWidth(line5)) / 2, h / 2 + 145)
    }

    // -------------------- RESET --------------------
    def resetGame(): Unit = {
      carX = -95.0
      carY = -485.0
      carHeading = 0.0
      carSpeed = 0.0
      score = 0
      coins = 0
      lives = 3
      nitro = 100.0
      boosting = false
      distance = 0.0
      level = 1
      offRoad = false
      invulnerable = 0.0
      elapsed = 0.0
      shake = 0.0
      pressedKeys.clear()
      initializeWorld()
      gameState = "playing"
      lastTime = System.nanoTime()
    }

    // -------------------- INPUT HELPERS --------------------
    def isDown(code: Int): Boolean = pressedKeys.contains(code)
    def anyDown(codes: Seq[Int]): Boolean = codes.exists(isDown)

    // -------------------- GAME UPDATE --------------------
    def updateGame(rawDt: Double): Unit = {
      val dt = clamp(rawDt, 0.0, 0.04)
      elapsed += dt

      if (gameState == "playing") {
        val accelerating = anyDown(Seq(KeyEvent.VK_W, KeyEvent.VK_UP))
        val reversing = anyDown(Seq(KeyEvent.VK_S, KeyEvent.VK_DOWN))
        val left = anyDown(Seq(KeyEvent.VK_A, KeyEvent.VK_LEFT))
        val right = anyDown(Seq(KeyEvent.VK_D, KeyEvent.VK_RIGHT))
        val rotateLeft = isDown(KeyEvent.VK_Q)
        val rotateRight = isDown(KeyEvent.VK_E)
        val handbrake = isDown(KeyEvent.VK_SHIFT)
        boosting = isDown(KeyEvent.VK_SPACE) && nitro > 0.0 && carSpeed > 90.0

        // Acceleration and reverse.
        if (accelerating) carSpeed += 510.0 * dt
        if (reversing) carSpeed -= 610.0 * dt

        val maxForward = if (boosting) 850.0 else 610.0
        carSpeed = clamp(carSpeed, -245.0, maxForward)

        // Friction / handbrake.
        if (!accelerating && !reversing) {
          carSpeed *= math.pow(if (handbrake) 0.91 else 0.985, dt * 60.0)
        }
        if (math.abs(carSpeed) < 2.0) carSpeed = 0.0

        // Full 360-degree steering. It works at every angle, not in lanes.
        val speedFactor = 0.38 + 0.62 * math.min(1.0, math.abs(carSpeed) / 500.0)
        val reverseFactor = if (carSpeed < -5.0) -1.0 else 1.0
        val steering = (if (left) -1.0 else 0.0) + (if (right) 1.0 else 0.0)
        carHeading += steering * 2.55 * speedFactor * reverseFactor * dt

        // Rotate in place for precise 360-degree turning.
        if (rotateLeft) carHeading -= 2.35 * dt
        if (rotateRight) carHeading += 2.35 * dt

        // Continuous free movement in any direction.
        val oldX = carX
        val oldY = carY
        carX += math.cos(carHeading) * carSpeed * dt
        carY += math.sin(carHeading) * carSpeed * dt

        // Keep the player inside the large world boundary.
        if (carX < -1370.0 || carX > 1370.0 || carY < -940.0 || carY > 940.0) {
          carX = clamp(carX, -1370.0, 1370.0)
          carY = clamp(carY, -940.0, 940.0)
          carSpeed *= -0.28
        }

        offRoad = !onRoad(carX, carY)
        if (offRoad) {
          carSpeed *= math.pow(0.972, dt * 60.0)
        }

        if (boosting) nitro = clamp(nitro - 32.0 * dt, 0.0, 100.0)
        else nitro = clamp(nitro + 8.0 * dt, 0.0, 100.0)

        val travel = distanceBetween(oldX, oldY, carX, carY)
        distance += travel * 0.045
        score += (travel * 0.10).toInt
        level = 1 + (distance / 450.0).toInt

        if (invulnerable > 0.0) invulnerable = math.max(0.0, invulnerable - dt)
        if (shake > 0.0) shake = math.max(0.0, shake - dt * 2.0)

        // Pickups.
        pickups.foreach { p =>
          if (p.active && distanceBetween(carX, carY, p.x, p.y) < 61.0) {
            p.active = false
            if (p.kind == "coin") {
              coins += 1
              score += 150
            } else {
              nitro = clamp(nitro + 34.0, 0.0, 100.0)
              score += 60
            }
          }
        }

        // Rival traffic follows the oval track.
        rivals.foreach { r =>
          r.angle += r.angularSpeed * dt
          val rx = math.cos(r.angle) * 860.0
          val ry = math.sin(r.angle) * 492.0
          if (distanceBetween(carX, carY, rx, ry) < 72.0 && invulnerable <= 0.0) {
            lives -= 1
            invulnerable = 1.7
            shake = 0.65
            carSpeed *= 0.35
            if (lives <= 0) {
              gameState = "over"
              if (score > bestScore) {
                bestScore = score
                saveBestScore()
              }
            }
          }
        }

        // Cones: collision slows the car and costs a life.
        cones.foreach { c =>
          if (distanceBetween(carX, carY, c.x, c.y) < 39.0 && invulnerable <= 0.0) {
            lives -= 1
            invulnerable = 1.25
            shake = 0.5
            carSpeed *= 0.32
            if (lives <= 0) {
              gameState = "over"
              if (score > bestScore) {
                bestScore = score
                saveBestScore()
              }
            }
          }
        }
      }
    }

    // -------------------- GAME PANEL --------------------
    val gamePanel = new JPanel {
      setPreferredSize(new Dimension(1160, 740))
      setBackground(Color.BLACK)
      setFocusable(true)

      override def paintComponent(graphics: Graphics): Unit = {
        super.paintComponent(graphics)
        val g = graphics.create().asInstanceOf[Graphics2D]
        setQuality(g)
        val w = getWidth
        val h = getHeight
        drawScreenBackground(g, w, h)

        // Camera follows the car while keeping the car visible near the lower screen.
        val world = g.create().asInstanceOf[Graphics2D]
        val shakeX = if (shake > 0.0) math.sin(elapsed * 55.0) * shake * 7.0 else 0.0
        val shakeY = if (shake > 0.0) math.cos(elapsed * 49.0) * shake * 5.0 else 0.0
        world.translate(w / 2.0 + shakeX, h * 0.66 + shakeY)
        world.scale(0.68, 0.68)
        world.translate(-carX, -carY)

        drawWorld(world)

        // Collectibles and cones.
        pickups.foreach(p => drawPickup(world, p))
        cones.foreach(c => drawCone(world, c))

        // Opponent cars.
        rivals.foreach { r =>
          val rx = math.cos(r.angle) * 860.0
          val ry = math.sin(r.angle) * 492.0
          val dx = -math.sin(r.angle) * 860.0
          val dy = math.cos(r.angle) * 492.0
          val rivalHeading = math.atan2(dy, dx)
          drawCar(world, rx, ry, rivalHeading, r.color, false, 0.82)
        }

        // Player car can point in ANY direction (full 360 degrees).
        if (invulnerable <= 0.0 || (System.currentTimeMillis() / 100) % 2 == 0) {
          drawCar(world, carX, carY, carHeading, new Color(25, 165, 255), true, 1.0)
        }

        world.dispose()

        drawHud(g, w, h)

        if (gameState == "menu") {
          drawOverlay(g, w, h, "NEON RUSH 360", "OPEN-WORLD FREE DRIVE  ?  STEER ANY DIRECTION  ?  EXPLORE THE WHOLE CIRCUIT")
        } else if (gameState == "paused") {
          drawOverlay(g, w, h, "PAUSED", "Press P or ENTER to continue driving.")
        } else if (gameState == "over") {
          drawOverlay(g, w, h, "GAME OVER", "FINAL SCORE: " + score + "     COINS: " + coins + "     BEST: " + bestScore)
        }

        g.dispose()
      }
    }

    // -------------------- KEYBOARD INPUT --------------------
    gamePanel.addKeyListener(new KeyAdapter {
      override def keyPressed(e: KeyEvent): Unit = {
        val code = e.getKeyCode
        if (gameState == "menu" && (code == KeyEvent.VK_ENTER || code == KeyEvent.VK_SPACE)) {
          resetGame()
        } else if (gameState == "over" && (code == KeyEvent.VK_ENTER || code == KeyEvent.VK_SPACE)) {
          resetGame()
        } else if (code == KeyEvent.VK_R) {
          resetGame()
        } else if (code == KeyEvent.VK_P || code == KeyEvent.VK_ESCAPE) {
          if (gameState == "playing") {
            gameState = "paused"
            pressedKeys.clear()
          } else if (gameState == "paused") {
            gameState = "playing"
            lastTime = System.nanoTime()
          }
        } else if (gameState == "playing") {
          pressedKeys += code
        }
        gamePanel.repaint()
      }

      override def keyReleased(e: KeyEvent): Unit = {
        pressedKeys -= e.getKeyCode
      }
    })

    // -------------------- MOUSE INPUT --------------------
    gamePanel.addMouseListener(new MouseAdapter {
      override def mouseClicked(e: MouseEvent): Unit = {
        if (gameState == "menu" || gameState == "over") {
          resetGame()
        } else if (gameState == "paused") {
          gameState = "playing"
          lastTime = System.nanoTime()
        }
        gamePanel.requestFocusInWindow()
        gamePanel.repaint()
      }
    })

    // -------------------- TIMER / MAIN LOOP --------------------
    val timer = new javax.swing.Timer(16, new ActionListener {
      override def actionPerformed(e: ActionEvent): Unit = {
        val now = System.nanoTime()
        val dt = (now - lastTime) / 1000000000.0
        lastTime = now
        updateGame(dt)
        gamePanel.repaint()
      }
    })

    // -------------------- SHOW GAME --------------------
    frame.setContentPane(gamePanel)
    frame.pack()
    frame.setLocationRelativeTo(null)
    frame.setVisible(true)
    gamePanel.requestFocusInWindow()
    timer.start()
  }
})