Schafkopf-Server/Sources/App/Model/Card/Card.swift

92 lines
1.8 KiB
Swift
Raw Permalink Normal View History

2021-11-30 11:55:13 +01:00
import Foundation
2021-12-01 22:47:19 +01:00
import Vapor
2021-11-30 11:55:13 +01:00
typealias CardId = String
2021-12-01 22:47:19 +01:00
struct Card: Codable {
2021-11-30 11:55:13 +01:00
2021-12-01 22:47:19 +01:00
enum Suit: Character, CaseIterable, Codable {
2021-11-30 11:55:13 +01:00
case eichel = "E"
case blatt = "B"
case herz = "H"
case schelln = "S"
2021-12-18 15:08:43 +01:00
var ace: Card {
.init(self, .ass)
}
2021-11-30 11:55:13 +01:00
}
let symbol: Symbol
let suit: Suit
init(suit: Suit, symbol: Symbol) {
self.suit = suit
self.symbol = symbol
}
2021-12-01 22:47:19 +01:00
init(_ suit: Suit, _ symbol: Symbol) {
self.suit = suit
self.symbol = symbol
}
2021-12-06 11:40:53 +01:00
init?(id: CardId) {
guard id.count == 2 else {
2021-11-30 11:55:13 +01:00
return nil
}
2021-12-06 11:40:53 +01:00
guard let suit = Suit(rawValue: id.first!),
let symbol = Symbol(id: id.last!) else {
2021-11-30 11:55:13 +01:00
return nil
}
self.suit = suit
self.symbol = symbol
}
var id: CardId {
2021-12-06 11:40:53 +01:00
"\(suit.rawValue)\(symbol.id)"
2021-12-01 22:47:19 +01:00
}
var points: Int {
symbol.points
2021-11-30 11:55:13 +01:00
}
2021-12-18 15:08:43 +01:00
var playable: PlayableCard {
.init(card: self, isPlayable: true)
}
var unplayable: PlayableCard {
.init(card: self, isPlayable: false)
}
func playable(_ isPlayable: Bool) -> PlayableCard {
.init(card: self, isPlayable: isPlayable)
}
2021-12-03 18:03:29 +01:00
static let allCards: Set<Card> = {
let all = Card.Suit.allCases.map { suit in
Card.Symbol.allCases.map { symbol in
Card(suit: suit, symbol: symbol)
}
}.joined()
return Set(all)
}()
2021-11-30 11:55:13 +01:00
}
2021-12-06 11:40:53 +01:00
extension Card {
func isTrump(in game: GameType) -> Bool {
game.sortingType.isTrump(self)
}
}
2021-11-30 11:55:13 +01:00
extension Card: CustomStringConvertible {
var description: String {
2021-12-01 22:47:19 +01:00
"\(suit) \(symbol)"
2021-11-30 11:55:13 +01:00
}
}
2021-12-01 22:47:19 +01:00
extension Card: Hashable {
}