[英](Java) Card Game Logic
我正在嘗試制作紙牌戰爭。 但是,對於此游戲,將有一個名為“王牌”的額外紙牌堆。 如果玩家1或2擁有一張在王牌堆中引用的牌,則無論其排名如何,它都是自動獲勝。 此刻,我堅持邏輯。
在稱為CardPile的類中,這里是構造函數和方法。
public CardPile(Card[ ] initialCards)
{
pile = new ArrayList<Card>();
for (int i=0; i<initialCards.length; i++)
pile.add(initialCards[i]);
}
public void add(Card aCard)
{
pile.add(aCard);
}
public Card get(int index)
{
return pile.get(index);
}
在我稱為TrumpWar的課程中
protected CardPile tCard;
protected CardPile cp;
protected CardPile p1;
protected CardPile p2;
public TrumpWar( )
{
cp = new CardPile (new Card[52]);
cp.shuffle();
tCard = new CardPile ();
for (int i=1; i<7; i++) //<---Stuck.
{
tCard.add(tCard.get(i)); //<---error
}
cp.shuffle();
p1 = new CardPile(new Card [26]);
p2 = new CardPile(new Card [26]);
}
當我運行游戲時,我得到了NullPointerException
,我很確定那是因為我沒有將任何東西傳遞給王牌堆。 當我嘗試為王牌ArrayList放入int時,我將得到一個錯誤int cannot be converted to Card []
。
我如何才能從52張牌中獲得前六張牌,而又不刪除它們,而只是將它們存儲為參考,並將其添加到王牌堆中?
此外,我是否正確聲明了player1,player2和cardpile?
非常感謝您的幫助,謝謝。
您應該替換為:
for (int i=0; i<6; i++)
{
tCard.add(cp.get(i));
}
您試圖從空的tCard
獲取卡片。
請注意,在調用cp = new CardPile(array)
之前,此代碼仍然無法工作,其中array實際上包含不為null
卡。 否則, tCard.add(cp.get(0))
不會將引用添加到第一張卡,而只是將其添加為null
卡類:
public class Card {
Integer i = new Integer(0);
Card(Integer is) {
this.i = is;
}
}
CardPile類:
public class CardPile {
ArrayList<Card> pile = null;
public CardPile(Integer no)
{
pile = new ArrayList<Card>();
for (int i=1; i<=no; i++) {
pile.add(new Card(i));
}
}
public void add(Card aCard)
{
pile.add(aCard);
}
public Card get(int index)
{
return pile.get(index);
}
}
TrumpWar班:
public class TrumpWar {
protected CardPile tCard;
protected CardPile cp;
protected CardPile p1;
protected CardPile p2;
public TrumpWar( )
{
cp = new CardPile (52); // only passing the no of cards to be created.
//cp.shuffle();
tCard = new CardPile(52); // only passing the no of cards to be created.
for (int i=1; i<7; i++)
{
tCard.add(tCard.get(i));
}
// cp.shuffle();
p1 = new CardPile(26);
p2 = new CardPile(26);
}
public static void main(String a[]){
new TrumpWar();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.