/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package spaceinvadergame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class SpaceInvaderGame extends JPanel implements ActionListener, KeyListener {
private Timer timer;
private int spaceshipX;
private ArrayList<Rectangle> bullets;
private ArrayList<Rectangle> enemies;
private Random random;
public SpaceInvaderGame() {
timer = new Timer(10, this);
timer.start();
spaceshipX = 250;
bullets = new ArrayList<>();
enemies = new ArrayList<>();
random = new Random();
this.setFocusable(true);
this.addKeyListener(this);
generateEnemies();
}
private void generateEnemies() {
for (int i = 0; i < 5; i++) {
enemies.add(new Rectangle(50 + i * 80, 50, 40, 40));
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(spaceshipX, 500, 50, 50);
g.setColor(Color.RED);
for (Rectangle bullet : bullets) {
g.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
}
g.setColor(Color.GREEN);
for (Rectangle enemy : enemies) {
g.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
}
}
@Override
public void actionPerformed(ActionEvent e) {
Iterator<Rectangle> bulletIterator = bullets.iterator();
while (bulletIterator.hasNext()) {
Rectangle bullet = bulletIterator.next();
bullet.y -= 5;
if (bullet.y < 0) {
bulletIterator.remove();
} else {
for (Iterator<Rectangle> enemyIterator = enemies.iterator(); enemyIterator.hasNext();) {
Rectangle enemy = enemyIterator.next();
if (bullet.intersects(enemy)) {
bulletIterator.remove();
enemyIterator.remove();
break;
}
}
}
}
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT && spaceshipX > 0) {
spaceshipX -= 5;
} else if (key == KeyEvent.VK_RIGHT && spaceshipX < getWidth() - 50) {
spaceshipX += 5;
} else if (key == KeyEvent.VK_SPACE) {
bullets.add(new Rectangle(spaceshipX + 20, 500, 10, 20));
}
}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
JFrame frame = new JFrame("Space Invader Game");
SpaceInvaderGame game = new SpaceInvaderGame();
frame.add(game);
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Tidak ada komentar:
Posting Komentar