You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift记忆游戏中如何固定随机选中的字典数组主题

解决Swift Concentration游戏主题随机但保持一致的问题

嘿,我来帮你搞定这个问题!你现在遇到的核心问题是:每次调用emoji(for:)函数时,都会重新生成randomThemeIndex,这就导致每次点击卡片都随机切换了主题,自然所有卡片没法保持同一套表情了。

解决方案思路

把主题的随机选择逻辑从函数内部移到类的初始化阶段,用一个实例变量存储选中的主题,这样整个游戏运行过程中只会选一次主题,所有卡片都从这个固定主题里取表情。

修改后的完整代码

var themeChoices = ["halloween": ["👻", "🎃", "💀", "😈", "🦇", "🍬", "🍎", "🕷️", "🕸️", "🌙"], 
                    "animals": ["🐶", "🐱", "🐭", "🐷", "🐮", "🐔", "🐸", "🐵", "🐺", "🐰"], 
                    "faces": ["😀", "😆", "😜", "😎", "😋", "😢", "😡", "😱", "😴", "😳"], 
                    "nature": ["🌲", "🌸", "🌺", "🌻", "🌼", "🌷", "🍀", "🍁", "🔥", "❄️"], 
                    "food": ["🍎", "🍌", "🍕", "🍔", "🍟", "🍦", "🍰", "🍗", "🍓", "🍇"], 
                    "sports": ["⚽️", "🏀", "🏈", "⚾️", "🎾", "⛳️", "🏊", "🚴", "🏃", "🏋️"]]
var emoji = [Int:String]()
// 新增:存储当前选中的主题,全局唯一
var currentTheme: [String]!

// 在类初始化时完成主题的随机选择
init() {
    let themeCount = themeChoices.count
    let randomThemeIndex = Int(arc4random_uniform(UInt32(themeCount)))
    currentTheme = Array(themeChoices.values)[randomThemeIndex]
}

func emoji(for card: Card) -> String {
    if emoji[card.identifier] == nil, currentTheme.count > 0 {
        // 这里直接用currentTheme.count即可,arc4random_uniform会生成0到count-1的随机数
        let randomCardIndex = Int(arc4random_uniform(UInt32(currentTheme.count)))
        emoji[card.identifier] = currentTheme.remove(at: randomCardIndex)
    }
    return emoji[card.identifier] ?? "?"
}

关键修改点说明

  • 新增currentTheme变量:作为类的属性,专门存储选中的主题,确保整个游戏过程中主题不变。
  • 初始化时选主题:把主题随机选择的逻辑放到init()方法里,只执行一次,避免每次调用表情函数都重新选主题。
  • 修正随机索引逻辑:原来的randomCardIndex用了count - 1,其实arc4random_uniform(UInt32(currentTheme.count))已经会生成0到count-1的合法索引,不用额外减1,更准确。

这样修改后,游戏启动时会随机选一个主题,所有卡片的表情都会从这个主题里选取,不会再出现点击换主题的问题啦!

内容的提问来源于stack exchange,提问作者Neemaximo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:50:42