1

我正在创建一个纸牌游戏并将 slick2d 用于图形。当我在 public void init 中调用我的方法从一副牌中抽一张牌时,它会运行两次。下面的方法从卡片组构造函数中抽取一张卡片并返回索引号。

public Card PlayerCardDraw()
{

    Card index = cards.remove(1);
    System.out.println("Cards left: " + cards.size());
    return index;
}

甲板构造函数:

Deck()
{
    cards = new ArrayList<Card>();
    for (int a = 0; a < 52; a++)
    {           
            cards.add(new Card(a));         
    }
}
public class Play extends BasicGameState
{
Deck deck = new Deck ();
Image PlayScreen;
Image PauseButton;
Image FaceDown1, FaceDown2;

Image card[] = new Image [52];

public String mouse = "no input";


Card C;

public Play (int state)
{

}


public void init (GameContainer gc, StateBasedGame sbg) throws SlickException
{
    PlayScreen = new Image ("res/Play/PlayScreen.png");
    PauseButton = new Image ("res/Play/PauseButton.png");
    FaceDown1 = new Image("res/CardBacks/redback1.png");
    FaceDown2 = new Image("res/CardBacks/redback2.png");

    String fileLocation = new String ();
    for (int i = 0 ; i < 52 ; i++)
    {
        fileLocation = "res/cards/" + (i+1) + ".png";
        card [i] = new Image (fileLocation);
    }
       //should only run once, right?
    C = deck.PlayerCardDraw();

}

我跑时得到的输出是 Cards left: 51 Cards left: 50

这意味着 PlayerCardDraw() 被调用了两次。我在一个简单的系统输出语句中添加了“嗨”,它也运行了两次。

有人知道为什么会这样以及如何解决吗?顺便说一句,这东西在程序进入播放状态之前就已经运行了。它在标题状态下显示左卡和 hi 卡,其中不包括任何这些。

4

1 回答 1

1

我意识到这是一个非常古老的问题,但我遇到了完全相同的问题,我只是想通了。StateBasedGame对我来说,我是在我的类的构造函数和函数中初始化我的屏幕initStatesList()。这是我的代码:

public TheGame(String name)
{
    super(name);

    this.addState(new TitleScreen(TheGame.MENUSTATEID));
    this.addState(new HelpScreen(TheGame.HELPSTATEID));
    this.addState(new GameScreen(TheGame.PLAYSTATEID, GAMEWIDTH, GAMEHEIGHT));
    this.addState(new PauseScreen(TheGame.PAUSESTATEID));
    this.addState(new GameOverScreen(TheGame.GAMEOVERSTATEID));
    this.addState(new HighScoresScreen(TheGame.GAMERESULTSSTATEID));
}

public void initStatesList(GameContainer arg0) throws SlickException 
{
    this.getState(TheGame.MENUSTATEID).init(arg0, this);
    this.getState(TheGame.HELPSTATEID).init(arg0, this);
    this.getState(TheGame.PLAYSTATEID).init(arg0, this);
    this.getState(TheGame.PAUSESTATEID).init(arg0, this);
    this.getState(TheGame.GAMEOVERSTATEID).init(arg0, this);
    this.getState(TheGame.GAMERESULTSSTATEID).init(arg0, this);

    this.enterState(TheGame.MENUSTATEID);
}

这是我的计算机科学老师教我的班级的方式,但他是 Slick 2D 的新手,所以我认为他只是犯了一个错误。我通过删除所有getState()行来修复它initStatesList()。我希望这可以帮到你。

于 2017-01-13T00:25:14.357 回答