gpt4 book ai didi

java - 如何创建随机怪物

转载 作者:行者123 更新时间:2023-12-01 14:41:45 24 4
gpt4 key购买 nike

我正在制作一款类似《Space Impact》的游戏。在我的游戏中,火箭工作正常,但我无法随机创建怪物。怪物在屏幕上,但它们没有移动,所以它们不活跃我怎样才能做到这一点?

public class Dnm extends JFrame implements Runnable {
Graphics dbg;
Image dbImage;
Image Pik1;
Image Boss;
static ImageIcon active;

int x, y, xDirection, yDirection, BossX, BossY;

public void run() {
try {
while (true) {
move();
boss();
Thread.sleep(10);
}
} catch (Exception e) {
System.out.println("Uh-oh, something went wrong!.");
}
}

private void move() {
x += xDirection;
y += yDirection;
}

private void boss() {
while (BossX == 0) {
BossX = getX() - 1;
}

Random rastgele = new Random(getY());
BossY = rastgele.nextInt();
}

public void setXDirection(int xdir) {
xDirection = xdir;
}

public void setYDirection(int ydir) {
yDirection = ydir;
}

// KEY COMMANDS //
public class AL extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();

if (keyCode == e.VK_LEFT) {
setXDirection(-1);
}
if (keyCode == e.VK_RIGHT) {
setXDirection(+1);
}
if (keyCode == e.VK_UP) {
setYDirection(-1);
}
if (keyCode == e.VK_DOWN) {
setYDirection(+1);
}
}

@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
setXDirection(0);
}
if (keyCode == e.VK_RIGHT) {
setXDirection(0);
}
if (keyCode == e.VK_UP) {
setYDirection(0);
}
if (keyCode == e.VK_DOWN) {
setYDirection(0);
}
}

@Override
public void keyTyped(KeyEvent e) {

}
}

// CONSTRUCTOR //
public Dnm() {
//Image Import
ImageIcon still = new ImageIcon("img/rocket.png");
Pik1 = still.getImage();

addKeyListener(new AL());

setTitle("Dnm");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setVisible(true);

x = 15;
y = 15;
}

public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);

}

public void paintComponent(Graphics g) {
ImageIcon background = new ImageIcon("img/space.jpeg");
Image background1 = background.getImage();

ImageIcon still1 = new ImageIcon("img/Alien.png");
Boss = still1.getImage();

g.setColor(Color.red);
g.drawImage(background1, 0, 0, this);
g.drawImage(Boss, BossX, BossY, this);
g.drawImage(Pik1, x, y, this);
g.setColor(Color.blue);

repaint();
}

public static void main(String[] args) {
Dnm game = new Dnm();

Thread t1 = new Thread(game);
t1.start();
}
}

谢谢。

最佳答案

由于您的代码不完整,很难确定,但这一行看起来很可疑:

while (BossX == 0) {
BossX = getX() - 1;
}

这段代码很可能会被执行一次,对吧?如果 BossX 最初为零,则代码将在您更改其值的位置执行。在下一次更新时,BossX 不为零(大概),因此代码不会执行。由于 BossX 是您绘制 Boss 的 X 坐标,因此它不会移动。相反,它只是在同一位置一遍又一遍地重绘。

要让怪物随机移动,请在每个游戏循环中随机增加或减少 X 和 Y 坐标值。添加第二个随机变量,使它们以随机速度沿随机方向移动(通过将坐标值调整为大于 1 的值)。

正如 NPE 所评论的,您应该在调试器中单步执行代码并准确找出发生了什么。

关于java - 如何创建随机怪物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15883117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com