Code Sketch
sniper_0718
cleari()
drawStage(Color(135, 206, 250)) // Sky blue stage background
val cb = canvasBounds
var truckX = cb.x + 100
var truckY = cb.y + 50
var obstacleX = cb.x + cb.width
var score = 0
var isJumping = false
var jumpVelocity = 0.0
// Build the truck using Kojo's Picture graphics API
val truckBody = fillColor(red) -> Picture.rectangle(90, 35)
val truckCab = fillColor(blue) -> Picture.rectangle(45, 30)
val wheel1 = fillColor(black) -> Picture.circle(10)
val wheel2 = fillColor(black) -> Picture.circle(10)
val truck = GPics(
truckBody,
trans(45, 35) -> truckCab,
trans(20, -10) -> wheel1,
trans(70, -10) -> wheel2
)
// Build the obstacle (Rock)
val obstacle = fillColor(darkGray) -> Picture.rectangle(25, 30)
// Initial positioning on the canvas
truck.setPosition(truckX, truckY)
obstacle.setPosition(obstacleX, truckY)
draw(truck, obstacle)
// Main animation game loop running ~50 times per second
animate {
// Check for UP arrow key press to jump
if (isKeyPressed(Kc.VK_UP) && !isJumping) {
isJumping = true
jumpVelocity = 16.0
}
// Apply jump physics and gravity
if (isJumping) {
truckY += jumpVelocity
jumpVelocity -= 1.0 // Gravity pulls down
if (truckY <= cb.y + 50) {
truckY = cb.y + 50
isJumping = false
}
}
// Move the obstacle from right to left
obstacleX -= 8.0
if (obstacleX < cb.x - 50) {
obstacleX = cb.x + cb.width + (math.random * 100)
score += 1
}
// Update object coordinates on screen
truck.setPosition(truckX, truckY)
obstacle.setPosition(obstacleX, cb.y + 50)
// Collision check between the truck and the obstacle
if (truck.collidesWith(obstacle)) {
score = 0 // Reset score on crash
obstacleX = cb.x + cb.width
}
}