You need to enable JavaScript to run this app. 求教如何在Swift Playgrounds中使用SpriteKit制作多选游戏
优惠活动
大模型
产品
解决方案
定价
更多

求教如何在Swift Playgrounds中使用SpriteKit制作多选游戏

SpriteKit 纯框架实现多选游戏的可运行方案(适配Swift Playgrounds)

实现核心原则

所有界面元素、交互逻辑完全依托SpriteKit原生能力实现,全程不引入UIKit相关的视图、控制器组件,可直接在Swift Playgrounds的实时预览环境中运行。

第一步:基础Playgrounds运行模板

先搭建可以触发实时预览的最小骨架,不需要额外配置项目:

import SpriteKit
import PlaygroundSupport

// 主游戏场景
class MultiSelectGameScene: SKScene {
    // 后续补充游戏逻辑
}

// 初始化SpriteKit视图,绑定到Playgrounds实时画布
let sceneView = SKView(frame: CGRect(x: 0, y: 0, width: 750, height: 1334))
let scene = MultiSelectGameScene(size: CGSize(width: 750, height: 1334))
scene.scaleMode = .aspectFit
sceneView.presentScene(scene)
PlaygroundPage.current.liveView = sceneView

第二步:自定义可复用多选选项组件

每个选项都是独立的SpriteKit节点,自带选中状态切换、触摸响应能力,完全替代UIButton的功能:

// 多选选项节点,纯SpriteKit元素
class SelectOptionNode: SKSpriteNode {
    let optionID: String
    var isSelected: Bool = false {
        didSet {
            // 视觉反馈切换
            self.color = isSelected ? .systemBlue : .darkGray
            optionLabel.fontColor = isSelected ? .white : .lightGray
            // 轻微缩放的点击动效
            self.run(.scale(to: 0.95, duration: 0.1))
        }
    }
    private let optionLabel = SKLabelNode(fontNamed: "Arial")

    init(optionID: String, text: String, position: CGPoint) {
        self.optionID = optionID
        super.init(texture: nil, color: .darkGray, size: CGSize(width: 300, height: 60))
        self.position = position
        self.isUserInteractionEnabled = true
        // 配置选项文字
        optionLabel.text = text
        optionLabel.fontSize = 20
        optionLabel.verticalAlignmentMode = .center
        addChild(optionLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // SpriteKit原生触摸响应,替代UIButton点击逻辑
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        isSelected.toggle()
        (scene as? MultiSelectGameScene)?.updateSelectedOptions(id: optionID, selected: isSelected)
    }
}

第三步:场景层的多选逻辑与结果判定

在之前的MultiSelectGameScene类中补充全流程游戏逻辑,实现题目展示、选项选择、答案判定的完整流程:

// 主游戏场景
class MultiSelectGameScene: SKScene {
    // 记录当前选中的选项ID集合
    var selectedOptionIDs: Set<String> = []
    private var submitButton: SKSpriteNode!

    override func didMove(to view: SKView) {
        backgroundColor = .black
        // 添加题干
        let questionLabel = SKLabelNode(text: "以下哪些是Swift的内置关键字?(可多选)")
        questionLabel.position = CGPoint(x: 0, y: 300)
        questionLabel.fontSize = 24
        questionLabel.fontColor = .white
        addChild(questionLabel)

        // 批量渲染选项
        let optionList = ["A. var", "B. func", "C. print", "D. UIViewController"]
        for (index, text) in optionList.enumerated() {
            let optionID = String(text.split(separator: ".").first!)
            let position = CGPoint(x: 0, y: 200 - CGFloat(index * 80))
            addChild(SelectOptionNode(optionID: optionID, text: text, position: position))
        }

        // 初始化提交按钮
        submitButton = SKSpriteNode(color: .systemGreen, size: CGSize(width: 200, height: 50))
        submitButton.position = CGPoint(x: 0, y: -250)
        submitButton.isUserInteractionEnabled = true
        let submitLabel = SKLabelNode(text: "提交答案")
        submitLabel.verticalAlignmentMode = .center
        submitLabel.fontColor = .white
        submitButton.addChild(submitLabel)
        addChild(submitButton)
    }

    // 更新选中状态集合
    func updateSelectedOptions(id: String, selected: Bool) {
        if selected {
            selectedOptionIDs.insert(id)
        } else {
            selectedOptionIDs.remove(id)
        }
    }

    // 处理提交按钮的触摸判定
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let location = touch.location(in: self)
        // 命中提交按钮时触发判定
        if submitButton.contains(location) {
            let correctAnswer: Set<String> = ["A", "B"]
            let feedbackLabel: SKLabelNode
            if selectedOptionIDs == correctAnswer {
                feedbackLabel = SKLabelNode(text: "回答正确!")
                feedbackLabel.fontColor = .systemGreen
            } else {
                feedbackLabel = SKLabelNode(text: "回答错误,正确答案为A、B")
                feedbackLabel.fontColor = .systemRed
            }
            feedbackLabel.position = CGPoint(x: 0, y: -180)
            addChild(feedbackLabel)
            // 1.5秒后自动清除反馈
            feedbackLabel.run(.sequence([
                .wait(forDuration: 1.5),
                .removeFromParent()
            ]))
        }
    }
}

落地注意事项

  • 全程没有引入任何UIKit的视图控制器、控件组件,所有交互完全由SpriteKit的节点响应链处理,符合避开UIController的需求
  • 场景尺寸适配iPad竖屏比例,在Playgrounds实时视图中不会出现布局错位
  • 可以直接通过SKAction给节点添加点击反馈、转场动效,不需要依赖其他框架
  • 答案判定逻辑通过Set集合的等值比对实现,不需要复杂的状态管理,在Playgrounds沙盒环境中可直接运行

内容的提问来源于stack exchange,提问作者Classic Boat 2.0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 14:06:03