下载安卓APP箭头
箭头给我发消息

客服QQ:3315713922

如何设计出贪吃蛇游戏?

作者:课课家教育     来源: http://www.kokojia.com点击数:1956发布时间: 2018-11-27 14:07:35

标签: JAVAjava游戏设计游戏制作

大神带你学编程,欢迎选课

  如何设计出贪吃蛇游戏?

  本次教程我们最主要的学习目的是设计出贪吃蛇游戏,大家可以根据这个学习目标,进行对课程的理解。

  学习目标:

  1.开发出贪吃蛇游戏

  2.阅读并理解贪吃蛇游戏代码

  3.参考贪吃蛇游戏,自己开发出类似的游戏

  一.贪吃蛇游戏开发

  1.新建一个项目GameFrame,再创建一个主类GameFrame

  代码如下:

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.setResizable(false);

        app.setVisible(true);

        drawB.gameStart();

    }

 

    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        new GameFrame();

    // TODO code application logic here

    }

}

 

  2.创建一个类GamePanel,代码如下:

import java.awt.*;

import java.awt.event.*;

 

 

/**

 *

 * @author Administrator

 */

public class GamePanel extends Panel implements Runnable, KeyListener{

 

 

    public int width;

    public int heigth;

    public int incre=1;

    private Image im;

    private Graphics dbg;

    private Thread gamethread;

    private static final int FPS = 30;

    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 Snake sk;

    private Food bk;

 

    public GamePanel() {

 

        width = 300;

        heigth = 300;

        setPreferredSize(new Dimension(width, heigth));

 

        sk = new Snake(this);

        bk = new Food(this, sk);

 

        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.white);

        dbg.fillRect(0, 0, width, heigth);

        sk.draw(dbg);

        bk.draw(dbg);

 

    }

 

    public void gameUpdate() {

 

        if (!isPaused) {

            sk.update();

            bk.update();

 

        }

    }

 

    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_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) {

    }

}

  3.创建类:Food,代码如下:

import java.awt.*;

import java.util.Random;

 

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

/**

 *

 * @author new

 */

public class Food {

 

    public Point location;

    public Point size;

    private GamePanel gameP;

    private Snake snk;

    private Random rand;

 

    public Food(GamePanel gp, Snake sk) {

        gameP = gp;

        snk = sk;

        rand = new Random();

        location = new Point(Math.abs(rand.nextInt() % gameP.width), Math.abs(rand.nextInt() % gameP.heigth));

        size = new Point(sk.diameter, sk.diameter);

    }

 

    public void update() {

        if ((Math.abs((snk.x + snk.diameter / 2) - (location.x + size.x / 2)) < snk.diameter) &&

                (Math.abs((snk.y + snk.diameter / 2) - (location.y + size.y / 2)) < snk.diameter)) {

            location = new Point(Math.abs(rand.nextInt() % gameP.width), Math.abs(rand.nextInt() % gameP.heigth));

            if (snk.length < Snake.MAXLENTH) {

                snk.length++;

            }

        }

    }

 

    public void draw(Graphics g) {

        g.setColor(Color.black);

        g.fillRect(location.x, location.y, size.x, size.y);

    }

}

 

  4.创建类Snake,代码如下:

import java.awt.*;

 

 

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

/**

 *

 * @author new

 */

public class Snake {

 

    GamePanel gameP;

    private Point[] body;

    public static final int MAXLENTH = 20;

    private int head;

    private int tail;

    public int length;

    private int speed;

    public int x;

    public int y;

    public int diameter;

 

    public Snake(GamePanel gp) {

        gameP = gp;

        body = new Point[MAXLENTH];

        head = -1;

        tail = -1;

        length = 1;

        speed = 3;

        x = 50;

        y = 50;

        diameter = 10;

    }

 

    public void update() {

 

 

        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;

        }

 

        head = (head + 1) % body.length;

 

        tail = (head + body.length - length + 1) % body.length;

 

        body[head] = new Point(x, y);

 

    }

 

    public void draw(Graphics g) {

        g.setColor(Color.blue);

        if (length > 1) {

            int i = tail;

            while (i != head) {

                g.fillRect(body[i].x, body[i].y, diameter, diameter);

                i = (i + 1) % body.length;

            }

        }

 

        g.setColor(Color. blue);

        g.fillRect(body[head].x, body[head].y, diameter, diameter);

    }

}

 

  保存全部,运行,试玩一下游戏,并自行理解代码.

  小编结语:其实,这个游戏的java代码并不难,最主要是大家能够好好熟悉一下游戏框架,并在此框架上,自行设计自己喜欢的游戏。

赞(12)
踩(0)
分享到:
华为认证网络工程师 HCIE直播课视频教程