我的计划是用 Java 设计一个简单的桌球游戏。
OOP 在这里对球最有意义。所有的球都具有相同的功能,因此最好创建一个 Ball 类来处理球的相对位置和其他变量,例如当它进入一个洞时,它会自行移除并增加你的分数. 所以当它碰到一个洞 Ball.dispose(); 会很合适。
我的问题是我不知道如何操纵和处理球。另外为了移动它,我依赖 Thread.sleep 而不是 java.swing.timer,因为没有可用的 Action Performed 方法我可以依赖。
我怎样才能更轻松地移动球并在需要时摆脱它?
覆盖球的绿色东西是我通过在球上画一个绿色椭圆来擦除球的最后位置的方法。
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Main extends JFrame{
Ball redball = new Ball (285, 600, 20, 20, Color.RED);
//variables to control redball
private int rX = redball.getX();
private int rY = redball.getY();
private final int rWidth = redball.getWidth();
private final int rHeight = redball.getHeight();
int Force = 30;
int Bearing = 20; // True Bearing
public Main (){
setSize(600, 800);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Pool");
}
public void paint(Graphics g){
super.paint(g);
// draw the table
g.setColor (Color.GREEN);
g.fillRect(100, 100, 400, 600);
g.setColor (Color.BLACK);
g.drawRect(99, 99, 401, 601);
//draw start ball
g.setColor(redball.getColor());
g.fillOval(rX, rY, rWidth, rHeight);
if (Force == 30){
for (int i = Force; i > 0;i--){
try {
Thread.sleep(100);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
Force--;
if (rY > 98 + rWidth) {
rY = rY - i;
rX = rX + (Bearing/5);
}
g.fillOval(rX, rY, rWidth, rHeight);
g.setColor(Color.GREEN);
repaint ();
g.fillOval(rX - (Bearing/5), rY + i, rWidth, rHeight); // repaint last ball
g.setColor(Color.RED);
repaint ();
}
}
// Ball.dispose (redball);
}
public static void main(String[] args) {
new Main();
}
这是球类
public class Ball {
private int x;
private int y;
private int width;
private int height;
private Color color;
public Ball (int x, int y, int width, int height, Color color)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
public void setX (int x){
this.x = x;
}
public int getX (){
return this.x;
}
public void setY (int x){
this.y = y;
}
public int getY (){
return this.y;
}
public void setWidth (int width){
this.width = width;
}
public int getWidth (){
return this.width;
}
public void setHeight (int height){
this.height = height;
}
public int getHeight (){
return this.height;
}
public void setColor (Color color){
this.color = color;
}
public Color getColor (){
return this.color;
}
public static void dispose(Ball ball) {
ball = null; // if I call this method nothing happens
}
}