This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
2
Trouble Shuffling Emojis in Memorize Game (CS193p)
Post Body
Hi everyone!
Iām currently working on the Memorize game from CS193p, and I've hit a snag with shuffling the emojis for the card game. Here's the relevant code snippet:
import SwiftUI
struct ContentView: View {
enum Theme: String{
case weather = "Weather"
case ocean = "Ocean"
case gaming = "Gaming"
}
@State var currentTheme: Theme = Theme.ocean
var emojis: [String] {
switch currentTheme {
case Theme.weather:
return ["āļø", "š§ļø", "š", "āļø"]
.flatMap { Array(repeating: $0, count: 4) }
case Theme.ocean:
return ["š ", "š", "š¬", "š¦"]
.flatMap { Array(repeating: $0, count: 4) }
case Theme.gaming:
return ["š®", "š¹ļø", "š²", "š"]
.flatMap { Array(repeating: $0, count: 4) }
}
}
var body: some View {
VStack {
VStack {
title
ScrollView {
cards
.foregroundColor(.orange)
}
Spacer()
themeChoosingBtns
}
}
.padding()
}
var title: some View {
Text("Memorize!")
.fontWeight(.semibold)
.font(.largeTitle)
}
var cards : some View {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 70))]){
ForEach(0..<emojis.count, id: \.self) { index in
CardView(content: emojis[index])
.aspectRatio(2/3, contentMode: .fit)
}
}
}
var themeChoosingBtns: some View {
HStack (spacing: 30) {
themeChangerView(theme: .weather, icon: "cloud.fill")
themeChangerView(theme: .ocean, icon: "fish.fill")
themeChangerView(theme: .gaming, icon: "gamecontroller.fill")
}
}
func themeChangerView(theme: Theme, icon: String) -> some View {
VStack{
Button {
currentTheme = theme
} label: {
Image(systemName: icon)
.scaledToFit()
.font(.largeTitle)
.frame(height: 40)
}
Text(theme.rawValue)
}
}
}
struct CardView: View {
@State var isFaceUp = true
let content: String
var body: some View {
let base = RoundedRectangle(cornerRadius: 12.0)
ZStack {
Group {
base.fill(.white)
base.strokeBorder(style: StrokeStyle(lineWidth: 2))
Text(content).font(.largeTitle)
}
.opacity(isFaceUp ? 1 : 0)
base.fill(.opacity(isFaceUp ? 0 : 1))
}
.onTapGesture {
isFaceUp.toggle()
}
}
}
#Preview {
ContentView()
}
The above code gives me this
As you can see there is the correct amount of emojis. However when I add a .shuffled() after the flatMap I get this.
How can I fix this issue? Is the way I'm setting the emojis wrong?
Post Details
We try to extract some basic information from the post title. This is not
always successful or accurate, please use your best judgement and compare
these values to the post title and body for confirmation.
- Posted
- 1 month ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/swift/comme...