Skip to content

Commit

Permalink
feat: added computed property for trick
Browse files Browse the repository at this point in the history
  • Loading branch information
Oliver-Binns committed Jul 17, 2023
1 parent 36df6e3 commit 98c1052
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Cards/Sources/Hearts/Hearts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import Combine

public final class Hearts: ObservableObject {
@Published private(set) var players: [Player]
var trick: [PlayingCard] {
players.compactMap(\.selectedCard)
}

public init(players: Int) {
self.players = Deck.hearts(playerCount: players)
Expand Down
5 changes: 5 additions & 0 deletions Cards/Sources/Hearts/Player.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ public final class Player: ObservableObject {
@Published
public private(set) var hand: [PlayingCard]

@Published
public private(set) var selectedCard: PlayingCard?

@Published
public private(set) var score: Int
private let scoringSystem = HeartsScore()
Expand All @@ -23,9 +26,11 @@ public final class Player: ObservableObject {
preconditionFailure("Cannot play a card that is not in your hand")
}
hand.remove(at: index)
selectedCard = card
}

func pickUp(cards: [PlayingCard]) {
selectedCard = nil
score = cards
.map(scoringSystem.score)
.reduce(score, +)
Expand Down
16 changes: 16 additions & 0 deletions Cards/Tests/HeartsTests/HeartsTrickTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import CardsModel
@testable import Hearts
import XCTest

final class HeartsTrickTests: XCTestCase {
func testTrick() {
let sut = Hearts(players: 4)
XCTAssertTrue(sut.trick.isEmpty)

let playerOne = sut.players[0]
let card = playerOne.hand[0]
playerOne.play(card: card)

XCTAssertEqual(sut.trick, [card])
}
}
17 changes: 17 additions & 0 deletions Cards/Tests/HeartsTests/PlayerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,20 @@ final class PlayerTests: XCTestCase {
XCTAssertTrue(sut.shotForTheMoon)
}
}

extension PlayerTests {
func testPlayCard() {
let sut = Player(hand: [
.suited(.five, .diamonds),
.suited(.jack, .spades)
])

sut.play(card: .suited(.five, .diamonds))
XCTAssertEqual(sut.selectedCard, .suited(.five, .diamonds))
XCTAssertEqual(sut.hand, [.suited(.jack, .spades)])

sut.play(card: .suited(.jack, .spades))
XCTAssertEqual(sut.selectedCard, .suited(.jack, .spades))
XCTAssertEqual(sut.hand, [])
}
}

0 comments on commit 98c1052

Please sign in to comment.