public InvaderGame() { setTitle("インベーダーゲーム"); setResizable(false); ScorePanel scorePanel = new ScorePanel(); MainPanel panel = new MainPanel(scorePanel); Container contentPane = getContentPane(); contentPane.add(scorePanel, BorderLayout.NORTH); contentPane.add(panel, BorderLayout.CENTER); pack(); }
private Thread gameLoop; ~~~ public MainPanel(ScorePanel scorePanel) { setPreferredSize(new Dimension(WIDTH, HEIGHT)); setFocusable(true); this.scorePanel = scorePanel; initGame(); random = new Random(); fireSound = Applet.newAudioClip(getClass().getResource("se/du.wav")); crySound = Applet.newAudioClip(getClass().getResource("se/gya2.wav")); bombSound = Applet.newAudioClip(getClass().getResource("se/gya.wav")); addKeyListener(this); gameLoop = new Thread(this); gameLoop.start(); }
private void initGame() { enemies = new Enemy[NUM_ENEMY]; for(int i = 0; i < NUM_ENEMY; i++) { enemies[i] = new Enemy(20 + (i % 10) * 40, 20 + (i / 10) * 40, 3, this); } player = new Player(0, HEIGHT - 20, this); playerbeams = new PlayerBeam[NUM_PLAYERBEAM]; for (int i = 0; i < NUM_PLAYERBEAM; i++) { playerbeams[i] = new PlayerBeam(this); } enemybeams = new EnemyBeam[NUM_ENEMYBEAM]; for (int i = 0; i < NUM_ENEMYBEAM; i++) { enemybeams[i] = new EnemyBeam(this); } }
public void run() { while(true) { move(); if(firePressed) { tryToFire(); } enemyAttack(); collisionDetection(); repaint(); try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } } }
public void upScore(int d) { score += d; repaint(); }
private void collisionDetection() { for (int i = 0; i < NUM_ENEMY; i++) { for (int j = 0; j < NUM_PLAYERBEAM; j++) { if (enemies[i].collideWith(playerbeams[j])) { enemies[i].die(); crySound.play(); scorePanel.upScore(KILL_ENEMY); break; } } }
public void move(int direction){ if (direction == LEFT) { x -= SPEED; } else if (direction == RIGHT) { x += SPEED; } if (x < 0) { x = 0; } if (x > MainPanel.WIDTH - image_width) { x = MainPanel.WIDTH - image_width; } }
public boolean collideWith(EnemyBeam enemybeam){ Rectangle rectPlayer = new Rectangle(x, y, image_width, image_height); Point pos = enemybeam.getPos(); Rectangle rectBeam = new Rectangle(pos.x, pos.y, enemybeam.getImageWidth(), enemybeam.getImageHeight()); return rectPlayer.intersects(rectBeam);
public void draw(Graphics g){ g.drawImage(image, x, y, null); }
public Point getPos(){ return new Point(x, y); }
public int getImageWidth(){ return image_width; }
public int getImageHeight(){ return image_height; }
private void loadImage(){ ImageIcon icon = new ImageIcon(getClass().getResource("image/player.gif")); image = icon.getImage(); image_width = image.getWidth(panel); image_height = image.getHeight(panel); }
public void die(){ setPos(TOMB.x, TOMB.y); isAlive = false; }
public void setPos(int x, int y){ this.x = x; this.y = y; }
public boolean isAlive(){ return isAlive; }