我有一个类似于生命游戏的游戏。游戏涉及 build 房屋并重新安排邻居等。我想重新启动游戏,只需将所有这些值设置回原始开始值即可。我如何用代码做到这一点。我理解它的英文,但似乎无法将其转换为代码。
这是我的一些主程序(如果有人想让我发布整个主程序,我可以),但为了简单起见,我不想让你们感到困惑。
所以我想要的是:重新启动游戏,我只想将所有这些值设置回原始的起始值。
一些主要程序:
public class Ghetto extends JFrame implements ActionListener, MouseListener,MouseMotionListener
{
protected Grids theGrid;
JButton resetButton;
javax.swing.Timer timer; // generates ticks that drive the animation
public final static int SIZE = 5;
public final static int BLUE = 10;
public final static int RED = 8;
public final static int DIVERSITY_PERCENTAGE = 70;
public static void main(String[] args)
{
new Ghetto();
}
public Ghetto() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(this);
addMouseMotionListener(this);
setLayout(new FlowLayout());
theGrid = new Grids(SIZE, BLUE, RED, DIVERSITY_PERCENTAGE);
add(theGrid);
resetButton = new JButton("Reset");
add(resetButton);
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetWithCurrent();
}
});
setSize(new Dimension(550, 600));
setVisible(true);
}
//public void resetWithCurrent()
//{
//}
@Override
public void actionPerformed(ActionEvent e)
{
timer.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
performStep();
}
});
}
}
最佳答案
通常,“重置”最简单的方法就是不重置。只需扔掉旧元素并制作一个全新的元素即可!构造函数会为你处理好一切,你不必担心会遗漏什么。如果确实需要,您可以创建一个执行所有必要设置的重置方法,并让构造函数调用它。您必须确保捕获所有内容,因此特别是您不能使用任何类似于 Foo x = bar
的字段初始化,也不能使用任何初始化 block 。
我建议的方法:
Ghetto ghetto = new Ghetto();
//Do stuff with the ghetto.
ghetto = new Ghetto();
//BLAM! The old ghetto is *gone*, and we have a new one to play with.
关于java - 如何将所有值设置回原始起始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22825991/