Java在画板上用键盘控制小球上下左右移动

在这里插入图片描述
ball.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author new
 */

import java.awt.*;
public class ball {

    gamePanel gameP;
    private int x;
    private int y;
    private int speed;
    private int diameter;

    public ball(gamePanel gp) {
        gameP = gp;
        x = 50;
        y = 50;
        diameter = 10;
        speed = 10;
    }


    public void move() {


        int direction=gameP.getDirection();
        switch (direction) {
            case gamePanel.SOUTH:
                y += speed;
                break;
            case gamePanel.NORTH:
                y -= speed;
                break;
            case gamePanel.EAST:
                x += speed;
                break;
            case gamePanel.WEST:
                x -= speed;
                break;
        }

        if (x > gameP.width) {
            x = -diameter;
        }
        if (y > gameP.heigth) {
            y = -diameter;
        }
        if (x < -diameter) {
            x = gameP.width;
        }
        if (y < -diameter) {
            y = gameP.heigth;
        }

    }

    public void draw(Graphics g) {
               g.setColor(Color.blue);
              g.fillOval(x, y, diameter, diameter);
    }
}

gamePanel.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.awt.*;
import java.awt.event.*;
import java.util.*;

/**
 *
 * @author Administrator
 */
public class gamePanel extends Panel implements Runnable, KeyListener {

    public int width;
    public int heigth;
    private Image im;
    private Graphics dbg;
    private Thread gamethread;
    private static final int FPS = 50;
    private boolean running = false;
    private boolean isPaused = false;
    private int direction;
    public static final int SOUTH = 0;
    public static final int NORTH = 1;
    public static final int EAST = 2;
    public static final int WEST = 3;
    private ball sk;

    public gamePanel() {

        width = 500;
        heigth = 500;
        setBackground(Color.pink);
        setPreferredSize(new Dimension(width, heigth));

        sk = new ball(this);

        setFocusable(true);
        requestFocus();
        addKeyListener(this);

    }

    public int getDirection() {
        return direction;
    }

    public void gameStart() {
        if (!running) {
            gamethread = new Thread(this);
            gamethread.start();
        }
    }

    public void gameStop() {
        running = false;
    }

    public void gamePaint() {
        Graphics g;
        try {
            g = this.getGraphics();
            if (g != null && im != null) {
                g.drawImage(im, 0, 0, null);
            }
            g.dispose();
        } catch (Exception e) {
        }
    }

    public void gameRender() {
        if (im == null) {
            im = createImage(width, heigth);
            if (im == null) {
                System.out.println("im is null");
            } else {
                dbg = im.getGraphics();
            }
        }

        dbg.setColor(Color.pink);
        dbg.fillRect(0, 0, width, heigth);
        sk.draw(dbg);

    }

    public void gameUpdate() {

        if (!isPaused) {
            sk.move();
        }
    }

    public void run() {
        long t1,t2,dt,sleepTime;  
        long period=1000/FPS;  //计算每一次循环需要的执行时间,单位毫秒
        t1=System.nanoTime();  //保存游戏循环执行前的系统时间,单位纳秒
          
        while(true){
           gameUpdate();
           gameRender();
           gamePaint();
           t2= System.nanoTime() ; //游戏循环执行后的系统时间,单位纳秒
           dt=(t2-t1)/1000000L;  //本次循环实际花费的时间,并转换为毫秒
           sleepTime = period - dt;//计算本次循环剩余的时间,单位毫秒
           if(sleepTime<=0)        //防止sleepTime值为负数
                 sleepTime=2;
           try {     
           Thread.sleep(sleepTime); //让线程休眠,由sleepTime值决定
          } catch (InterruptedException ex) { }
             t1 = System.nanoTime();  //重新获取当前系统时间
        }
    }

    public void keyTyped(KeyEvent e) {

    }

    public void keyPressed(KeyEvent e) {
        int keycode = e.getKeyCode();
        if (keycode == KeyEvent.VK_ESCAPE) {
            running = false;
            System.out.println("key is escape");
        }
        if (keycode == KeyEvent.VK_P) {
            isPaused =!isPaused;
            System.out.println("key is P");
        }
        if (!isPaused ) {
            switch (keycode) {

                case KeyEvent.VK_DOWN:
                    direction = SOUTH;
                    System.out.println("key is down" + direction);
                    break;
                case KeyEvent.VK_UP:
                    direction = NORTH;
                    System.out.println("key is up" + direction);
                    break;
                case KeyEvent.VK_RIGHT:
                    direction = EAST;
                    System.out.println("key is right" + direction);
                    break;
                case KeyEvent.VK_LEFT:
                    direction = WEST;
                    System.out.println("key is left" + direction);
                    break;
            }
        }
    }

    public void keyReleased(KeyEvent e) {

    }

}

GameFrame.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */
import java.awt.*;
import java.awt.event.*;

public class GameFrame {

    public GameFrame() {
        Frame app = new Frame("GameFrame");

        app.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        app.setLocation(100, 100);
        gamePanel drawB = new gamePanel();
        app.add(drawB, BorderLayout.CENTER);

        app.pack();
        app.setVisible(true);
          drawB.gameStart();    
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new GameFrame();
    // TODO code application logic here
    }
}

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值