我正在编写一个小程序,使得棋子以相同的速度来回运行。然而,底部检查器的运行速度比顶部检查器快得多。我如何纠正它,使它们来回以相同的速度运行。我猜测它与for循环有关但我无法弄明白。
import java.awt.*;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Image;
public class Checkers extends java.applet.Applet implements Runnable {
Thread runner;
int x1pos;
int x2pos;
Image offscreenImg;
Graphics offscreenG;
public void init() {
offscreenImg = createImage(this.size().width, this.size().height);
offscreenG = offscreenImg.getGraphics();
}
public void start() {
if (runner == null); {
runner = new Thread(this);
runner.start();
}
}
public void stop() {
if (runner != null) {
runner.stop();
runner = null;
}
}
public void run() {
while (true) {
for (x1pos = 5; x1pos <= 105; x1pos+=4)
{
for (x2pos = 105; x2pos >= 5; x2pos-=4)
{
repaint ();
try { Thread.sleep(10); }
catch (InterruptedException e) { }
}
repaint();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
}
x1pos = 5;
x2pos = 105;
}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
// Draw background onto the buffer area
offscreenG.setColor(Color.black);
offscreenG.fillRect(0,0,100,100);
offscreenG.setColor(Color.blue);
offscreenG.fillRect(100,0,100,100);
offscreenG.setColor(Color.blue);
offscreenG.fillRect(0,100,100,100);
offscreenG.setColor(Color.black);
offscreenG.fillRect(100,100,100,100);
// Draw checker
offscreenG.setColor(Color.red);
offscreenG.fillOval(x1pos,5,90,90);
offscreenG.setColor(Color.green);
offscreenG.fillOval(x2pos,105,90,90);
// Now, transfer the entire buffer onto the screen
g.drawImage(offscreenImg,0,0,this);
}
public void destroy() {
offscreenG.dispose();
}
}
谢谢
答案 0 :(得分:0)
您的run语句中的循环是嵌套的。这意味着每次更新x1pos时,都会将x2pos从105更新为5.
你的for循环应该读(尽可能与你的相似)
for (x1pos = 5, x2pos = 105; x1pos <= 105 && x2pos >= 5 ; x1pos+=4, x2pos-=4)
{
repaint ();
try { Thread.sleep(10); }
catch (InterruptedException e) { }
}