// EmojiMemoryGameView.swift
// Memorize
//
// Created by on 2021/7/15.
// #View
import SwiftUI
struct EmojiMemoryGameView: View {
@ObservedObject var game: EmojiMemoryGame
var body: some View {
ScrollView {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 65))]){
ForEach(game.cards) { card in
CardView(card: card).aspectRatio(2/3, contentMode: .fit)
.onTapGesture {
game.choose(card)
}
}
}
}
.foregroundColor(.red)
.padding(.horizontal)
}
}
struct CardView: View {
var card: EmojiMemoryGame.Card
var body: some View {
ZStack {
let shape = RoundedRectangle(cornerRadius: 20)
if card.isFaceUp {
shape.fill().foregroundColor(.white)
shape.strokeBorder(lineWidth: 3)
Text(card.content).font(.largeTitle)
} else if card.isMatched {
shape.opacity(0)
} else {
shape.fill()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let game = EmojiMemoryGame()
EmojiMemoryGameView(game: game)
.preferredColorScheme(/*@START_MENU_TOKEN@*/.dark/*@END_MENU_TOKEN@*/)
EmojiMemoryGameView(game: game)
.preferredColorScheme(.light)
}
}
// EmojiMemoryGame.swift
// Memorize
//
// Created by on 2022/4/5.
//
import SwiftUI
class EmojiMemoryGame: ObservableObject {
typealias Card = MemoryGame<String>.Card
private static var emojis = ["🚙", "🚗", "⛱", "🎡", "🪝", "🗿", "🛖", "⏱", "☎️", "🎰","🚜","🛴", "✈️"]
private static func makeMemoryGame() -> MemoryGame<String> {
MemoryGame<String>(numberOfPairOfCards: 4) {pairIndex in emojis[pairIndex]}
}
@Published private var model = makeMemoryGame()
var cards: Array<Card> {
model.cards
}
//MARK: - Intent(s)
func choose(_ card: Card) {
model.choose(card)
}
}
// MemoryGame.swift
// Memorize
//
// Created by on 2022/4/3.
//
import Foundation
struct MemoryGame<CardContent> where CardContent: Equatable {
private(set) var cards: Array<Card>
private var indexOfTheOneAndOnlyFaceUpCard: Int?
mutating func choose(_ card: Card){
if let chosenIndex = cards.firstIndex(where: {$0.id == card.id}),
!cards[chosenIndex].isMatched,
!cards[chosenIndex].isFaceUp
{
if let potentialMatchIndex = indexOfTheOneAndOnlyFaceUpCard {
if cards[chosenIndex].content == cards[potentialMatchIndex].content {
cards[chosenIndex].isMatched = true
cards[potentialMatchIndex].isMatched = true
}
indexOfTheOneAndOnlyFaceUpCard = nil
} else {
for index in cards.indices {
cards[index].isFaceUp = false
}
indexOfTheOneAndOnlyFaceUpCard = chosenIndex
}
cards[chosenIndex].isFaceUp.toggle()
}
}
init(numberOfPairOfCards: Int, createCardContent: (Int) -> CardContent) {
cards = []
for pairIndex in 0..<numberOfPairOfCards {
let content = createCardContent(pairIndex)
cards.append(Card(content: content, id: pairIndex*2))
cards.append(Card(content: content, id: pairIndex*2+1))
}
}
struct Card: Identifiable {
var isFaceUp = false
var isMatched = false
let content: CardContent
let id: Int
}
}
import SwiftUI
@main
struct MemorizeApp: App {
private let game = EmojiMemoryGame()
var body: some Scene {
WindowGroup {
EmojiMemoryGameView(game: game)
}
}
}
网友评论