【发布时间】:2025-12-24 08:00:06
【问题描述】:
我对 Java 还很陌生,现在正在学习游戏设计。我有点刚开始,所以它不是真正的游戏。 我正在处理一个线程和一个数字数组。我必须让多个正方形同时在屏幕上移动。我的代码在一个方块上运行良好,但是当我尝试将它实现到多个方块时遇到了麻烦。我正在使用两个接口,但我不知道如何使用数组来制作单个随机正方形的多个案例。任何帮助将不胜感激。 伙计们干杯。
import java.awt.*;
import javax.swing.*;
public class MovingSquares extends JFrame implements Runnable
{
private static final Dimension WindowSize = new Dimension(600, 600);
private static final int NUMGAMEOBJECTS = 30;
private GameObject[] GameObjectsArray = new GameObject[NUMGAMEOBJECTS];
static int strtCoX = (int) (Math.random() * 600);
static int strtCoY = (int) (Math.random() * 600);
public MovingSquares() {
this.setTitle("Crazy squares");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int x = screensize.width/2 - WindowSize.width/2;
int y = screensize.height/2 - WindowSize.height/2;
setBounds(x, y, WindowSize.width, WindowSize.height);
setVisible(true);
Thread t = new Thread(this);
t.start();
}
public void run() {
while (true) {
try {
Thread.sleep(20);
} catch (InterruptedException e) { }
GameObject.move();
this.repaint();
}
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, WindowSize.width, WindowSize.height);
int size = 50;
int R = (int) (Math.random() * 256);
int G = (int) (Math.random() * 256);
int B = (int) (Math.random() * 256);
Color c = new Color(R, G, B);
g.setColor(c);
g.fillRect(strtCoX, strtCoY, size, size);
}
public static void main(String[] args) {
MovingSquares M = new MovingSquares();
}
}
第二个接口 - GameObject 类。
import java.awt.*;
public class GameObject
{
private static double x;
private static double y;
private Color c;
public static int ranCoX = (int) (Math.random() * 20);
public static int ranCoY = (int) (Math.random() * 20);
public GameObject() {
int strtX = (int) x;
int strtY = (int) y;
int speedX = (int) (Math.random() * 10);
int speedY = (int) (Math.random() * 10);
}
public static void move() {
int velX = (int) (Math.random() * ranCoX);
int velY = (int) (Math.random() * ranCoY);
if (MovingSquares.strtCoY > 600)
MovingSquares.strtCoY = MovingSquares.strtCoY - 550;
else if (MovingSquares.strtCoX > 600)
MovingSquares.strtCoX = MovingSquares.strtCoX - 550;
MovingSquares.strtCoX += velX;
MovingSquares.strtCoY += velY;
}
public static void paint(Graphics g) {
int size = 50;
x = (Math.random() * 600);
y = (Math.random() * 600);
int R = (int) (Math.random() * 256);
int G = (int) (Math.random() * 256);
int B = (int) (Math.random() * 256);
Color c = new Color(R, G, B);
g.setColor(c);
g.fillRect((int)x, (int) y, size, size);
}
}
【问题讨论】:
-
建议:不要使用线程来操纵元素的位置——而是在重新绘制时计算它们的位置。
-
感谢您的建议,但我正在学习线程,这就是要求完成的方式。为对象(正方形)运行单个线程。主要问题是将我的代码实现到给定的数组中。
-
顺便说一句 -
repaint();调用需要在事件调度线程上。要将其放回 EDT,请从SwingUtiliities.invokeLater(..)调用它。正如@slartidan 所建议的那样,这种事情在 SwingTimer中是自动的。主 UI 也应该在 EDT 上构建(main(..)中的内容)。
标签: java arrays swing object graphics