Advertisement
Guest User

Untitled

a guest
Feb 16th, 2013
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.80 KB | None | 0 0
  1.  
  2.  
  3. import java.awt.Color;
  4. import java.awt.Graphics;
  5. import java.awt.Image;
  6. import java.awt.event.*;
  7. import java.util.Random;
  8.  
  9. import javax.swing.JApplet;
  10.  
  11. @SuppressWarnings("serial")
  12. public class MovingBox extends JApplet implements Runnable, KeyListener
  13. {
  14.     int gameStatus;
  15.     int boxX = 150, boxY = 100;
  16.     private Image dbImage;
  17.     private Graphics dbg;
  18.     public void init()
  19.     {
  20.         this.addKeyListener(this);
  21.         this.setSize(440,440);
  22.     }
  23.  
  24.     public void start()
  25.     {
  26.         Thread th = new Thread(this);
  27.         th.start();
  28.     }
  29.  
  30.     public void run()
  31.     {
  32.         int directionX = 0;
  33.         int directionY = 0;
  34.    
  35.         while (gameStatus ==0 ) {
  36.             if (gameStatus ==1){break;}
  37.         }
  38.        
  39.         for (int i=1 ; i<1000000; i++){
  40.        
  41.             if ( i % 200 < 100 ){
  42.                 directionX = 1;
  43.             }
  44.             if ( i % 200 > 100 && i %200 <200  ){
  45.                 directionX = -1;
  46.             }
  47.            
  48.             boxX += directionX;
  49.             boxY += directionY;
  50.             try {
  51.                 Thread.sleep(10);
  52.             } catch (InterruptedException e) {
  53.                 // TODO Auto-generated catch block
  54.                 e.printStackTrace();
  55.             }
  56.         repaint();
  57.     }}
  58.    
  59.      public void paint(Graphics g){
  60.         g.setColor(Color.white);
  61.         g.fillRect(20,20,400,400);
  62.         g.setColor(Color.BLUE);
  63.         g.fillRect(boxX, boxY, 30, 30);
  64.      } 
  65.        
  66.     public void update(Graphics g)
  67.     {
  68.         if (dbImage == null){
  69.             dbImage = createImage (this.getSize().width, this.getSize().height);
  70.             dbg = dbImage.getGraphics ();
  71.         }
  72.         dbg.setColor (getBackground ());
  73.         dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
  74.         dbg.setColor (getForeground());
  75.         paint (dbg);
  76.         g.drawImage (dbImage, 0, 0, this);
  77.     }
  78.    
  79.     public void keyTyped(KeyEvent e) {}
  80.     public void keyReleased(KeyEvent arg0) {}
  81.     public void keyPressed(KeyEvent e) {
  82.         int key = e.getKeyCode();  
  83.     if(gameStatus==0) {
  84.             if(key==KeyEvent.VK_SPACE) {
  85.                 gameStatus = 1;
  86.             }
  87.         }
  88.     }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement