snake in swift in swift

Here's a basic implementation of the Snake game in Swift using SpriteKit:

main.swift
import SpriteKit

class GameScene: SKScene {

    let snake = SKShapeNode(rectOf: CGSize(width: 20, height: 20))
    var direction = "right"
    let moveAmount = 20.0

    override func didMove(to view: SKView) {

        // set up the snake
        snake.fillColor = .white
        addChild(snake)

        // start moving the snake
        let moveAction = SKAction.run(move)
        let delayAction = SKAction.wait(forDuration: 0.1)
        let sequenceAction = SKAction.sequence([moveAction, delayAction])
        let repeatAction = SKAction.repeatForever(sequenceAction)
        run(repeatAction)

    }

    func move() {
        switch direction {

        case "up":
            snake.position.y += CGFloat(moveAmount)

        case "down":
            snake.position.y -= CGFloat(moveAmount)

        case "left":
            snake.position.x -= CGFloat(moveAmount)

        case "right":
            snake.position.x += CGFloat(moveAmount)

        default:
            break

        }
    }

    override func keyDown(with event: NSEvent) {

        switch event.keyCode {

        case 126: // up arrow
            direction = "up"

        case 125: // down arrow
            direction = "down"

        case 123: // left arrow
            direction = "left"

        case 124: // right arrow
            direction = "right"

        default:
            break

        }
    }
}
1394 chars
67 lines

This code sets up a rectangular SKShapeNode to represent the snake, and uses a simple switch statement to move it in response to arrow key inputs. The movement is achieved by adjusting the node's position property.

Note that this example doesn't include collision detection or any real gameplay logic beyond moving the snake, but it provides a starting point for building a more complete game.

gistlibby LogSnag