正在开发一个简单的纸牌游戏。尝试使逻辑起作用,从牌组中“抽”一张牌并将其添加到玩家手中。
这是相关的代码片段。
import Foundation
struct Player: Identifiable {
var id: UUID = UUID()
var name: String
var cards: [Card] = []
var plays: [Plays] = []
let human: Bool
init(name: String, human: Bool) {
self.name = name
self.human = human
}
mutating func addCard(card: Card)
{
print("Adding card \(card.id) to the players cards")
cards.append(card)
print("Player now has \(cards.count) cards")
}
}
class Game: ObservableObject {
@Published var deck:Deck = Deck()
@Published var discard: [Card] = []
@Published var players: [Player]
@Published var round: Int = 1
init(){
players = []
players.append(Player(name: "Player 1", human: false))
players.append(Player(name: "Player 2", human: false))
players.append(Player(name: "Player 3", human: false))
players.append(Player(name: "Player 4", human: true))
//self.deal()
}
func deal() {
if players[0].cards.isEmpty {
for _ in 1...7 {
players[0].addCard(card: deck.deal())
players[1].addCard(card: deck.deal())
players[2].addCard(card: deck.deal())
players[3].addCard(card: deck.deal())
}
print("All the cards are dealt and player 4 now has \(players[3].cards.count) cards")
} else {
print("Players already have 7 cards")
}
}
func discard(card: Card, player: Player) {
var selectedPlayer = players.first(where: { $0.id == player.id })
selectedPlayer?.cards.removeAll(where: { $0.id == card.id})
discard.append(card)
}
func draw(player: Player){
var selectedPlayer = players.first(where: { $0.id == player.id })
let drawnCard = deck.deal()
print("They drew the \(drawnCard.rank.name) of \(drawnCard.suit.name) with ID \(drawnCard.id)")
selectedPlayer?.addCard(card: drawnCard)
}
}
我无法理解的是,当我从 Game 类的
player.addCard(card: card)
函数内部调用 deal()
时,它工作正常并按预期添加卡片。但是从 draw
函数内部(朝向游戏类的底部)调用相同的函数实际上并不会将卡添加到玩家手上。
我可以从
addCard
函数内的打印语句看到它正在被调用,并且它传递的卡的 ID 是正确的(并且对于启动它的每个 tapGesture 来说都是不同的)。
有什么想法为什么
array.append()
实际上没有添加到数组中吗?
使用
firstIndex
和 players[index]
尝试此方法,如代码示例中所示
func draw(player: Player){
if let index = players.firstIndex(where: { $0.id == player.id }) {
let drawnCard = deck.deal()
print("They drew the \(drawnCard.name) of \(drawnCard.name) with ID \(drawnCard.id)")
players[index].addCard(card: drawnCard)
}
}