ios - 如何快速随机化一组精灵?
问题描述
每次应用程序启动时,我都想对数组中的元素进行洗牌,这些元素也应该放在屏幕上而不重复,我该怎么做?我尝试了几个扩展来打乱我的数组,但没有奏效
我正在使用 swift 4.1,这是我的代码:
import SpriteKit
struct ContainerSprite{
let block : SKSpriteNode!
let containers = ["Container_Circle_Blue","Container_Hexagone_Blue",
"Container_Square_Blue","Container_Star_Blue","Container_Triangle_Blue",
"Container_Circle_DBlue","Container_Hexagone_DBlue","Container_Square_DBlue",
"Container_Star_DBlue","Container_Triangle_DBlue","Container_Circle_Green",
"Container_Hexagone_Green","Container_Square_Green","Container_Star_Green",
"Container_Triangle_Green"]
init (numContainer: Int, row: Int, col: Int , inThisScene: GameScene) {
block = SKSpriteNode(imageNamed: containers[numContainer])
let numberOfBlocks = 12.5
let blockScale = 0.6
}
}
这是我使用的扩展之一,但是当我尝试时,它显示的元素随机重复
extension MutableCollection {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
// Change Int in the next line to IndexDistance in < Swift 4.1
let d: Int = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
let i = index(firstUnshuffled, offsetBy: d)
swapAt(firstUnshuffled, i)
}
}
}
extension Sequence {
/// Returns an array with the contents of this sequence, shuffled.
func shuffled() -> [Element] {
var result = Array(self)
result.shuffle()
return result
}
}
解决方案
推荐阅读
- javascript - 如何从满足某些条件的数组中删除项目。使用角度/打字稿
- flutter - [Flutter]Layout/Build Container 基于其兄弟部件的大小(两个部件都是 Column 的子级)
- android - jitpack - 从服务器收到状态码 521/401/403
- javascript - 除非我打开扩展开发工具,否则上下文菜单不起作用
- php - 将 JMS Serializer 与 PHPSpec 测试用例一起使用导致注释 @JMS\Serializer\Annotation\Type 不存在,或无法自动加载
- javascript - TypeError:messaging.getToken 不是函数
- informatica - Informatica Power Center - 错误:“目标表 [TABLE_NAME] 没有指定键。”
- javascript - 带有 SSR 的 Vue.js 3 中的 Vuex、watch 和生命周期钩子
- css - 滚动“触摸操作:无”区域后,移动 Chrome 不注册点击
- android - 在使用 FirebaseRecyclerPagingAdapter 时,第二次单击 RecyclerView 中的项目时,片段显示为空