以下代码示例在我正在做的一个项目中让我有些悲伤:
这是我的问题...
此代码导致在窗口上绘制一个正方形网格,以及一个彩色形状,从该网格的顶部开始:
MainWindow mainAppWindow = mainAppWindow = new MainWindow("TETRIS");
mainAppWindow.setExtendedState(Frame.MAXIMIZED_BOTH);
mainAppWindow.setVisible(true);
TetriminoFactory blockBuilder = mainAppWindow.getGameBoard().getBlockFactory();
mainAppWindow.getGameBoard().setActiveTetrimino(blockBuilder.createTetrimino());
Tetrimino activeTetrimino = mainAppWindow.getGameBoard().getActiveTetrimino();
在此之后,我有一个 while 循环,它应该每秒将形状向下移动指定距离。这个动作应该在窗口上表现出来:
while((activeTetrimino.getLowermostPiece().getLoc().getYPos() / MiscConsts.TETRIS_UNIT) <= mainAppWindow.getGameBoard().getLowermostRowIndex())
{
if(activeTetrimino.checkForNeighbouringBlock().equals(Collision.BLOCK_BELOW_ME))
{
if(!activeTetrimino.setSecuredState(true))
{
activeTetrimino = blockBuilder.createTetrimino();
}
}
activeTetrimino.moveTetrimino(0, MiscConsts.TETRIS_UNIT);
mainAppWindow.canvas.repaint();
try {
Thread.sleep(MiscConsts.TIME_BETWEEN_ADVANCEMENTS);
} catch (InterruptedException e) {
System.out.println("ERROR - InterruptedException thrown in operate(). Terminating.");
e.printStackTrace();
System.exit(1000);
}
}
正是在这一点上,我遇到了一个问题。该循环似乎撤消了所有先前的绘图,并产生了一个空白屏幕。如果我将循环注释掉,则会绘制网格以及形状,但当然不会发生任何移动。我不确定这里发生了什么,但我有预感它与线程或其他东西有关。或者也许只是 while 循环是反摇摆:P
完整摘录:
public static void main(String[] args)
{
theApp = new Tetris();
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
theApp.createGUI(); // Call GUI creator
}
});
}
public void createGUI()
{
MainWindow mainAppWindow = mainAppWindow = new MainWindow("TETRIS");
mainAppWindow.setExtendedState(Frame.MAXIMIZED_BOTH);
mainAppWindow.setVisible(true);
TetriminoFactory blockBuilder = mainAppWindow.getGameBoard().getBlockFactory();
// NEEDS WORK???
mainAppWindow.getGameBoard().setActiveTetrimino(blockBuilder.createTetrimino());
Tetrimino activeTetrimino = mainAppWindow.getGameBoard().getActiveTetrimino();
while((activeTetrimino.getLowermostPiece().getLoc().getYPos() / MiscConsts.TETRIS_UNIT) <= mainAppWindow.getGameBoard().getLowermostRowIndex())
{
if(activeTetrimino.checkForNeighbouringBlock().equals(Collision.BLOCK_BELOW_ME))
{
if(!activeTetrimino.setSecuredState(true))
{
activeTetrimino = blockBuilder.createTetrimino();
}
}
activeTetrimino.moveTetrimino(0, MiscConsts.TETRIS_UNIT);
mainAppWindow.canvas.repaint();
try {
Thread.sleep(MiscConsts.TIME_BETWEEN_ADVANCEMENTS);
} catch (InterruptedException e) {
System.out.println("ERROR - InterruptedException thrown in operate(). Terminating.");
e.printStackTrace();
System.exit(1000);
}
}
}