正在开发一款简单的纸牌游戏。尝试让逻辑发挥作用,从牌堆中“抽”一张牌并将其添加到玩家手中。
以下是相关的代码片段。
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)
}
}
我不明白的是,当我player.addCard(card: card)
从 Game 类中的函数内部调用时deal()
,它运行正常,并按预期添加了卡片。但从函数内部draw
(靠近游戏类的底部)调用相同的函数实际上并没有将卡片添加到玩家手中。
我可以从函数内部的打印语句中看到addCard
它被调用,并且它传递的卡的 ID 是正确的(并且对于启动它的每个 tapGesture 都是不同的)。
知道为什么array.append()
实际上没有添加到数组中吗?
尝试使用这种方法
firstIndex
并直接使用players[index]
,如代码示例所示您的代码不起作用,因为
Player
是struct
(值类型),因此在您的draw
函数中,您实际上将卡添加到数组中元素的副本版本players
(即selectedPlayer
)。@workingdog 的答案有效,因为它直接修改数组元素