I'm trying to make a space invaders game and I've got an issue where I'm trying to move the spaceinvaders in a loop [though the code shows an iteration of 5 movements in a for] but they aren't updated in the window.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyledDocument;
import java.util.Random;
public class SpaceInvadersPanel extends JPanel {
boolean running = false;
int indice = 0; //placeholder
int fine = 10; //placeholder
int speed = 10; //placeholder
String correctAnswer = "prova"; //Placeholder
Aliens[] alien = new Aliens[fine];
int alienX = 35;
int alienY = 35;
SpaceInvadersPanel(int SCREEN_WIDTH, int SCREEN_HEIGHT) throws IOException, InterruptedException {
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.white);
this.setFocusable(true);
startGame();
}
public void startGame() throws IOException, InterruptedException{
newSpaceInvader();
}
public void newSpaceInvader() {
for(int i = 0; i<alien.length; i++) {
alien[i] = new Aliens(alienX, alienY, speed);
alienX += 50;
if (i == 4) {alienY += 50; alienX = 35;}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
try {
draw(g);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {e.printStackTrace();
}
}
public void draw(Graphics g) throws IOException, InterruptedException {
BufferedImage image = ImageIO.read(new File("C:\\Users\\39340\\Desktop\\", "spaceinvadersart40bianco.png"));
g.setColor(Color.red);
for(int i = 0; i<alien.length; i++) {
g.drawImage(image, alien[i].x, alien[i].y, null);
}
run();
}
public void run() throws IOException, InterruptedException {
for (int i=0; i<5; i++) {System.out.println("sono al run");
move();Thread.sleep(500);}
}
public void move() throws IOException {
for(int i = 0; i<alien.length; i++) {
System.out.println("sto aumentando roba nel move");
System.out.println("alien x = " +alien[i].x);
alien[i].x += 50;
System.out.println("ora alien x = " +alien[i].x);
//alien[i].y += speed;
}
}
public void checkCollision() {}
public void gameOver(Graphics g) {}
}