Code Sketch


Bixuu
By: Mhalsakant School
Category: Programming

import java.awt._
import java.awt.event._
import java.awt.geom._
import javax.swing._
import scala.collection.mutable.ArrayBuffer
import java.util.Random

case class MObstacle(
  var x: Double,
  y: Double,
  w: Double,
  h: Double,
  kind: String
)

case class MCoin(var x: Double, y: Double)

case class MParticle(
  var x: Double,
  var y: Double,
  var vx: Double,
  var vy: Double,
  var life: Int
)

class MouseDashGame extends JPanel {

  val W = 1100
  val H = 650

  val SIZE = 42

  val random = new Random()

  var state = "MENU"

  var playerX = 160.0
  var playerY = 300.0

  var targetX = 160.0
  var targetY = 300.0

  var score = 0
  var coinsCollected = 0

  var frame = 0
  var speed = 5.0

  var spawnTimer = 0
  var coinTimer = 0

  var bestScore = 0

  val obstacles = ArrayBuffer[MObstacle]()
  val coins = ArrayBuffer[MCoin]()
  val particles = ArrayBuffer[MParticle]()

  val timer = new Timer(16, new ActionListener {
    override def actionPerformed(e: ActionEvent): Unit = {
      updateGame()
      repaint()
    }
  })

  setPreferredSize(new Dimension(W, H))
  setBackground(Color.BLACK)
  setFocusable(true)

  // MOUSE MOVEMENT
  addMouseMotionListener(new MouseMotionAdapter {

    override def mouseMoved(e: MouseEvent): Unit = {
      movePlayer(e.getX, e.getY)
    }

    override def mouseDragged(e: MouseEvent): Unit = {
      movePlayer(e.getX, e.getY)
    }
  })

  def movePlayer(x: Int, y: Int): Unit = {

    targetX = math.max(
      5.0,
      math.min(W - SIZE - 5.0, x.toDouble)
    )

    targetY = math.max(
      75.0,
      math.min(H - SIZE - 20.0, y.toDouble)
    )

    if (state == "MENU") repaint()
  }

  // MOUSE CLICK
  addMouseListener(new MouseAdapter {

    override def mousePressed(e: MouseEvent): Unit = {

      requestFocusInWindow()

      if (state == "MENU" || state == "DEAD") {
        resetGame()
      }
    }
  })

  // KEYBOARD OPTIONS
  def bind(key: String, id: String)(action: => Unit): Unit = {

    getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
      .put(KeyStroke.getKeyStroke(key), id)

    getActionMap.put(id, new AbstractAction {

      override def actionPerformed(e: ActionEvent): Unit = {
        action
      }
    })
  }

  bind("P", "pause") {
    if (state == "PLAY") state = "PAUSE"
    else if (state == "PAUSE") state = "PLAY"
  }

  bind("R", "restart") {
    resetGame()
  }

  bind("ESCAPE", "menu") {
    state = "MENU"
  }

  // RESET GAME
  def resetGame(): Unit = {

    playerX = targetX
    playerY = targetY

    score = 0
    coinsCollected = 0

    frame = 0
    speed = 5.0

    spawnTimer = 0
    coinTimer = 0

    obstacles.clear()
    coins.clear()
    particles.clear()

    state = "PLAY"
  }

  // CREATE OBSTACLES
  def spawnObstacle(): Unit = {

    val y = 100 + random.nextInt(440)

    if (random.nextInt(3) == 0) {

      obstacles += MObstacle(
        W + 40.0,
        y.toDouble,
        65.0,
        65.0,
        "block"
      )

    } else {

      obstacles += MObstacle(
        W + 40.0,
        y.toDouble,
        52.0,
        52.0,
        "spike"
      )
    }
  }

  // CREATE COINS
  def spawnCoin(): Unit = {

    val y = 100 + random.nextInt(430)

    coins += MCoin(
      W + 40.0,
      y.toDouble
    )
  }

  // PARTICLES
  def updateParticles(): Unit = {

    particles.foreach { p =>
      p.x += p.vx
      p.y += p.vy
      p.life -= 1
    }

    var i = particles.length - 1

    while (i >= 0) {
      if (particles(i).life <= 0) {
        particles.remove(i)
      }
      i -= 1
    }
  }

  def explosion(): Unit = {

    for (i <- 0 until 28) {

      val angle = i * math.Pi * 2.0 / 28.0

      particles += MParticle(
        playerX + SIZE / 2.0,
        playerY + SIZE / 2.0,
        math.cos(angle) * 4.5,
        math.sin(angle) * 4.5,
        35
      )
    }
  }

  // COLLISION
  def checkCollision(): Boolean = {

    val player = new Rectangle2D.Double(
      playerX + 5,
      playerY + 5,
      SIZE - 10,
      SIZE - 10
    )

    obstacles.exists { o =>

      if (o.kind == "block") {

        val rect = new Rectangle2D.Double(
          o.x + 4,
          o.y + 4,
          o.w - 8,
          o.h - 8
        )

        player.intersects(rect)

      } else {

        val triangle = new Polygon(
          Array(
            o.x.toInt,
            (o.x + o.w / 2.0).toInt,
            (o.x + o.w).toInt
          ),
          Array(
            (o.y + o.h).toInt,
            o.y.toInt,
            (o.y + o.h).toInt
          ),
          3
        )

        triangle.intersects(player)
      }
    }
  }

  // COIN COLLECTION
  def collectCoins(): Unit = {

    val player = new Rectangle2D.Double(
      playerX,
      playerY,
      SIZE,
      SIZE
    )

    var i = coins.length - 1

    while (i >= 0) {

      val coin = coins(i)

      val rect = new Rectangle2D.Double(
        coin.x - 12,
        coin.y - 12,
        24,
        24
      )

      if (player.intersects(rect)) {

        coins.remove(i)

        score += 50
        coinsCollected += 1

        for (j <- 0 until 8) {

          val a = j * math.Pi * 2.0 / 8.0

          particles += MParticle(
            coin.x,
            coin.y,
            math.cos(a) * 2.5,
            math.sin(a) * 2.5,
            22
          )
        }
      }

      i -= 1
    }
  }

  // REMOVE OLD OBJECTS
  def removeObjects(): Unit = {

    var i = obstacles.length - 1

    while (i >= 0) {
      if (obstacles(i).x + obstacles(i).w < -10) {
        obstacles.remove(i)
      }
      i -= 1
    }

    var j = coins.length - 1

    while (j >= 0) {
      if (coins(j).x < -30) {
        coins.remove(j)
      }
      j -= 1
    }
  }

  // MAIN GAME LOOP
  def updateGame(): Unit = {

    updateParticles()

    if (state != "PLAY") return

    frame += 1

    // Smooth mouse following
    playerX += (targetX - playerX) * 0.35
    playerY += (targetY - playerY) * 0.35

    // Increase speed slowly
    speed = math.min(11.0, 5.0 + score / 900.0)

    // Spawn obstacles
    spawnTimer += 1

    if (spawnTimer >= math.max(35, 75 - score / 200)) {
      spawnObstacle()
      spawnTimer = 0
    }

    // Spawn coins
    coinTimer += 1

    if (coinTimer >= 85) {
      spawnCoin()
      coinTimer = 0
    }

    // Move obstacles
    obstacles.foreach { o =>
      o.x -= speed
    }

    // Move coins
    coins.foreach { c =>
      c.x -= speed
    }

    removeObjects()

    // Score
    if (frame % 5 == 0) {
      score += 1
    }

    collectCoins()

    // Collision
    if (checkCollision()) {

      state = "DEAD"

      explosion()

      if (score > bestScore) {
        bestScore = score
      }
    }
  }

  // BACKGROUND
  def drawBackground(g: Graphics2D): Unit = {

    g.setPaint(new GradientPaint(
      0, 0,
      new Color(5, 8, 27),
      0, H,
      new Color(28, 12, 60)
    ))

    g.fillRect(0, 0, W, H)

    // Stars
    for (i <- 0 until 65) {

      val x = (
        i * 97 -
        (frame * 0.8).toInt % W + W
      ) % W

      val y = (i * 53) % H

      g.setColor(new Color(210, 225, 255, 115))

      g.fillOval(x, y, 3, 3)
    }

    // Moving grid
    val offset = (frame * 2) % 50

    g.setColor(new Color(80, 100, 180, 30))

    var x = -offset

    while (x < W) {
      g.drawLine(x, 0, x, H)
      x += 50
    }

    var y = 0

    while (y < H) {
      g.drawLine(0, y, W, y)
      y += 50
    }

    // Side glow
    g.setColor(new Color(
      0, 220, 255, 20
    ))

    g.fillRect(0, 0, 5, H)
    g.fillRect(W - 5, 0, 5, H)
  }

  // OBSTACLES
  def drawObstacles(g: Graphics2D): Unit = {

    obstacles.foreach { o =>

      if (o.kind == "block") {

        g.setColor(new Color(0, 220, 255, 35))

        g.fillRoundRect(
          o.x.toInt - 7,
          o.y.toInt - 7,
          o.w.toInt + 14,
          o.h.toInt + 14,
          12,
          12
        )

        g.setPaint(new GradientPaint(
          o.x.toFloat,
          o.y.toFloat,
          new Color(100, 245, 255),
          o.x.toFloat,
          (o.y + o.h).toFloat,
          new Color(0, 75, 180)
        ))

        g.fillRoundRect(
          o.x.toInt,
          o.y.toInt,
          o.w.toInt,
          o.h.toInt,
          9,
          9
        )

        g.setColor(Color.WHITE)
        g.setStroke(new BasicStroke(2))

        g.drawRoundRect(
          o.x.toInt,
          o.y.toInt,
          o.w.toInt,
          o.h.toInt,
          9,
          9
        )

      } else {

        val p = new Polygon(
          Array(
            o.x.toInt,
            (o.x + o.w / 2.0).toInt,
            (o.x + o.w).toInt
          ),
          Array(
            (o.y + o.h).toInt,
            o.y.toInt,
            (o.y + o.h).toInt
          ),
          3
        )

        g.setColor(new Color(255, 40, 100, 45))

        g.fillOval(
          o.x.toInt - 12,
          o.y.toInt - 8,
          o.w.toInt + 24,
          o.h.toInt + 16
        )

        g.setPaint(new GradientPaint(
          o.x.toFloat,
          o.y.toFloat,
          Color.WHITE,
          o.x.toFloat,
          (o.y + o.h).toFloat,
          new Color(255, 40, 100)
        ))

        g.fillPolygon(p)

        g.setColor(Color.WHITE)
        g.drawPolygon(p)
      }
    }
  }

  // COINS
  def drawCoins(g: Graphics2D): Unit = {

    coins.foreach { c =>

      val x = c.x.toInt
      val y = c.y.toInt

      g.setColor(new Color(255, 210, 0, 35))
      g.fillOval(x - 19, y - 19, 38, 38)

      g.setPaint(new GradientPaint(
        x.toFloat - 12,
        y.toFloat - 12,
        Color.WHITE,
        x.toFloat + 12,
        y.toFloat + 12,
        new Color(255, 155, 0)
      ))

      g.fillOval(x - 12, y - 12, 24, 24)

      g.setColor(Color.WHITE)
      g.drawOval(x - 12, y - 12, 24, 24)

      g.setFont(new Font("Arial", Font.BOLD, 15))
      g.drawString("$", x - 4, y + 6)
    }
  }

  // PLAYER
  def drawPlayer(g: Graphics2D): Unit = {

    val cx = (playerX + SIZE / 2).toInt
    val cy = (playerY + SIZE / 2).toInt

    // Glow
    for (i <- 3 to 1 by -1) {

      g.setColor(new Color(
        0,
        230,
        255,
        20
      ))

      g.fillOval(
        cx - 28 - i * 6,
        cy - 28 - i * 6,
        56 + i * 12,
        56 + i * 12
      )
    }

    // Trail
    g.setColor(new Color(0, 220, 255, 35))
    g.fillOval(cx - 42, cy - 10, 24, 20)

    val cg = g.create().asInstanceOf[Graphics2D]

    cg.translate(cx, cy)

    cg.setPaint(new GradientPaint(
      -20, -20,
      Color.WHITE,
      20, 20,
      new Color(0, 170, 255)
    ))

    cg.fillRoundRect(-SIZE / 2, -SIZE / 2, SIZE, SIZE, 9, 9)

    cg.setColor(Color.WHITE)
    cg.setStroke(new BasicStroke(3))

    cg.drawRoundRect(-SIZE / 2, -SIZE / 2, SIZE, SIZE, 9, 9)

    cg.setColor(new Color(10, 30, 70))

    cg.fillOval(-11, -7, 7, 9)
    cg.fillOval(5, -7, 7, 9)

    cg.drawArc(-10, 1, 20, 15, 200, 140)

    cg.dispose()
  }

  // PARTICLES
  def drawParticles(g: Graphics2D): Unit = {

    particles.foreach { p =>

      val alpha = math.max(0, math.min(255, p.life * 7))

      g.setColor(new Color(0, 210, 255, alpha))

      g.fillOval(
        p.x.toInt,
        p.y.toInt,
        7,
        7
      )
    }
  }

  // HUD
  def drawHUD(g: Graphics2D): Unit = {

    g.setFont(new Font("Arial", Font.BOLD, 20))

    g.setColor(Color.WHITE)

    g.drawString("MOUSE DASH", 25, 37)

    g.setFont(new Font("Arial", Font.BOLD, 16))

    g.drawString("SCORE: " + score, 25, 70)

    g.drawString("COINS: " + coinsCollected, 25, 98)

    g.drawString("BEST: " + bestScore, 25, 126)

    // Progress / speed
    g.setColor(new Color(70, 80, 110))

    g.fillRoundRect(400, 26, 300, 12, 10, 10)

    g.setColor(new Color(0, 230, 255))

    g.fillRoundRect(
      400,
      26,
      (300 * math.min(1.0, score / 2000.0)).toInt,
      12,
      10,
      10
    )

    g.setColor(Color.WHITE)

    g.drawString("SPEED: " + speed.toInt, 850, 36)

    g.drawString("MOVE YOUR MOUSE TO CONTROL", 830, 66)
  }

  def center(g: Graphics2D, text: String, y: Int): Unit = {

    val fm = g.getFontMetrics

    g.drawString(
      text,
      (W - fm.stringWidth(text)) / 2,
      y
    )
  }

  // MENU
  def drawMenu(g: Graphics2D): Unit = {

    g.setColor(new Color(0, 0, 15, 180))
    g.fillRect(0, 0, W, H)

    g.setFont(new Font("Arial", Font.BOLD, 74))
    g.setColor(new Color(0, 230, 255))

    center(g, "MOUSE DASH", 205)

    g.setFont(new Font("Arial", Font.BOLD, 22))
    g.setColor(Color.WHITE)

    center(g, "CONTROL THE PLAYER WITH YOUR MOUSE", 260)

    g.setFont(new Font("Arial", Font.BOLD, 22))
    g.setColor(Color.YELLOW)

    center(g, "CLICK TO START", 365)

    g.setFont(new Font("Arial", Font.PLAIN, 18))
    g.setColor(Color.LIGHT_GRAY)

    center(g, "MOVE MOUSE = MOVE PLAYER", 425)

    center(g, "DODGE OBSTACLES AND COLLECT COINS", 465)

    center(g, "P = PAUSE     R = RESTART     ESC = MENU", 515)
  }

  // GAME OVER
  def drawGameOver(g: Graphics2D): Unit = {

    g.setColor(new Color(0, 0, 15, 200))
    g.fillRect(0, 0, W, H)

    g.setFont(new Font("Arial", Font.BOLD, 65))
    g.setColor(Color.RED)

    center(g, "GAME OVER", 245)

    g.setFont(new Font("Arial", Font.BOLD, 25))
    g.setColor(Color.WHITE)

    center(g, "YOUR SCORE: " + score, 310)

    center(g, "BEST SCORE: " + bestScore, 355)

    g.setColor(Color.YELLOW)

    center(g, "CLICK TO PLAY AGAIN", 430)
  }

  // MAIN DRAW
  override def paintComponent(graphics: Graphics): Unit = {

    super.paintComponent(graphics)

    val g = graphics.create().asInstanceOf[Graphics2D]

    g.setRenderingHint(
      RenderingHints.KEY_ANTIALIASING,
      RenderingHints.VALUE_ANTIALIAS_ON
    )

    drawBackground(g)
    drawObstacles(g)
    drawCoins(g)
    drawParticles(g)
    drawPlayer(g)

    if (state == "MENU") {

      drawMenu(g)

    } else if (state == "PLAY") {

      drawHUD(g)

    } else if (state == "PAUSE") {

      g.setColor(new Color(0, 0, 0, 180))
      g.fillRect(0, 0, W, H)

      g.setFont(new Font("Arial", Font.BOLD, 60))
      g.setColor(Color.YELLOW)

      center(g, "PAUSED", 290)

    } else if (state == "DEAD") {

      drawGameOver(g)
    }

    g.dispose()
  }
}

// ======================================
// DIRECT SWING WINDOW LAUNCH
// ======================================

SwingUtilities.invokeLater(new Runnable {

  override def run(): Unit = {

    val game = new MouseDashGame()

    val window = new JFrame("MOUSE DASH - Mouse Controlled Game")

    window.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)

    window.setContentPane(game)
    window.pack()

    window.setResizable(false)
    window.setLocationRelativeTo(null)

    window.setVisible(true)

    game.timer.start()
    game.requestFocusInWindow()
  }
})