美文网首页
2022-04-14 翻面之前

2022-04-14 翻面之前

作者: 脑子 | 来源:发表于2022-04-14 04:38 被阅读0次

ContentView

import SwiftUI


struct ContentView: View {
    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)
                    }
                }
            }
            .foregroundColor(.red)
        
        }
        .padding(.horizontal)
        
    }
    
}

struct CardView: View {
    var card: MemoryGame<String>.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

import Foundation

struct MemoryGame<CardContent> {
    var cards: Array<Card>
    
    func choose(_ card: Card) {
        
    }
    
    init(numberOfPairsOfCards: Int, createCardContent: (Int) -> CardContent) {
        cards = []
        for pairIndex in 0..<numberOfPairsOfCards {
            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: Bool = false
        var isMatched: Bool = false
        var content: CardContent
        var id: Int
    }
}

EmojiMemoryGame

import SwiftUI


class EmojiMemoryGame {
    static var emojis = ["🚙", "🚗", "⛱", "🎡", "🪝", "🗿", "🛖", "⏱", "☎️", "🎰","🚜","🛴", "✈️"]
    
    static func makeMemoryGame() -> MemoryGame<String> {
        MemoryGame<String>(numberOfPairsOfCards: 4){pairIndex in
             emojis[pairIndex]
        }
    }
    var model: MemoryGame<String> = makeMemoryGame()
    
    var cards: Array<MemoryGame<String>.Card> {
        model.cards
    }
}

相关文章

网友评论

      本文标题:2022-04-14 翻面之前

      本文链接:https://www.haomeiwen.com/subject/ksnzsrtx.html