Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Image;
- import java.awt.event.*;
- import java.util.Random;
- import javax.swing.JApplet;
- @SuppressWarnings("serial")
- public class MovingBox extends JApplet implements Runnable, KeyListener
- {
- int gameStatus;
- int boxX = 150, boxY = 100;
- private Image dbImage;
- private Graphics dbg;
- public void init()
- {
- this.addKeyListener(this);
- this.setSize(440,440);
- }
- public void start()
- {
- Thread th = new Thread(this);
- th.start();
- }
- public void run()
- {
- int directionX = 0;
- int directionY = 0;
- while (gameStatus ==0 ) {
- if (gameStatus ==1){break;}
- }
- for (int i=1 ; i<1000000; i++){
- if ( i % 200 < 100 ){
- directionX = 1;
- }
- if ( i % 200 > 100 && i %200 <200 ){
- directionX = -1;
- }
- boxX += directionX;
- boxY += directionY;
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- repaint();
- }}
- public void paint(Graphics g){
- g.setColor(Color.white);
- g.fillRect(20,20,400,400);
- g.setColor(Color.BLUE);
- g.fillRect(boxX, boxY, 30, 30);
- }
- public void update(Graphics g)
- {
- if (dbImage == null){
- dbImage = createImage (this.getSize().width, this.getSize().height);
- dbg = dbImage.getGraphics ();
- }
- dbg.setColor (getBackground ());
- dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
- dbg.setColor (getForeground());
- paint (dbg);
- g.drawImage (dbImage, 0, 0, this);
- }
- public void keyTyped(KeyEvent e) {}
- public void keyReleased(KeyEvent arg0) {}
- public void keyPressed(KeyEvent e) {
- int key = e.getKeyCode();
- if(gameStatus==0) {
- if(key==KeyEvent.VK_SPACE) {
- gameStatus = 1;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement