Skip to content

Instantly share code, notes, and snippets.

@MetalBeetle
Created March 1, 2011 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MetalBeetle/848861 to your computer and use it in GitHub Desktop.
Save MetalBeetle/848861 to your computer and use it in GitHub Desktop.
A tiny invaders game that fits into 1kB of pack200 jar file.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.util.Random;
import javax.swing.JApplet;
public class M extends JApplet implements Runnable, KeyListener {
boolean key[] = new boolean[65535];
BufferStrategy strategy;
Random r = new Random();
@Override
public void init() {
setIgnoreRepaint(true);
Canvas canvas = new Canvas();
add(canvas);
canvas.setBounds(0, 0, 800, 600);
canvas.createBufferStrategy(2);
strategy = canvas.getBufferStrategy();
canvas.addKeyListener(this);
new Thread(this).start();
}
public void run() {
outer: while (true) {
boolean gameover = false;
int shipPos = 400;
int shotX = 400; int shotY = 550;
boolean[] iAlive = new boolean[20];
int[] iX = new int[20];
int iY = 0;
int level = 0;
int dir = 0;
game: while (true) {
try { Thread.sleep(20); } catch (Exception ex) {}
Graphics g = strategy.getDrawGraphics();
if (key[KeyEvent.VK_LEFT]) { shipPos -= 5; }
if (key[KeyEvent.VK_RIGHT]) { shipPos += 5; }
if (shipPos < 10) { shipPos = 10; }
if (shipPos > 790) { shipPos = 790; }
if (shotY < 0) { shotY = 550; }
if (shotY == 550) {
shotX = shipPos;
if (key[KeyEvent.VK_SPACE]) { shotY = 549; }
} else {
shotY -= 10;
}
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 600);
g.setColor(Color.RED);
if (gameover) { g.drawString("GAME OVER", 100, 100); }
g.fillRect(shotX - 1, shotY, 3, 20);
g.setColor(Color.GREEN);
if (r.nextInt(100 - level) == 0) {
dir = r.nextBoolean() ? -2 - level / 10 : 2 + level / 10;
}
for (int i = 0; i < level; i++) {
if (iAlive[i]) {
if (shotY != 550 && Math.abs(iX[i] - shotX) < 20 && Math.abs(iY - shotY) < 20) {
iAlive[i] = false;
shotY = 550;
continue;
}
if (iX[i] < 0 || iX[i] > 800) { dir = -dir; }
g.fillOval((iX[i] += dir) - 15, iY - 15, 30, 30);
}
}
iY += 1 + level / 30;
g.setColor(Color.LIGHT_GRAY);
g.fillOval(shipPos - 10, 530, 20, 40);
strategy.show();
if (gameover) { try { Thread.sleep(2000); } catch (Exception e) {} continue outer; }
for (boolean alive : iAlive) {
if (alive) {
if (iY > 600) {
gameover = true;
}
continue game;
}
}
level++;
for (int i = 0; i < level; i++) {
iAlive[i] = true;
iX[i] = r.nextInt(800);
iY = 0;
}
}
}
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
key[((KeyEvent) e).getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
key[((KeyEvent) e).getKeyCode()] = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment