Te tuhi i tetahi keemu kaari mahara ki te Swift

Te tuhi i tetahi keemu kaari mahara ki te Swift

Ko tenei tuhinga e whakaatu ana i te tukanga o te hanga i tetahi keemu whakangungu mahara ngawari e tino pai ana ahau. I tua atu i te pai ki a koe ano, ka ako koe mo nga karaehe Swift me nga tikanga ka haere koe. Engari i mua i te tiimata, kia mohio tatou ki te keemu ano.

Ka whakamahara matou: mo nga kaipānui katoa o "Habr" - he utu mo te 10 rubles i te wa e whakauru ana ki tetahi akoranga Skillbox ma te whakamahi i te waehere whakatairanga "Habr".

Ka tūtohu a Skillbox: Matauranga ipurangi "Whakawhanake Mahi Java".

Me pehea te purei Kaari Mahara

Ka timata te keemu ki te whakaaturanga o te huinga kaari. Ka takoto te kanohi ki raro (he ahua ki raro). Ka paatohia e koe tetahi, ka tuwhera te ahua mo etahi hēkona.

Ko te mahi a te kaitakaro he kimi i nga kaari katoa he rite nga pikitia. Mena, i muri i te whakatuwheratanga o te kaari tuatahi, ka huri koe i te tuarua ka rite nga pikitia, ka noho tuwhera nga kaari e rua. Ki te kore e taurite, ka kati ano nga kaari. Ko te kaupapa ko te whakatuwhera i nga mea katoa.

Te hanganga kaupapa

Hei hanga i tetahi putanga ngawari o tenei keemu ka hiahia koe ki nga waahanga e whai ake nei:

  • Kotahi te Kaiwhakahaere: GameController.swift.
  • Kotahi Tirohanga: CardCell.swift.
  • E rua nga Tauira: MemoryGame.swift me Card.swift.
  • Main.storyboard ki te whakarite kei te waatea te huinga katoa o nga waahanga.

Ka timata ma te waahanga ngawari o te keemu, ko nga kaari.

Kaari.tere

E toru nga ahuatanga o te tauira kaari: id hei tautuhi i ia mea, he taurangi boolean e whakaatuhia ana hei tohu i te mana o te kaari (huna, tuwhera ranei), me te URL mahi toi mo nga whakaahua kei runga i nga kaari.

class Card {        
    var id: String    
    var shown: Bool = false    
    var artworkURL: UIImage!
}

Ka hiahia ano koe ki enei tikanga hei whakahaere i te taunekeneke a te kaiwhakamahi me nga mapi:

Tikanga mo te whakaatu whakaahua ki runga kaari. I konei ka tautuhia nga taonga katoa ki te taunoa. Mo te id, ka whakaputahia he id matapōkere mā te karanga i te NSUIS().uuidString.

init(image: UIImage) {        
    self.id = NSUUID().uuidString        
    self.shown = false        
    self.artworkURL = image    
}

Tikanga mo te whakataurite i nga kaari ID.

func equals(_ card: Card) -> Bool {
    return (card.id == id)    
}

Tikanga ki te hanga kape o ia kaari - kia nui ake te maha o nga mea rite. Ma tenei tikanga ka whakahoki i te kaari me nga uara rite.

func copy() -> Card {        
    return Card(card: self)    
}
 
init(card: Card) {        
    self.id = card.id        
    self.shown = card.shown        
    self.artworkURL = card.artworkURL    
}

Me tetahi atu tikanga hei riwhi i nga kaari i te timatanga. Ka waiho hei toronga mo te akomanga Array.

extension Array {    
    mutating func shuffle() {        
        for _ in 0...self.count {            
            sort { (_,_) in arc4random() < arc4random() }        
        }   
    }
}

Na konei ko te whakatinanatanga o te waehere mo te tauira Kaari me nga taonga me nga tikanga katoa.

class Card {
    
    var id: String
    var shown: Bool = false
    var artworkURL: UIImage!
    
    static var allCards = [Card]()
 
    init(card: Card) {
        self.id = card.id
        self.shown = card.shown
        self.artworkURL = card.artworkURL
    }
    
    init(image: UIImage) {
        self.id = NSUUID().uuidString
        self.shown = false
        self.artworkURL = image
    }
    
    func equals(_ card: Card) -> Bool {
        return (card.id == id)
    }
    
    func copy() -> Card {
        return Card(card: self)
    }
}
 
extension Array {
    mutating func shuffle() {
        for _ in 0...self.count {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

Haere ana matou.

Ko te tauira tuarua ko MemoryGame, i konei ka whakatakotohia he matiti 4*4. Ka whai taonga te tauira penei i nga kaari (he huinga kaari kei runga i te matiti), he kaari kua whakaatuhia me nga kaari kua tuwhera, me tetahi taurangi boolean isPlaying ki te whai i te mana o te keemu.

class MemoryGame {        
    var cards:[Card] = [Card]()    
    var cardsShown:[Card] = [Card]()    
    var isPlaying: Bool = false
}

Me whakawhanake ano tatou i nga tikanga hei whakahaere i te taunekeneke a te kaiwhakamahi me te matiti.

He tikanga riwhi i nga kaari i roto i te matiti.

func shuffleCards(cards:[Card]) -> [Card] {       
    var randomCards = cards        
    randomCards.shuffle()                
 
    return randomCards    
}

Tikanga mo te hanga keemu hou. I konei ka karangahia te tikanga tuatahi ki te tiimata i te tahora tuatahi me te arawhiti i te taurangi isPlaying ki te pono.

func newGame(cardsArray:[Card]) -> [Card] {       
    cards = shuffleCards(cards: cardsArray)        
    isPlaying = true            
 
    return cards    
}

Ki te hiahia tatou ki te whakaara ano i te keemu, katahi ka tautuhia te taurangi isPlaying ki te teka ka tango i te whakatakotoranga tuatahi o nga kaari.

func restartGame() {        
    isPlaying = false                
    cards.removeAll()        
    cardsShown.removeAll()    
}

Tikanga mo te manatoko i nga kaari kua paatohia. He korero mo ia i muri mai.

func cardAtIndex(_ index: Int) -> Card? {        
    if cards.count > index {            
        return cards[index]        
    } else {            
        return nil        
    }    
}

He tikanga whakahoki i te tuunga o tetahi kaari motuhake.

func indexForCard(_ card: Card) -> Int? {        
    for index in 0...cards.count-1 {            
        if card === cards[index] {                
            return index            
        }      
    }
        
    return nil    
}

Te arowhai i te tutukitanga o te kaari kua tohua me te paerewa.

func unmatchedCardShown() -> Bool {
    return cardsShown.count % 2 != 0
}

Ka panuitia e tenei tikanga te huānga whakamutunga i te rarangi **cardsShown** ka whakahoki i te kaari kore-rite.

func didSelectCard(_ card: Card?) {        
    guard let card = card else { return }                
    
    if unmatchedCardShown() {            
        let unmatched = unmatchedCard()!                        
        
        if card.equals(unmatched) {          
            cardsShown.append(card)            
        } else {                
            let secondCard = cardsShown.removeLast()      
        }                    
    } else {            
        cardsShown.append(card)        
    }                
    
    if cardsShown.count == cards.count {            
        endGame()        
    }    
}

Main.papakōrero me GameController.swift

He penei te ahua o Main.storyboard:

Te tuhi i tetahi keemu kaari mahara ki te Swift

I te tuatahi, me whakarite e koe te keemu hou hei viewDidLoad i roto i te kaiwhakahaere, tae atu ki nga whakaahua mo te matiti. I roto i te keemu, ka whakaatuhia enei mea katoa e 4*4 collectionView. Mena kaore koe i te mohio ki te collectionView, koinei ka taea e koe te tiki i nga korero e hiahia ana koe.

Ka whirihorahia e matou te GameController hei kaiwhakahaere pakiaka o te tono. Ko te GameController he kohingaTirohanga ka kiia e matou he IBOutlet. Ko tetahi atu korero mo te paatene IBAction onStartGame(), he UIButton tenei, ka kite koe i te papa korero e kiia nei ko PLAY.

He iti mo te whakatinanatanga o nga kaiwhakahaere:

  • Tuatahi, ka arawhitia e rua nga mea matua - te matiti: keemu = MemoryGame(), me te huinga kaari: kaari = [Kari]().
  • Ka tautuhia nga taurangi tuatahi hei viewDidLoad, koinei te tikanga tuatahi e kiia ana i te wa e rere ana te keemu.
  • Ko te collectionView kua tautuhia ki te huna na te mea kua huna nga kaari katoa kia pehia e te kaiwhakamahi te PLAY.
  • Ka pehi ana matou i te PLAY, ka timata te waahanga onStartGame IBAction, ka whakatauhia e matou te kohingaTirohanga isHidden taonga ki te teka kia kitea ai nga kaari.
  • Ia wa ka kowhiri te kaiwhakamahi i tetahi kaari, ka karangahia te tikanga didSelectItemAt. I roto i te tikanga ka karanga matou didSelectCard ki te whakatinana i te arorau keemu matua.

Anei te whakatinanatanga GameController whakamutunga:

class GameController: UIViewController {
 
    @IBOutlet weak var collectionView: UICollectionView!
    
    let game = MemoryGame()
    var cards = [Card]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        game.delegate = self
        
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.isHidden = true
        
        APIClient.shared.getCardImages { (cardsArray, error) in
            if let _ = error {
                // show alert
            }
            
            self.cards = cardsArray!
            self.setupNewGame()
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        if game.isPlaying {
            resetGame()
        }
    }
    
    func setupNewGame() {
        cards = game.newGame(cardsArray: self.cards)
        collectionView.reloadData()
    }
    
    func resetGame() {
        game.restartGame()
        setupNewGame()
    }
    
    @IBAction func onStartGame(_ sender: Any) {
        collectionView.isHidden = false
    }
}
 
// MARK: - CollectionView Delegate Methods
extension GameController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cards.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CardCell", for: indexPath) as! CardCell
        cell.showCard(false, animted: false)
        
        guard let card = game.cardAtIndex(indexPath.item) else { return cell }
        cell.card = card
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! CardCell
        
        if cell.shown { return }
        game.didSelectCard(cell.card)
        
        collectionView.deselectItem(at: indexPath, animated:true)
    }
}

Inaianei me korero iti mo nga tikanga whakahirahira.

Nga kawa

Ko te mahi me nga kawa te kaupapa matua o te kaupapa Swift. Ko nga kawa e whakarato ana i te kaha ki te tautuhi ture mo te karaehe, te hanganga, te tatau ranei. Ma tenei maataapono ka taea e koe te tuhi i nga waehere taapiri me te taapiri. Inaa, he tauira tenei kei te whakatinanahia e matou mo te collectionView i GameController. Inaianei me hanga ta tatou ake putanga. Ka penei te ahua o te syntax:

protocol MemoryGameProtocol {
    //protocol definition goes here
}

E mohio ana tatou ka taea e te kawa te tautuhi i nga ture, i nga tohutohu ranei mo te whakatinana i te karaehe, no reira me whakaaro tatou me pehea. E wha katoa e hiahia ana koe.

  • Tīmata kēmu: memoryGameDidStart.
  • Me tahuri koe ki raro i te kaari: memoryGameShowCards.
  • Me tahuri koe ki raro i te kaari: memoryGameHideCards.
  • Mutunga keemu: memoryGameDidEnd.

Ka taea te whakatinana i nga tikanga e wha mo te akomanga matua, ko te GameController.

memoryGameDidStart

Ina whakahaerea tenei tikanga, me timata te keemu (ka pehi te kaiwhakamahi i te PLAY). I konei ka utaina ano e matou nga korero ma te waea atu ki te collectionView.reloadData(), ka riwhi i nga kaari.

func memoryGameDidStart(_ game: MemoryGame) {
    collectionView.reloadData()
}

memoryGameShowKari

Ka kiia tenei tikanga mai i te kohingaSDViewSelectItemAt. Tuatahi ka whakaatu i te kaari kua tohua. Katahi ka tirohia mena he kaari kaore i rite i roto i nga kaari e whakaatuhia ana (mehemea he rereke te maha o nga kaari e whakaatuhia ana). Mena he kotahi, ka whakatauritehia te kaari kua tohua ki a ia. Mena he rite nga pikitia, ka taapirihia nga kaari e rua ki nga kaariKa whakaatuhia ka noho kanohi ki runga. Mena he rereke, ka waiho nga kaari ka whakaatuhia, ka huri kanohi ki raro.

memoryGameHideKari

Ki te kore e taurite nga kaari, ka kiia tenei tikanga ka huna nga whakaahua kaari.

whakaaturia = teka.

memoryGameDidEnd

Ina karangahia tenei tikanga, ko te tikanga kua hurahia nga kaari katoa kei roto i nga kaariKa whakaatuhia te raarangi: cardsShown.count = cards.count, no reira kua mutu te keemu. Ka karangahia te tikanga i muri i ta matou karangatanga endGame() ki te tautuhi i te isPlaying var ki te teka, muri iho ka whakaatuhia te karere mutunga keemu. Ka whakamahia hoki te alertController hei tohu mo te kaiwhakahaere. Ka karangahia te viewDidDisappear ka tautuhi ano te keemu.

Anei te ahua o te katoa i GameController:

extension GameController: MemoryGameProtocol {
    func memoryGameDidStart(_ game: MemoryGame) {
        collectionView.reloadData()
    }
 
 
    func memoryGame(_ game: MemoryGame, showCards cards: [Card]) {
        for card in cards {
            guard let index = game.indexForCard(card)
                else { continue
            }        
            
            let cell = collectionView.cellForItem(
                at: IndexPath(item: index, section:0)
            ) as! CardCell
 
            cell.showCard(true, animted: true)
        }
    }
 
    func memoryGame(_ game: MemoryGame, hideCards cards: [Card]) {
        for card in cards {
            guard let index = game.indexForCard(card)
                else { continue
            }
            
            let cell = collectionView.cellForItem(
                at: IndexPath(item: index, section:0)
            ) as! CardCell
    
            cell.showCard(false, animted: true)
        }
    }
 
    func memoryGameDidEnd(_ game: MemoryGame) {
        let alertController = UIAlertController(
            title: defaultAlertTitle,
            message: defaultAlertMessage,
            preferredStyle: .alert
        )
 
        let cancelAction = UIAlertAction(
            title: "Nah", style: .cancel) {
            [weak self] (action) in
            self?.collectionView.isHidden = true
        }
 
        let playAgainAction = UIAlertAction(
            title: "Dale!", style: .default) {
            [weak self] (action) in
            self?.collectionView.isHidden = true
 
            self?.resetGame()
        }
 
        alertController.addAction(cancelAction)
        alertController.addAction(playAgainAction)
        
        self.present(alertController, animated: true) { }
    
        resetGame()
    }
}

Te tuhi i tetahi keemu kaari mahara ki te Swift
Inaa, heoi ano. Ka taea e koe te whakamahi i tenei kaupapa ki te hanga i to ake putanga o te keemu.

Kia hari te whakawaehere!

Ka tūtohu a Skillbox:

Source: will.com

Tāpiri i te kōrero