Code Sketch


purva chavan
By: Mhalsakant School
Category: Art
cleari()
drawStage(cm.darkBlue)

val cb = canvasBounds

// Catch the Star - Advanced Game
// Controls: LEFT and RIGHT arrow keys

// Create the catcher
val catcher = fillColor(cm.orange) ->
    Picture.rectangle(70, 20)

catcher.setPosition(0, cb.y + 35)
draw(catcher)

// Create the star
val star = fillColor(cm.yellow) ->
    Picture {
        repeat(5) {
            forward(25)
            right(144)
        }
    }

star.setPosition(0, cb.y + cb.height - 30)
draw(star)

// Game settings
var score = 0
var lives = 3
var level = 1
var speed = 3.0
var frames = 0
var gameOver = false

// Random number generator
val rng = new scala.util.Random()

// Place star at a random position
def resetStar(): Unit = {
    val x = cb.x + 25 +
        rng.nextDouble() * (cb.width - 50)

    star.setPosition(x, cb.y + cb.height - 30)
}

// Start the game
animate {
    if (!gameOver) {
        frames = frames + 1

        // Move catcher with arrow keys
        var px = catcher.position.x

        if (isKeyPressed(Kc.VK_LEFT)) {
            px = px - 6
        }

        if (isKeyPressed(Kc.VK_RIGHT)) {
            px = px + 6
        }

        // Keep catcher inside the canvas
        px = math.max(cb.x + 40,
            math.min(cb.x + cb.width - 40, px))

        catcher.setPosition(px, cb.y + 35)

        // Move star downward
        star.translate(0, -speed)

        // Catch the star
        if (star.collidesWith(catcher)) {
            score = score + 1
            println("Score: " + score)

            // Increase level every 5 points
            if (score % 5 == 0) {
                level = level + 1
                speed = speed + 1
                println("LEVEL UP! Level: " + level)
            }

            resetStar()
        }

        // Missed star
        if (star.position.y < cb.y) {
            lives = lives - 1
            println("Lives left: " + lives)
            resetStar()

            if (lives <= 0) {
                gameOver = true
                println("GAME OVER!")
                println("Final Score: " + score)
                stopAnimation()
            }
        }

        // Time limit: about 60 seconds
        if (frames >= 3000) {
            gameOver = true
            println("TIME UP!")
            println("Final Score: " + score)
            stopAnimation()
        }
    }
}

activateCanvas()