Code Sketch


DURVA
By: Mhalsakant School
Category: Art
// Clear the canvas and set a dark background
cleari()
drawStage(black)

// Setup the Player (Green Square)
val player = Picture.rectangle(40, 40)
player.setFillColor(green)
player.setPenColor(noColor)
player.setPosition(0, -150) // Start at the bottom center
draw(player)

// Setup the Obstacle (Red Ball)
val obstacle = Picture.circle(20)
obstacle.setFillColor(red)
obstacle.setPenColor(noColor)
obstacle.setPosition(0, 200) // Start at the top center
draw(obstacle)

// Setup Game Status Text
val statusText = Picture.text("Use Arrow Keys to Move!", 20)
statusText.setPenColor(white)
statusText.setPosition(canvasBounds.x + 20, canvasBounds.y + canvasBounds.height - 40)
draw(statusText)

// Game speed settings
val playerSpeed = 15.0
var obstacleSpeed = 8.0
var score = 0

// Keyboard Inputs: Control the player using direct numeric keycodes
onKeyPress { key =>
    val cb = canvasBounds
    val pb = player.bounds
    
    key match {
        // Move Left (KeyCode 37)
        case 37 => 
            if (pb.x > cb.x) player.translate(-playerSpeed, 0)
            
        // Move Right (KeyCode 39)
        case 39 => 
            if (pb.x + pb.width < cb.x + cb.width) player.translate(playerSpeed, 0)
            
        // Move Up (KeyCode 38)
        case 38 => 
            if (pb.y + pb.height < cb.y + cb.height) player.translate(0, playerSpeed)
            
        // Move Down (KeyCode 40)
        case 40 => 
            if (pb.y > cb.y) player.translate(0, -playerSpeed)
            
        case _ => // Do nothing for other keys
    }
}

// Main Animation Loop
animate {
    // 1. Make the obstacle fall downwards
    obstacle.translate(0, -obstacleSpeed)
    
    val cb = canvasBounds
    val ob = obstacle.bounds
    val pb = player.bounds
    
    // 2. Reset obstacle if it falls off the bottom screen
    if (ob.y + ob.height < cb.y) {
        // Teleport back to top at a random X coordinate
        val randomX = random(-200, 200)
        obstacle.setPosition(randomX, cb.y + cb.height)
        
        // Increase score and difficulty speed
        score += 1
        obstacleSpeed += 0.5
        statusText.update(s"Score: $score")
    }
    
    // 3. Collision Detection (Hits the player)
    if (pb.intersects(ob)) {
        statusText.update(s"GAME OVER! Final Score: $score")
        
        // Reset game state
        score = 0
        obstacleSpeed = 8.0
        player.setPosition(0, -150)
        obstacle.setPosition(0, cb.y + cb.height)
    }
}