I’m writing a Tetris-like game for Android and I’m trying to implement the “real-time part”. I have something which seems to work, but I want to be sure that my implementation is correct.
我想的是:
这些形状按固定速度定下(例如,我想要等到nm>milliseconds,每次打下形状的y)。
参与者可以随时放弃体质,然后必须立即中断等待n<>n><>>m>milliseconds的时间,并只为下一个形状重新开始。
当形状下降或形形形形形形形形形形形色时,游戏在形成另一种形态之前等待m>
<>m>m>m> milliseconds 该系统必须能够随时停下read。
我正在做的是:
class TetrisThread extends Thread {
private int n = 3000; // for testing purposes, in the real game n will be smaller ;)
private int m = 1000;
@Override
public void run() {
doDraw();
while(!interrupted())
{
try {
synchronized (this) {
wait(n);
}
doPhysics();
doDraw();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
// This method is the one which will drop the shape, it is called from another thread
synchronized public boolean onTouch([…]) {
[…]
// The shape has to be dropped
dropShape();
notify();
[…]
}
private void doPhysics() throws InterruptedException {
[…]
// The shape cannot go down or has been dropped
sleep(m);
createNewShape();
[…]
}
}
特别是,<条码>同步(这一条){等待(n);}看不见,因为如果我正确理解,这将在<条码>上锁,立即予以公布。
But wait()
requires to be used in a synchronized(this)
block (why?) and I cannot either synchronize the whole run()
method, because then if I try to drop three times the shape during the sleep(m)
call, then the three next shapes will be automatically dropped (which is not what I want).
Does this seem correct to you?
Do you have any correction, advice, or remark?
Thank you :-)