### Start Game Session (Swift) Source: https://context7.com/reyhanl/watermelonninja/llms.txt Initiates a new game session by resetting score and health, and starting a timer for automatic fruit generation. This function prepares the game state for the player. It's often triggered by a 'retry' action or on initial load. ```swift // Starting a new game session func startGameExample() { let scene = GameScene() // Called automatically by didMove(to:) or manually via retry button scene.startGame() // Behind the scenes: // - scene.score = 0 // - scene.health = 3 // - scene.isGameOver = false // - Timer created with 1 second interval calling generateFruit() // - Three heart nodes added to UI // Timer calls generateFruit() every second which: // - Generates 0-2 random objects (fruits or bombs) // - Each has 25% chance of being a bomb, 75% fruit // - Spawns at random X position at bottom of screen // - Applies physics velocity to launch upward } ``` -------------------------------- ### Initialize and Present Game Scene (Swift) Source: https://context7.com/reyhanl/watermelonninja/llms.txt Initializes and presents the main game scene ('GameScene') within an SKView. It configures the view to display the scene, showing FPS and node count for debugging. This code is typically found in a UIViewController. ```swift import SpriteKit import GameplayKit // Initialize and present the game scene class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let view = self.view as! SKView? { if let scene = SKScene(fileNamed: "GameScene") { scene.scaleMode = .aspectFit view.presentScene(scene) } view.ignoresSiblingOrder = true view.showsFPS = true view.showsNodeCount = true } } } // Key properties and initialization let scene = GameScene() scene.score = 0 // Current score scene.health = 3 // Current health (0-3) scene.isGameOver = false // Game state flag // Scene automatically calls didMove when presented // Starts game with timer-based fruit generation ``` -------------------------------- ### Manage Health System with Visual Feedback (Swift) Source: https://context7.com/reyhanl/watermelonninja/llms.txt Manages the player's health, represented by three heart indicators. It uses a `didSet` observer to update the visual representation of hearts when health changes. When health reaches zero, it triggers the `gameOver` sequence. This system is central to the game's win/loss condition. ```swift // Health management with visual feedback var health = 3 { didSet { if health == 3 { firstHealth.isEmpty = false secondHealth.isEmpty = false thirdHealth.isEmpty = false } else if health == 2 { executeHealth(node: thirdHealth) } else if health == 1 { executeHealth(node: secondHealth) } else if health == 0 { executeHealth(node: thirdHealth) executeHealth(node: secondHealth) executeHealth(node: firstHealth) gameOver() } } } ``` -------------------------------- ### Create Custom Fruit SKSpriteNode Subclass with Screen Tracking Source: https://context7.com/reyhanl/watermelonninja/llms.txt Custom SKSpriteNode subclass for watermelon objects that can be sliced. Includes screen tracking via isOnScreen boolean property and initializes with watermelon texture. Designed to work with physics bodies for collision detection and touch-based slicing mechanics. ```swift import SpriteKit class Fruit: SKSpriteNode { var isOnScreen = false // Tracks if fruit has appeared on screen override init(texture: SKTexture?, color: UIColor, size: CGSize) { super.init(texture: texture, color: color, size: size) self.texture = .init(imageNamed: "watermelon") } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.texture = .init(imageNamed: "watermelon") } } // Usage in game scene let fruit = Fruit() fruit.size = .init(width: nodeSize, height: nodeSize) fruit.name = "fruit" fruit.position = .init(x: randomX, y: -height / 2) fruit.physicsBody = makeBody() // Add physics // Touch detection identifies Fruit type if node is Fruit { sliceFruit(node: node) } ``` -------------------------------- ### Initiate Game Over Sequence and UI Updates (Swift) Source: https://context7.com/reyhanl/watermelonninja/llms.txt Manages the game over state by stopping fruit spawning, slicing any remaining fruits on screen, and displaying the retry button. This function is called when the player's health reaches zero, signaling the end of the current game session. ```swift // Game over sequence func gameOver() { generateFruitTimer?.invalidate() // Stop spawning // Slice all remaining fruits for child in children.filter({ $0 is Fruit }) { animateSliceFruit(node: child) } addRetryButton() // Show retry UI } ``` -------------------------------- ### Implement Physics-Based Fruit Slice Animation with Split Halves Source: https://context7.com/reyhanl/watermelonninja/llms.txt Animation system that creates visual feedback by spawning left and right sprite halves with opposite horizontal velocities. Uses physics simulation for realistic trajectory including gravity, rotation, and off-screen cleanup. Called when fruit is successfully sliced to increment score and remove original node. ```swift // Slicing animation with physics-based split func animateSliceFruit(node: SKNode) { let rotation = node.zRotation let nodeSize = node.frame.width // Create left half let leftSlice = SKSpriteNode(imageNamed: "sliceLeft") leftSlice.size = .init(width: nodeSize, height: nodeSize) leftSlice.position = node.position leftSlice.zPosition = 0 leftSlice.physicsBody = makeBody() leftSlice.physicsBody?.velocity.dx = -nodeSize / 2 // Move left leftSlice.zRotation = rotation addChild(leftSlice) // Create right half let rightSlice = SKSpriteNode(imageNamed: "sliceRight") rightSlice.size = .init(width: nodeSize, height: nodeSize) rightSlice.position = node.position rightSlice.physicsBody = makeBody() rightSlice.zPosition = 1 rightSlice.physicsBody?.velocity.dx = nodeSize / 2 // Move right rightSlice.zRotation = rotation addChild(rightSlice) // Physics simulation causes halves to: // - Fly apart horizontally // - Continue upward trajectory // - Rotate from angular velocity // - Fall with gravity // - Clean up automatically when off-screen } // Called when fruit is sliced func sliceFruit(node: SKNode) { guard !slicedFruits.contains(node) else { return } slicedFruits.append(node) animateSliceFruit(node: node) score += 1 node.removeFromParent() } ``` -------------------------------- ### Create Custom Bomb SKSpriteNode Subclass for Game Over Obstacles Source: https://context7.com/reyhanl/watermelonninja/llms.txt Custom SKSpriteNode subclass representing bomb obstacles that trigger immediate game over upon touch. Initializes with bomb texture and physics body. Integrates with game state management to invalidate spawn timers and end gameplay when touched. ```swift import SpriteKit class Bomb: SKSpriteNode { override init(texture: SKTexture?, color: UIColor, size: CGSize) { super.init(texture: texture, color: color, size: size) self.texture = .init(imageNamed: "bomb") } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.texture = .init(imageNamed: "bomb") } } // Usage in game scene let bomb = Bomb() bomb.size = .init(width: nodeSize, height: nodeSize) bomb.position = .init(x: randomX, y: -height / 2) bomb.physicsBody = makeBody() // Add physics // Touch detection triggers game over if node is Bomb { guard isGameOver == false else { return } isGameOver = true generateFruitTimer?.invalidate() // Scale animation then set health to 0 } ``` -------------------------------- ### Create Custom Heart SKSpriteNode for Health UI Indicators Source: https://context7.com/reyhanl/watermelonninja/llms.txt Custom SKSpriteNode subclass for health display with filled/empty state toggling via computed property. Includes proportional sizing method that maintains aspect ratio based on image dimensions. Supports multiple heart instances positioned at screen top for health visualization. ```swift import SpriteKit class Heart: SKSpriteNode { var isEmpty: Bool = false { didSet { // Toggle between filled and empty heart textures texture = isEmpty ? .init(imageNamed: "heart") : .init(imageNamed: "heart.fill") } } override init(texture: SKTexture?, color: UIColor, size: CGSize) { super.init(texture: texture, color: color, size: size) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setSize(width: CGFloat) { if let image = UIImage(named: "heart") { let tempWidth = width let tempHeight = tempWidth / image.size.width * image.size.height self.size = CGSize(width: tempWidth, height: tempHeight) } } } // Usage: Three hearts positioned at top-right let firstHealth = Heart() firstHealth.isEmpty = false firstHealth.setSize(width: width / 12) firstHealth.position = .init(x: width / 2 - firstHealth.size.width, y: safeAreaY) let secondHealth = Heart() secondHealth.isEmpty = false secondHealth.setSize(width: width / 12) secondHealth.position.x = firstHealth.position.x - firstHealth.frame.size.width - padding // Health loss updates isEmpty property heartNode.isEmpty = true // Automatically switches texture ``` -------------------------------- ### Swift SpriteKit Score Label and Update Source: https://context7.com/reyhanl/watermelonninja/llms.txt Implements a score label in SpriteKit using Swift. It sets up an SKLabelNode with initial text '0', applies a distance constraint to position it relative to the screen border, and updates the label's text automatically when the 'score' property changes via a `didSet` observer. This is useful for displaying dynamic scores in a SpriteKit game. ```swift // Score label with auto-update private lazy var scoreLabel: SKLabelNode = { let label = SKLabelNode(text: "0") let rangeToLeftBorder = SKRange(lowerLimit: 10.0, upperLimit: 150.0) let distanceConstraint = SKConstraint.distance(rangeToLeftBorder, to: label) label.constraints = [distanceConstraint] label.position = .init( x: -width / 2 + label.frame.size.width + 10, y: height / 2 - 100 ) label.fontSize = 50 return label }() // Score property with didSet observer var score = 0 { didSet { scoreLabel.text = "\(score)" } } // Usage flow addChild(scoreLabel) // Add to scene once score = 0 // Reset on game start score += 1 // Increment on each fruit slice - label updates automatically // Example during gameplay: // User slices 5 fruits: // score += 1 // "1" // score += 1 // "2" // score += 1 // "3" // score += 1 // "4" // score += 1 // "5" ``` -------------------------------- ### Simulate Physics and Manage Off-Screen Objects (Swift) Source: https://context7.com/reyhanl/watermelonninja/llms.txt Performs frame-by-frame physics simulation checks. It identifies nodes (fruits, bombs, slices) that have moved off the bottom of the screen. For fruits, it decrements health if not sliced; otherwise, it cleans up nodes. This is crucial for maintaining game state and performance. ```swift // Frame-by-frame simulation check override func didSimulatePhysics() { super.didSimulatePhysics() let bottom = -(height / 2) for node in children { if let fruitNode = node as? Fruit { if fruitNode.position.y > bottom { fruitNode.isOnScreen = true } else if fruitNode.isOnScreen && fruitNode.position.y < bottom { // Fruit fell off screen without being sliced fruitNode.removeFromParent() guard health != 0 else { return } health -= 1 // Lose health for missing fruit } } else { // Clean up bombs and slice sprites if node.position.y < bottom { node.removeFromParent() } } } } ``` -------------------------------- ### Handle Touches for Slicing Fruits and Bombs (Swift) Source: https://context7.com/reyhanl/watermelonninja/llms.txt Processes user touch events to detect interactions with fruits (slicing) and bombs (game over). It identifies nodes at the touch location and triggers corresponding game logic, including score updates, animations, and game state changes. This function is part of the main game scene's touch handling. ```swift // Touch interaction flow override func touchesMoved(_ touches: Set, with event: UIEvent?) { for touch in touches { let position = touch.location(in: self) // Check all nodes at touch position for node in nodes(at: position) { if node is Fruit { // Slice fruit: add to score, animate slice, remove node sliceFruit(node: node) // - Increments score += 1 // - Creates left/right slice sprites with physics // - Removes original fruit node } else if node is Bomb { guard isGameOver == false else { return } isGameOver = true generateFruitTimer?.invalidate() // Bomb animation: scale up then down node.run(.scale(by: 2, duration: 0.2)) { node.run(.scale(by: 0.5, duration: 0.2)) { self.health = 0 // Instant game over } } } } } } // Retry button handling override func touchesBegan(_ touches: Set, with event: UIEvent?) { for touch in touches { let position = touch.location(in: self) for node in nodes(at: position) { if node.name == "retry" { retryButton.removeFromParent() startGame() // Restart game } } } } ``` -------------------------------- ### Create Physics Bodies for Game Objects (Swift) Source: https://context7.com/reyhanl/watermelonninja/llms.txt Generates a new SKPhysicsBody with customizable properties such as gravity, damping, charge, and mass. It also assigns a random angular velocity. This function is used to create physics bodies for various game elements like fruits and bomb slices. ```swift // Physics body creation func makeBody() -> SKPhysicsBody { let body = SKPhysicsBody() body.affectedByGravity = true body.angularDamping = 0.2 body.charge = 0.2 body.allowsRotation = true body.mass = 0.2 body.angularVelocity = .random(in: -1...1) return body } ``` -------------------------------- ### Generate Game Objects (Swift) Source: https://context7.com/reyhanl/watermelonninja/llms.txt Generates and animates random game objects, such as fruits or bombs, with physics-based trajectories. This function is called periodically by a timer to keep the game dynamic. It determines the type and initial physics properties of spawned objects. ```swift // Fruit generation mechanism func generateFruitExample() { let scene = GameScene() // Called every 1 second by timer scene.generateFruit() // Generates 0-2 objects per tick for _ in 0...Int.random(in: 0...2) { let type = Int.random(in: 0...3) let x = CGFloat.random(in: -scene.width / 2...scene.width / 2) let position = CGPoint(x: x, y: -scene.height / 2) var node: SKNode if type == 0 { // 25% chance - Bomb node = scene.makeBomb(at: position) } else { // 75% chance - Fruit node = scene.makeWatermelon(at: position) } scene.addChild(node) scene.animateFruit(node: node) // Physics body applies velocity: // dx: random in range [-width/2, width/2] // dy: height + height/2 (upward launch) // Angular velocity: random rotation } } ``` -------------------------------- ### Animate Heart Destruction on Health Loss (Swift) Source: https://context7.com/reyhanl/watermelonninja/llms.txt Handles the visual animation when a heart is destroyed due to health loss. It creates two slice sprites (left and right) that mimic the fruit slicing animation and applies physics to them. This provides visual feedback to the player about losing a life. ```swift // Heart destruction animation func executeHealth(node: SKNode) { guard let heartNode = node as? Heart, !heartNode.isEmpty else { return } heartNode.isEmpty = true // Create split heart animation similar to fruit slicing let leftSlice = SKSpriteNode(imageNamed: "heart.sliceLeft") leftSlice.size = heartNode.frame.size leftSlice.position = heartNode.position leftSlice.physicsBody = makeBody() leftSlice.physicsBody?.velocity.dx = -nodeSize / 2 addChild(leftSlice) let rightSlice = SKSpriteNode(imageNamed: "heart.sliceRight") rightSlice.size = heartNode.frame.size rightSlice.position = heartNode.position rightSlice.physicsBody = makeBody() rightSlice.physicsBody?.velocity.dx = nodeSize / 2 addChild(rightSlice) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.