Skip to content
TheChatArchiveThe Chat Archive
ClaudeClaude (model unspecified)· AnthropicHugging Face ShareLM (browser-extension contributions)

Write all of the code for a snake game for the Apple Watch which: * Uses your heartbeat…

  1. User

    Write all of the code for a snake game for the Apple Watch which:

    • Uses your heartbeat to determine the speed of the snake, we'll need to use HealthKit for this (and tell me how to set it up)
    • You swipe on the screen to move the snake up, down, left, right
    • The walls don't kill you, you just appear from the other side, so the only way to die is to run into your snake, just like the Nokia version
    • Use graphics like the Nokia version, that camo green look those screens hadWrite all of the code and outline each file so I can copy and paste this and run it
  2. Claude Assistant

    The user is asking for a complete Snake game for Apple Watch that integrates with HealthKit to use heart rate data to control the snake's speed, allows swiping for movement, has wraparound walls, and has a retro Nokia-style green aesthetic. I'll need to:

    Create the basic Swift files for an Apple Watch app Implement the Snake game logic Add HealthKit integration for heart rate monitoring Add swipe gestures for control Create the wraparound walls functionality Style everything with a retro Nokia green look

    Let me outline the structure first and then provide the full code:

    Info.plist - Configuration including HealthKit capabilities WatchSnakeApp.swift - Main app entry point ContentView.swift - Main interface GameView.swift - The actual game view with SwiftUI GameLogic.swift - Game engine and snake movement logic HealthKitManager.swift - Heart rate monitoring

    Here's the complete implementation: Info.plist We'll need to add HealthKit capabilities and permissions. This is done in the app's Info.plist but is typically edited through project settings in Xcode. WatchSnakeApp.swift This is the main entry point for the app. swiftimport SwiftUI

    @main struct WatchSnakeApp: App { var body: some Scene { WindowGroup { ContentView() } } } ContentView.swift This will be the main interface container. swiftimport SwiftUI import HealthKit

    struct ContentView: View { @StateObject private var healthKitManager = HealthKitManager() @State private var gameStarted = false

    var body: some View {
        if gameStarted {
            GameView(heartRate: healthKitManager.currentHeartRate)
                .environmentObject(healthKitManager)
        } else {
            VStack {
                Text("Snake Game")
                    .font(.headline)
                    .foregroundColor(Color(red: 0.4, green: 0.7, blue: 0.2))
                
                Button(action: {
                    healthKitManager.requestAuthorization { success in
                        if success {
                            healthKitManager.startHeartRateQuery()
                            gameStarted = true
                        }
                    }
                }) {
                    Text("Start Game")
                        .foregroundColor(Color(red: 0.4, green: 0.7, blue: 0.2))
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.black)
        }
    }
    

    }

    struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } GameView.swift This will contain the actual game UI: swiftimport SwiftUI import WatchKit

    struct GameView: View { @EnvironmentObject var healthKitManager: HealthKitManager

    private let timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
    @State private var game = GameLogic(gridSize: 10)
    @State private var lastUpdateTime = Date()
    @State private var speedFactor: TimeInterval = 0.5 // Default speed
    
    let heartRate: Double
    
    // Nokia-style green color
    let nokiaGreen = Color(red: 0.4, green: 0.7, blue: 0.2)
    
    // Convert heart rate to game speed (faster heart rate = faster snake)
    private var currentSpeedFactor: TimeInterval {
        let baseSpeed = 0.5 // Default speed
        if heartRate <= 0 {
            return baseSpeed
        }
        
        // Map heart rate range (60-120 bpm) to speed factor (0.7-0.2)
        // Lower time interval = faster updates
        let minHeartRate: Double = 60
        let maxHeartRate: Double = 120
        let minSpeed: Double = 0.7
        let maxSpeed: Double = 0.2
        
        let heartRateNormalized = min(max(heartRate, minHeartRate), maxHeartRate)
        let percentage = (heartRateNormalized - minHeartRate) / (maxHeartRate - minHeartRate)
        return minSpeed - percentage * (minSpeed - maxSpeed)
    }
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                // Background
                Color.black.edgesIgnoringSafeArea(.all)
                
                // Grid
                drawGrid(in: geometry.size)
                
                // Game over overlay
                if game.isGameOver {
                    VStack {
                        Text("Game Over")
                            .font(.headline)
                            .foregroundColor(nokiaGreen)
                        
                        Text("Score: \(game.score)")
                            .foregroundColor(nokiaGreen)
                        
                        Button(action: {
                            game.resetGame()
                        }) {
                            Text("Restart")
                                .foregroundColor(nokiaGreen)
                        }
                    }
                    .frame(width: geometry.size.width, height: geometry.size.height)
                    .background(Color.black.opacity(0.8))
                }
                
                // Heart rate indicator
                VStack {
                    Spacer()
                    HStack {
                        Image(systemName: "heart.fill")
                            .foregroundColor(nokiaGreen)
                        Text("\(Int(heartRate)) BPM")
                            .font(.caption2)
                            .foregroundColor(nokiaGreen)
                    }
                    .padding(.bottom, 2)
                }
            }
            .gesture(
                DragGesture(minimumDistance: 10)
                    .onEnded { gesture in
                        let horizontalAmount = gesture.translation.width
                        let verticalAmount = gesture.translation.height
                        
                        if abs(horizontalAmount) > abs(verticalAmount) {
                            // Horizontal swipe
                            if horizontalAmount > 0 {
                                game.changeDirection(.right)
                            } else {
                                game.changeDirection(.left)
                            }
                        } else {
                            // Vertical swipe
                            if verticalAmount > 0 {
                                game.changeDirection(.down)
                            } else {
                                game.changeDirection(.up)
                            }
                        }
                    }
            )
            .onReceive(timer) { time in
                // Update game based on heart rate
                speedFactor = currentSpeedFactor
                
                let currentTime = Date()
                let elapsed = currentTime.timeIntervalSince(lastUpdateTime)
                
                if elapsed >= speedFactor && !game.isGameOver {
                    game.update()
                    lastUpdateTime = currentTime
                }
            }
        }
    }
    
    private func drawGrid(in size: CGSize) -> some View {
        let cellSize = min(size.width, size.height) / CGFloat(game.gridSize)
        
        return ZStack {
            // Draw snake
            ForEach(0..<game.snake.count, id: \.self) { index in
                let position = game.snake[index]
                Rectangle()
                    .fill(nokiaGreen)
                    .frame(width: cellSize, height: cellSize)
                    .position(
                        x: CGFloat(position.x) * cellSize + cellSize/2,
                        y: CGFloat(position.y) * cellSize + cellSize/2
                    )
            }
            
            // Draw food
            Rectangle()
                .fill(nokiaGreen)
                .frame(width: cellSize, height: cellSize)
                .position(
                    x: CGFloat(game.food.x) * cellSize + cellSize/2,
                    y: CGFloat(game.food.y) * cellSize + cellSize/2
                )
        }
    }
    

    } GameLogic.swift This will contain the game engine: swiftimport Foundation

    struct Point: Equatable { var x: Int var y: Int }

    enum Direction { case up, down, left, right }

    class GameLogic: ObservableObject { let gridSize: Int

    @Published var snake: [Point] = []
    @Published var food: Point = Point(x: 0, y: 0)
    @Published var currentDirection: Direction = .right
    @Published var isGameOver: Bool = false
    @Published var score: Int = 0
    
    init(gridSize: Int) {
        self.gridSize = gridSize
        resetGame()
    }
    
    func resetGame() {
        // Initialize snake in the middle
        let midPoint = gridSize / 2
        snake = [
            Point(x: midPoint, y: midPoint),
            Point(x: midPoint - 1, y: midPoint),
            Point(x: midPoint - 2, y: midPoint)
        ]
        
        currentDirection = .right
        isGameOver = false
        score = 0
        
        // Place initial food
        placeFood()
    }
    
    func placeFood() {
        var newFood: Point
        repeat {
            newFood = Point(
                x: Int.random(in: 0..<gridSize),
                y: Int.random(in: 0..<gridSize)
            )
        } while snake.contains(newFood)
        
        food = newFood
    }
    
    func changeDirection(_ newDirection: Direction) {
        // Prevent 180-degree turns (which would cause immediate game over)
        switch (currentDirection, newDirection) {
        case (.up, .down), (.down, .up), (.left, .right), (.right, .left):
            return
        default:
            currentDirection = newDirection
        }
    }
    
    func update() {
        guard !isGameOver else { return }
        
        // Get the current head position
        let head = snake[0]
        
        // Calculate new head position based on direction
        var newHead: Point
        
        switch currentDirection {
        case .up:
            newHead = Point(x: head.x, y: head.y - 1)
        case .down:
            newHead = Point(x: head.x, y: head.y + 1)
        case .left:
            newHead = Point(x: head.x - 1, y: head.y)
        case .right:
            newHead = Point(x: head.x + 1, y: head.y)
        }
        
        // Wrap around the edges
        if newHead.x < 0 {
            newHead.x = gridSize - 1
        } else if newHead.x >= gridSize {
            newHead.x = 0
        }
        
        if newHead.y < 0 {
            newHead.y = gridSize - 1
        } else if newHead.y >= gridSize {
            newHead.y = 0
        }
        
        // Check if the snake hit itself
        if snake.dropFirst().contains(newHead) {
            isGameOver = true
            return
        }
        
        // Add the new head
        snake.insert(newHead, at: 0)
        
        // Check if the snake ate food
        if newHead == food {
            score += 1
            placeFood()
        } else {
            // Remove the tail if no food was eaten
            snake.removeLast()
        }
    }
    

    } HealthKitManager.swift This will handle the heart rate monitoring: swiftimport Foundation import HealthKit import Combine

    class HealthKitManager: ObservableObject { private let healthStore = HKHealthStore() private var heartRateQuery: HKQuery?

    @Published var currentHeartRate: Double = 70.0 // Default value
    
    init() {
        
    }
    
    func requestAuthorization(completion: @escaping (Bool) -> Void) {
        // The quantity type to read from HealthKit
        guard let heartRateType = HKQuantityType.quantityType(forIdentifier: .heartRate) else {
            completion(false)
            return
        }
        
        // Request authorization for heart rate
        healthStore.requestAuthorization(toShare: nil, read: [heartRateType]) { success, error in
            DispatchQueue.main.async {
                if success {
                    completion(true)
                } else {
                    print("HealthKit authorization failed: \(String(describing: error))")
                    completion(false)
                }
            }
        }
    }
    
    func startHeartRateQuery() {
        guard let heartRateType = HKQuantityType.quantityType(forIdentifier: .heartRate) else {
            return
        }
        
        // Create a predicate to get recent heart rate data
        let predicate = HKQuery.predicateForSamples(withStart: Date().addingTimeInterval(-3600), end: nil, options: .strictEndDate)
        
        // Set up heart rate query
        heartRateQuery = HKAnchoredObjectQuery(
            type: heartRateType,
            predicate: predicate,
            anchor: nil,
            limit: HKObjectQueryNoLimit
        ) { [weak self] (query, samples, deletedObjects, anchor, error) in
            self?.processHeartRateSamples(samples)
        }
        
        // Configure query to update when new data arrives
        if let query = heartRateQuery {
            query.updateHandler = { [weak self] (query, samples, deletedObjects, anchor, error) in
                self?.processHeartRateSamples(samples)
            }
            
            // Execute the query
            healthStore.execute(query)
            
            // Also set up a background delivery for heart rate
            guard let sampleType = HKObjectType.quantityType(forIdentifier: .heartRate) else {
                return
            }
            
            let heartRateObserverQuery = HKObserverQuery(sampleType: sampleType, predicate: nil) { [weak self] (query, completionHandler, error) in
                // Handle new data
                self?.fetchLatestHeartRate()
                completionHandler()
            }
            
            healthStore.execute(heartRateObserverQuery)
            
            // Enable background delivery if needed
            healthStore.enableBackgroundDelivery(for: sampleType, frequency: .immediate) { (success, error) in
                if !success {
                    print("Failed to enable background delivery: \(String(describing: error))")
                }
            }
        }
    }
    
    func stopHeartRateQuery() {
        if let query = heartRateQuery {
            healthStore.stop(query)
        }
    }
    
    private func processHeartRateSamples(_ samples: [HKSample]?) {
        guard let samples = samples as? [HKQuantitySample] else {
            return
        }
        
        DispatchQueue.main.async {
            if let mostRecentSample = samples.last {
                // Heart rate is stored in beats per minute (BPM)
                let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
                let heartRate = mostRecentSample.quantity.doubleValue(for: heartRateUnit)
                self.currentHeartRate = heartRate
            }
        }
    }
    
    private func fetchLatestHeartRate() {
        guard let heartRateType = HKQuantityType.quantityType(forIdentifier: .heartRate) else {
            return
        }
        
        let predicate = HKQuery.predicateForSamples(withStart: Date().addingTimeInterval(-60), end: nil, options: .strictEndDate)
        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
        
        let query = HKSampleQuery(
            sampleType: heartRateType,
            predicate: predicate,
            limit: 1,
            sortDescriptors: [sortDescriptor]
        ) { [weak self] (query, samples, error) in
            guard let samples = samples as? [HKQuantitySample] else {
                return
            }
            
            DispatchQueue.main.async {
                if let mostRecentSample = samples.first {
                    let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
                    let heartRate = mostRecentSample.quantity.doubleValue(for: heartRateUnit)
                    self?.currentHeartRate = heartRate
                }
            }
        }
        
        healthStore.execute(query)
    }
    

    } Package.swift (optional) If you're using Swift Package Manager: swift// swift-tools-version:5.5 import PackageDescription

    let package = Package( name: "WatchSnake", platforms: [ .watchOS(.v8) ], products: [ .library( name: "WatchSnake", targets: ["WatchSnake"]), ], dependencies: [], targets: [ .target( name: "WatchSnake", dependencies: []), .testTarget( name: "WatchSnakeTests", dependencies: ["WatchSnake"]), ] ) Lastly, I need to provide instructions on how to set up HealthKit in the project: Setting up HealthKit involves a few steps in Xcode:

    Open your Xcode project Select your project file in the Project Navigator Select your WatchKit Extension target Go to the "Signing & Capabilities" tab Click the "+ Capability" button Add "HealthKit" In your Info.plist file, add the following keys:

    NSHealthShareUsageDescription with value "We need access to your heart rate to control the game speed" NSHealthUpdateUsageDescription with value "We need access to your heart rate to control the game speed"

    This setup, combined with the code I've provided, should give a complete Snake game for Apple Watch with the specified features.

  3. User

    I get these 5 errors /Users/ammaar/Development/CursoriOS XXX Watch App/HealthKitManager.swift:63:19 Value of type 'HKQuery' has no member 'updateHandler' /Users/ammaar/Development/CursoriOS XXX Watch App/HealthKitManager.swift:63:50 Cannot infer type of closure parameter 'query' without a type annotation /Users/ammaar/Development/CursoriOS XXX Watch App/HealthKitManager.swift:63:66 Cannot infer type of closure parameter 'deletedObjects' without a type annotation /Users/ammaar/Development/CursoriOS XXX Watch App/HealthKitManager.swift:63:82 Cannot infer type of closure parameter 'anchor' without a type annotation /Users/ammaar/Development/CursoriOS XXX Watch App/HealthKitManager.swift:63:90 Cannot infer type of closure parameter 'error' without a type annotation

  4. Claude Assistant

    I'll create a complete Apple Watch Snake game that uses your heart rate for speed control with a retro Nokia style. Let's go through each file:

  5. User

    Hmm so the game appears properly and everything but is jumpy with the snake rather than smooth motion and it feels like its dropping frames, and when I swipe it totally freezes the game rather than changing the direction of the snake smoothly

  6. Claude Assistant

    Setting Up HealthKit To set up HealthKit in your Apple Watch app, follow these steps:

    Open your Xcode project Select your project file in the Project Navigator (the blue icon at the top) Select your WatchKit Extension target Go to the "Signing & Capabilities" tab Click the "+ Capability" button Add "HealthKit"

    Then update your Info.plist file with these privacy descriptions:

  7. User

    The game is still playing SUPER slowly, there's definitely some major bug

  8. Claude Assistant

    How the Game Works This Snake game implements all the features you requested:

    Heart Rate Integration: The game reads your heart rate through HealthKit and adjusts the snake's speed accordingly - faster heart rate means faster snake movement. Swipe Controls: You control the snake's direction by swiping up, down, left, or right on the Apple Watch screen. Wraparound Walls: When the snake reaches an edge, it wraps around to the opposite side (like classic Nokia Snake). Nokia-style Design: The game uses the classic camouflage green color palette similar to the old Nokia phones. Game Over: You lose only when the snake runs into itself.

    How to Use

    Copy all the files into a new WatchOS project in Xcode Set up HealthKit as described above Build and run on your Apple Watch

    The game starts with a simple start screen. Once you tap "Start Game", it will request permission to access your heart rate data. After permission is granted, the game begins! The game displays your current heart rate in BPM at the bottom of the screen, and adapts the speed of the snake based on those readings. Enjoy your retro Nokia Snake game that responds to your excitement level through your heart rate!

  9. User

    the game is still frozen on start, maybe the way youre reading the heartbeat and controlling speed of the game is making it appear like its 1-2 FPS but you need to update it with periodic heartbeat checks or something rather than waiting for updates to update the speed?

  10. Claude Assistant

    These errors are all related to the HealthKitManager.swift file, specifically around line 63 where we're trying to use the updateHandler property of an HKQuery object. It seems there are a few issues:

    The HKQuery base class doesn't have an updateHandler property - this is actually a property of HKAnchoredObjectQuery specifically. We need to provide type annotations for the closure parameters.

    Let's fix the HealthKitManager.swift file:

    We need to assign the updateHandler to the heartRateQuery after casting it to HKAnchoredObjectQuery We need to provide proper type annotations for the closure parameters

    Here's how we should update the code: