需要小程序的帮助

时间:2014-05-19 05:48:20

标签: java animation applet awt java-2d

我是GUI和Applets的新手。我正在尝试制作一个非常基本的乒乓球比赛,而我之前已经接近它,但我已经搞砸了我的代码,似乎无法让它正常工作。我希望我的标签显示分数但由于某种原因它显示“...”作为分数。此外,我似乎无法让我的酒吧移动到屏幕的底部。一旦球从底部下方而不是杆位,我希望标签显示Game Over和他们的分数。感谢您的帮助,我为我(可能)草率的代码道歉。

package games;

import java.awt.Graphics;

public class FirstGame extends GameLoop {

public void init()
{
    setSize(400, 400);
    Thread th = new Thread(this);
    th.start();
    offscreen = createImage(400, 400);
    d = offscreen.getGraphics();
    addKeyListener(this);
}

public void paint(Graphics g){
    d.clearRect(0, 0, 400, 400);
    d.fillRect(x, y, 80, 20);
    d.fillOval(xBall, yBall, 20, 20);
    g.drawImage(offscreen, 0, 0, this);
}

public void update(Graphics g){
    paint(g);
}
}

GameLoop

package games;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Label;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class GameLoop extends Applet implements Runnable, KeyListener
{
public int x, y, xspeed, yspeed, xBall, yBall, barSpeed, score;
public Image offscreen;
public Graphics d;
public int width, height;
public Label label;

public boolean left, right, notLose;

//@Override
public void run() {
    x = 160;
    y = 379;
    xspeed = 3;
    yspeed = 3;
    xBall = 190;
    yBall = 190;
    barSpeed = 3;
    notLose = true;
    score = 0;
    label = new Label("Your Score: " + Integer.toString(score));

    this.add(label);

    while(true){
        if(left == true){
            x-=barSpeed;
        }
        if(right == true){
            x+=barSpeed;
        }
        xBall += xspeed;
        yBall -= yspeed;

        //left and right walls
        if(xBall < 10 || xBall > 390){
            xspeed = -xspeed;
        }

        if(yBall < 10){
            yspeed = -yspeed;
        }

        if(yBall  - 10 > 379 && (!(xBall >  x- 10) && !(xBall < x + 90))){
            notLose = false;
        }
        if(notLose = false){
            label.setText("Game Over! Your Score: " + Integer.toString(score));
        }

        label.setText("Your Score: " + Integer.toString(score));
        score++;
        repaint();

        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }//end while
}//end run()

public void keyTyped(KeyEvent e) {
}

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == 37){
        left = true;
    }
    if(e.getKeyCode() == 39){
        right = true;
    }
}

public void keyReleased(KeyEvent e) {
    if(e.getKeyCode() == 37){
        left = false;
    }
    if(e.getKeyCode() == 39){
        right = false;
    }
}
}

0 个答案:

没有答案