gpt4 book ai didi

Java Swing Sprite : how to simulate a rolling dice

转载 作者:行者123 更新时间:2023-11-30 03:34:26 25 4
gpt4 key购买 nike

在我们用 Java 开发的游戏板中,我们希望在按下按钮时显示一种滚动的骰子。我们正在尝试使用以下图像作为 Sprite :

enter image description here

所以当按下按钮时,会发生以下情况:

private void startAnimationDie(final JPanel panel) {
int launchResult = /* getting a launch dice result from the core game (from 1 to 6)*/

new Thread() {
public void run() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
BufferedImage[] animationBuffer = initAnimationBuffer();
BufferedImage[][] exactDieFaces = initExactDieFaces();
int launchResult = coreGame.launchDie();
coreGame.getMyPartecipant().setLastLaunch(launchResult);
AnimationSprite animation = new AnimationSprite(animationBuffer, Constants.DIE_ANIMATION_SPEED);
animation.start();
JLabel resultDie = new JLabel();
resultDie.setBounds(60, 265, Constants.DIE_SIZE, Constants.DIE_SIZE);
for (int counter = 0; counter < Constants.DIE_ANIMATION_SPEED * 100; counter++) {
animation.update();
//panel.removeAll();
panel.updateUI();
//System.out.println("infor");
resultDie.setIcon(new ImageIcon(animationBuffer[counter % Constants.ROTATIONS]));
panel.add(resultDie);
panel.updateUI();
updateUI();

}
panel.removeAll();
panel.updateUI();
AnimationSprite resultAnimation = new AnimationSprite(exactDieFaces[launchResult - 1], 6);
resultAnimation.start();
resultAnimation.update();
System.out.println("0");
resultDie.setIcon(new ImageIcon(exactDieFaces[launchResult - 1][0]));
System.out.println("1");
resultDie.setBounds(60, 265, Constants.DIE_SIZE, Constants.DIE_SIZE);
System.out.println("2");
panel.add(resultDie);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
userPlayer.getGamePanel().makePossibleMoveFlash();
}
});
} catch (Exception ex) {
}
}
}.start();

其中,exactDieFaces 包含根据正在启动的 pawn 颜色的骰子面,该面将在模拟滚动完成后显示;另一方面,animationBuffer 包含从 Sprite 图像中获取的 40 或 50 个所有颜色的随机面,如下所示:

private BufferedImage[] initAnimationBuffer() {
BufferedImage[] result = new BufferedImage[Constants.ROTATIONS];
int rowSprite, colSprite;
Random random = new Random();
for (int i = 0; i < Constants.ROTATIONS; i++) {
rowSprite = 1 + random.nextInt(5);
colSprite = 1 + random.nextInt(5);
result[i] = DieSprite.getSpriteExact(0 /* offset */,colSprite, rowSprite);
}
return result;
}

问题是动画期间没有显示任何内容:我预计会看到许多骰子面一个接一个地变化,直到 for 循环结束,但没有显示任何内容......我唯一看到的是根据彩色典当已经启动了骰子,但同时什么也没有......你能帮助我吗?

最佳答案

如果我正确理解您的代码,您将尝试在同一个 for 循环中多次更新 UI。动画不是这样运作的。您需要一个计时器,它会定期通知您移至下一帧进行查看。

了解如何使用计时器的一个好起点是 here在 Java 教程中。

关于Java Swing Sprite : how to simulate a rolling dice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28321238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com