Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- class Lazers extends JFrame {
- //define rectangles for the lazers and person
- int x = (int) (Math.random() * 780);
- final Rectangle guy = new Rectangle (375, 400, 50, 50 );
- final Rectangle lazer = new Rectangle ( x, 0, 7, 23 );
- Rectangle back = new Rectangle( 0, 0, 800, 500 );
- //holds the variables for the guy's movement
- int STOP = 0, LEFT = 1, RIGHT = 2;
- int guyDirection;
- //variables that check if player is intersecting the sides
- Rectangle leftSide = new Rectangle (780, 0, 5, 500);
- Rectangle rightSide = new Rectangle (0, 0, 5, 500);
- public static void main (String []args ) {
- Lazers frame = new Lazers();
- frame.setVisible(true);
- }
- public Lazers( ) { //DO NOT TOUCH!!!
- //set the frame default properties
- super ( "My Lazer Game");
- setSize ( 800,500 );
- setLocationRelativeTo ( null );
- setResizable (false);
- Image img = Toolkit.getDefaultToolkit().getImage( "guy.PNG" );
- setIconImage ( img );
- //register 'Exit upon closing' as a default close operation
- setDefaultCloseOperation( EXIT_ON_CLOSE );
- guyMove gm = new guyMove();
- gm.start();
- }
- public void paint(Graphics g) {
- //super.paint(g);
- g.setColor(Color.BLACK);
- g.fillRect(back.x, back.y, back.width, back.height);
- //put the guy's rectangle on the screen
- g.setColor(Color.BLUE);
- g.fill3DRect(guy.x,guy.y,guy.width,guy.height,true);
- //put the lazers on the screen
- g.setColor(Color.ORANGE);
- g.fill3DRect(lazer.x,lazer.y,lazer.width,lazer.height,true);
- }
- private class guyMove extends Thread implements KeyListener {
- public void run() {
- addKeyListener(this);
- while (true) {
- try {
- repaint();
- if (guy.intersects(leftSide) ||
- guy.intersects(rightSide)) {
- guyDirection = STOP;
- }
- if (guyDirection==STOP) {
- }
- if (guyDirection==LEFT) {
- guy.x -= 5;
- }
- if (guyDirection==RIGHT) {
- guy.x += 5;
- }
- Thread.sleep(75);
- }
- catch(Exception e) {
- break;
- }
- }
- }
- public void keyPressed(KeyEvent event) {}
- public void keyReleased(KeyEvent event) {}
- public void keyTyped(KeyEvent event) {
- if (event.getKeyChar()=='a') {
- guyDirection = LEFT;
- }
- if (event.getKeyChar()=='d') {
- guyDirection = RIGHT;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment