Skip to content

Instantly share code, notes, and snippets.

@davidgomes
Created September 15, 2011 13:39
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 davidgomes/73ee38624eeedb9e1611 to your computer and use it in GitHub Desktop.
Save davidgomes/73ee38624eeedb9e1611 to your computer and use it in GitHub Desktop.
Space Invaders
import java.awt.Dimension;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class MainFrame extends JFrame {
Dimension size = new Dimension(850, 600);
public MainFrame(String string) {
setTitle(string);
setSize(size);
setMinimumSize(size);
setMaximumSize(size);
setPreferredSize(size);
setResizable(false);
this.pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void run() {
this.setVisible(true);
}
}
public class Player {
int x = 0;
int y;
int height = 20;
int width = 50;
}
public class SpaceInvaders {
public static void main(String[] args) {
MainFrame mainFrame = new MainFrame("Space Invaders");
SpaceInvadersPanel gamePanel = new SpaceInvadersPanel();
mainFrame.add(gamePanel);
mainFrame.run();
}
}
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class SpaceInvadersPanel extends JPanel implements KeyListener {
boolean needs_repaint;
boolean on_title_screen, on_game, on_game_over;
Player player = new Player();
int y = 0;
public void paintComponent(Graphics g) {
/* Draws the elements on the screen */
super.paintComponent(g);
y = this.getParent().getHeight() - player.height;
g.fillRect(player.x, y, player.width, player.height);
/* Repainting has finished */
needs_repaint = false;
}
public SpaceInvadersPanel() {
this.setFocusable(true);
this.addKeyListener(this);
Dimension size = new Dimension(850, 600);
this.setSize(size);
this.setMinimumSize(size);
this.setMaximumSize(size);
this.setPreferredSize(size);
}
public void keyPressed(KeyEvent e) {
int key_code = e.getKeyCode();
if (key_code == KeyEvent.VK_RIGHT) {
player.x += player.width;
needs_repaint = true;
}
if (key_code == KeyEvent.VK_LEFT) {
player.x -= player.width;
needs_repaint = true;
}
if (needs_repaint)
this.repaint();
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment