卡在运动桨上

时间:2019-05-15 23:15:08

标签: java netbeans-8

对于我的课堂,我需要创建一个单人乒乓球游戏。我们需要使用我们所学的内容,因此它的代码很简单,问题是,当“ while循环”运行时,我的Keydown线程似乎无法正常工作。我的老师根本没有帮助,所以这就是我在这里的原因。请仅使用程序中使用的方法和方法来提供帮助。

我尝试将球代码移入运行线程,但似乎永远无法真正使该线程运行。

public class PongGame extends Applet {

    int startup = 0;
    int x = 400;
    int y = 500;
    int x2 = (int) (Math.random() * (600 + 1));
    int y2 = (int) (Math.random() * (600 + 1));
    int xVelocity = 1;
    int yVelocity = 1;
    int x2Velocity = 1;
    int y2Velocity = 1;
    int curry = 700;
    int currx = 600;
    int counter = 2;

    @Override
    public void init() {
        setSize(1440, 900);
        setBackground(Color.black);
        setFont(new Font("Helvetica", Font.BOLD, 36));

    }

    @Override
    public boolean keyDown(Event evt, int key) {

        startup = startup + 1;
        repaint();

        if (key == Event.RIGHT) {
            currx += 10;
        }
        if (key == Event.LEFT) {
            currx -= 10;
        }

        if (currx == 1400) {
            currx = 10;
        }
        if (currx == 20) {
            currx = 1399;
        }

        repaint();
        return false;

    }

    public void run(Graphics g) {
        startup = 0;
        while (counter > 0) {

            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
            }

            x += xVelocity;
            y += yVelocity;

            g.setColor(Color.blue);
            g.fillRect(currx, curry, 300, 25);

            g.setColor(Color.red);
            g.fillOval(x, y, 30, 30);

            for (int j = 0; j < 20000000; j++);
            g.setColor(Color.black);
            g.fillOval(x, y, 30, 30);

            //Bounce the ball off the wall or paddle
            if (x >= 1400 || x <= 0) {
                xVelocity = -xVelocity;
            }
            if (y >= 800 || y <= 0) {
                yVelocity = -yVelocity;
            }
            if (((y == 675)) && ((currx <= x) && (currx + 300) >= x)) {
                yVelocity = -yVelocity;
                y = y - 10;
                repaint();

            }
        }
    }

    public void paint(Graphics g) {
        if (startup == 0) {
            g.setColor(Color.white);
            g.drawString("Welcome To PONG", 0, 100);
            g.drawString("Created by Caden Anton", 0, 200);
            g.drawString("copyright May 3rd, 2019 ©", 0, 300);
            g.drawString("Press any key to continue", 0, 400);
        }

        if (startup == 1) {
            g.setColor(Color.white);
            g.drawString("RULES:", 0, 100);
            g.drawString("Press the arrwow keys to move the paddle", 0, 200);
            g.drawString("Your objective is to keep the ball from touching the ground", 0, 300);
            g.drawString("Once the ball hits the ground you lose the game", 0, 400);
        }
        if (startup >= 2) {
            //Input Run thread start here. 
        }
    }
}

0 个答案:

没有答案