2021-09-22可以翻转备份

MemorizeApp.swift----------------

import SwiftUI

@main
struct MemorizeApp: App {
    let game = EmojiMemoryGame()
    var body: some Scene {
        WindowGroup {
            ContentView(viewModel: game)
        }
    }
}

ContentView.swift -------------------

import SwiftUI

struct ContentView: View {
    @ObservedObject var viewModel: EmojiMemoryGame
    var body: some View {
        VStack {
            ScrollView {
                LazyVGrid(columns: [GridItem(.adaptive(minimum: 65))]){
                    ForEach(viewModel.cards) { card in
                        CardView(card: card).aspectRatio(2/3, contentMode: .fit)
                            .onTapGesture {
                                viewModel.choose(card)
                            }
                    }
                }
            }
            .foregroundColor(.red)
        }
        .padding(.horizontal)
        
    }
}

struct CardView: View {
    var card: MemoryGame.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 {
                shape.fill()
            }
        }
       
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let game = EmojiMemoryGame()
        ContentView(viewModel: game)
            .preferredColorScheme(/*@START_MENU_TOKEN@*/.dark/*@END_MENU_TOKEN@*/)
        ContentView(viewModel: game)
            .preferredColorScheme(.light)
    }
}

MemoryGame.swift-------------

import Foundation

struct MemoryGame {
    var cards: Array
    
    mutating func choose(_ card: Card) {
        let chosenIndex = index(of: card)
        cards[chosenIndex].isFaceUp.toggle()
        
        func index(of card: Card) -> Int {
            for index in 0.. CardContent) {
        cards = Array()
        for pairIndex in 0..

EmojiMemoryGame.swift

import SwiftUI

class EmojiMemoryGame: ObservableObject {
    static var emojis = ["", "", "⛱", "", "", "", "", "⏱", "☎️", "","","", "✈️"]
    @Published var model: MemoryGame = makeMemoryGame()
    
    static func makeMemoryGame() -> MemoryGame {
        MemoryGame(numberOfPairOfCards: 4){ pairIndex in emojis[pairIndex]}
    }
    
    func choose(_ card: MemoryGame.Card) {
        model.choose(card)
    }
    
    var cards: Array.Card> {
        return model.cards
    }
}

你可能感兴趣的:(2021-09-22可以翻转备份)