我正在制作卡片格斗游戏,似乎与arraylists有问题 我有1个arraylist,其中包含游戏中所有可用的牌, 和另一个播放列表,其中包含用户选择使用的卡片。
第二个arraylist开始为空,当用户开始从第一个arraylist中挑选卡片时,该卡片会被转移到第二个播放列表中。
问题在于,如果用户选择了两张相同的卡,那么一张卡发生的情况也会发生在另一张卡上。所以让我们说用户选择名为"超人"两次。当一个超级男人的健康下降时,另一个人也会下降。
我的代码如下所示,用于添加卡片来选择卡片:
//choosenCards is the arraylist of cards that the user chooses
//cards is the arraylist of available cards
choosenCards.add(cards.get(index));
答案 0 :(得分:2)
“添加”这样的卡实际上只是添加一个指向原始对象的引用。您想要的可能是“深层复制”(因此您可以从原始版本获得两个独立版本)。
使用choosenCards.add((Class of the card object) cards.get(index).clone());
(Class of the card object)
的原因是Object.clone()
返回Object
,然后需要将其转换为正确的类型。
答案 1 :(得分:0)
如果您需要从cards
转移到choosenCards
,则需要使用remove(index)。
choosenCards.add(cards.remove(index));
请注意,从卡中取出卡后,最大可用索引会减少一个。
您编码而是将卡片添加到choosenCard
,但不会从cards
中删除。