Skip to content

Instantly share code, notes, and snippets.

@davidseek
Last active January 18, 2021 22:49
Show Gist options
  • Save davidseek/bcaf77c1650ae27c2840ad35b5e876db to your computer and use it in GitHub Desktop.
Save davidseek/bcaf77c1650ae27c2840ad35b5e876db to your computer and use it in GitHub Desktop.
Game.swift
typealias WholeCards = (left: Card, right: Card)
struct Game {
// The whole card are your left and your right hand.
var wholeCards: WholeCards = (.none, .none) {
didSet {
// We're printing the new cards to debug the ML models.
print("New wholeCards: ", wholeCards)
}
}
// MARK: - Public
// Sets the left whole card for the player
mutating public func setLeftWholeCard(_ face: String, _ suite: String) {
// We first need to make sure, that the ML model recognizes valid elements.
// If we for example got a `D` as Face, we'd not get a valid Face case.
guard let face = Card.Face(rawValue: face),
let suite = Card.Suite(rawValue: suite) else {
// MARK: - TODO, handle appropriately
return
}
// Initate a new card for Face/Suite
let card = Card(face, suite)
// Since we're using SwiftUI, we want to be as efficient as possible.
// Therefore we're only updating the card, if the card changed.
guard wholeCards.left != card else { return }
wholeCards.left = card
}
// Same as above for the left whole card, just on the right.
mutating public func setRightWholeCard(_ face: String, _ suite: String) {
...
}
}
struct Card: CustomStringConvertible, Equatable {
// Overwriting the description to get a decent print log
var description: String {
// Example the King of hearts: `Kh`
return "\(face.rawValue)\(suite.rawValue)"
}
// All possible faces
enum Face: String {
case A = "A"
case K = "K"
case Q = "Q"
case J = "J"
case T = "10"
case Nine = "9"
case Eight = "8"
case Seven = "7"
case Six = "6"
case Five = "5"
case Four = "4"
case Three = "3"
case Two = "2"
case None
}
// All possible suites
enum Suite: String {
case Clubs = "c"
case Hearts = "h"
case Spades = "s"
case Diamonds = "d"
case None
}
let face: Face
let suite: Suite
init(_ face: Face, _ suite: Suite) {
self.face = face
self.suite = suite
}
// MARK: - Public
public func get(_ face: String, _ suite: String) -> Card {
return Card(
Face(rawValue: face)!,
Suite(rawValue: suite)!
)
}
// MARK: - Static
// For easy access in SwiftUI previews
static var none: Card {
return Card(
.None,
.None
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment