Last active
September 18, 2023 21:05
-
-
Save markjamesm/08bf727b1113d4989e59f7073697dc17 to your computer and use it in GitHub Desktop.
Deck of cards model in Swift 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Deck of cards model in Swift 5. | |
// Run in Swift playgrounds | |
// Value of AKQJ needs to be changed. | |
import Foundation | |
enum CardSuits: String, CaseIterable { | |
case Hearts = "Hearts" | |
case Spades = "Spades" | |
case Clubs = "Clubs" | |
case Diamonds = "Diamonds" | |
} | |
enum CardValue: Int, CaseIterable { | |
case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king | |
// case jack, queen, king, ace | |
} | |
struct PlayingCard { | |
var cardValue: CardValue | |
var cardSuit: CardSuits | |
init(value: CardValue, suit: CardSuits) | |
{ | |
self.cardValue = value | |
self.cardSuit = suit | |
} | |
func cardName() { | |
print("\(cardValue) of \(cardSuit)") | |
} | |
} | |
class CardDeck { | |
var cardsRemaining: Int | |
var deck: [PlayingCard] | |
init() { | |
cardsRemaining = 52 | |
deck = [] | |
} | |
func createDeck() { | |
for suit in CardSuits.allCases { | |
for value in CardValue.allCases { | |
deck.append(PlayingCard(value: value, suit: suit)) | |
} | |
} | |
} | |
func listDeck() { | |
var count = 0 | |
for card in deck { | |
print(card) | |
count += 1 | |
} | |
print(count) | |
} | |
func shuffleDeck() { | |
deck.shuffle() | |
} | |
func drawCard() { | |
// let cardDrawn = deck.randomElement()! | |
guard let cardDrawn = deck.popLast() else { | |
print("No cards left in deck!") | |
return | |
} | |
// deck.remove(at: cardDrawn) | |
if self.cardsRemaining >= 1 { | |
self.cardsRemaining -= 1 | |
print("You drew:") | |
print(cardDrawn.cardName()) | |
print(cardsRemaining) | |
} | |
else { | |
print("No cards left in deck!") | |
} | |
} | |
} | |
// Create our deck, shuffle it, and then draw a card. | |
var deck = CardDeck() | |
deck.createDeck() | |
deck.shuffleDeck() | |
deck.drawCard() | |
// Optional functionality | |
//deck.listDeck() | |
//deck.cardsRemaing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment