注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Blade

做人,做事,积极,认真……

 
 
 

日志

 
 

Java——贪吃蛇游戏  

2009-12-02 15:42:26|  分类: 问题解决 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

//贪吃蛇游戏
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

class SnakeApp {

    public static void main(String[] args) {
        SnakeFrame frame = new SnakeFrame();
        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.setSize(WIDTH, HEIGHT);
        frame.setResizable(false);
        frame.setLocation(300, 200);
        frame.setTitle("贪吃蛇 V1.0");
        frame.show();
    }
    private static final int WIDTH = 300;
    private static final int HEIGHT = 270;
}

class SnakeFrame extends JFrame {

    SnakeFrame() {

        final SnakePanel p = new SnakePanel(this);
        //添加菜单
        JMenuBar menubar = new JMenuBar();
        setJMenuBar(menubar);
        //文件选项
        JMenu fileMenu = new JMenu("文件");
        fileMenu.add(new AbstractAction("帮助") {

            public void actionPerformed(ActionEvent event) {
                JOptionPane.showConfirmDialog(
                        p, "上下左右--控制" + " ; " + "enter--暂停", "操纵说明",
                        JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE);
            }
        });
        fileMenu.add(new AbstractAction("退出") {

            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }
        });
        menubar.add(fileMenu);
        //"设置"菜单
        JMenu optionMenu = new JMenu("设置");
        //等级选项
        ButtonGroup groupDegree = new ButtonGroup();
        JRadioButtonMenuItem oneItem = new JRadioButtonMenuItem("第1级");
        JRadioButtonMenuItem twoItem = new JRadioButtonMenuItem("第2级");
        JRadioButtonMenuItem threeItem = new JRadioButtonMenuItem("第3级");
        threeItem.setSelected(true);
        JRadioButtonMenuItem fourItem = new JRadioButtonMenuItem("第4级");
        JRadioButtonMenuItem fiveItem = new JRadioButtonMenuItem("第5级");
        groupDegree.add(oneItem);
        groupDegree.add(twoItem);
        groupDegree.add(threeItem);
        groupDegree.add(fourItem);
        groupDegree.add(fiveItem);
        oneItem.addActionListener(new listener(300));
        twoItem.addActionListener(new listener(200));
        threeItem.addActionListener(new listener(100));
        fourItem.addActionListener(new listener(70));
        fiveItem.addActionListener(new listener(50));
        JMenu degreeMenu = new JMenu("等级");
        degreeMenu.add(oneItem);
        degreeMenu.add(twoItem);
        degreeMenu.add(threeItem);
        degreeMenu.add(fourItem);
        degreeMenu.add(fiveItem);
        optionMenu.add(degreeMenu);
        menubar.add(optionMenu);
        Container contentpane = getContentPane();
        contentpane.setLayout(new FlowLayout());
        contentpane.add(p);
        JButton newcmd = new JButton("新游戏");
        newcmd.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                p.newGame(speedtime);
            }
        });
        JButton stopcmd = new JButton("暂停");
        stopcmd.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                p.stopGame();
            }
        });

        JButton runcmd = new JButton("继续");
        runcmd.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                p.resumeGame();
            }
        });
        scoreField = new JTextField("0", 3);
        scoreField.setEnabled(false);
        scoreField.setHorizontalAlignment(scoreField.CENTER);
        JPanel toolPanel = new JPanel();
        toolPanel.add(newcmd);
        toolPanel.add(stopcmd);
        toolPanel.add(runcmd);
        toolPanel.add(scoreField);
        contentpane.add(toolPanel);
    }
    public JTextField scoreField;
    private long speedtime = 100;

    private class listener implements ActionListener {

        private long pause;

        listener(long pause) {
            if (pause > 10) {
                this.pause = pause;
            } else {
                this.pause = 100;
            }
        }

        public void actionPerformed(ActionEvent e) {
            speedtime = pause;
        }
    }
}

class SnakePanel extends JPanel
        implements Runnable, KeyListener {

    public SnakePanel(SnakeFrame parent) {
        this.parent = parent;
        grids = new JPanel[row][col];
        others = new LinkedList();
        snakeBody = new LinkedList();
        snakeHead = new ArrayIndexReadOnly(0, 0);
        tempBlock = new ArrayIndexReadOnly(0, 0);
        direction = new ArrayIndex(0, 1);
        setLayout(new GridLayout(row, col, 1, 1));
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                grids[i][j] = new JPanel();
                grids[i][j].setBackground(othersColor);
                add(grids[i][j]);
            }
        }
        addKeyListener(this);
    }

    public void newGame(long speedTime) {
        this.speedTime = speedTime;
        if (gameHaveExit) {
            snake.initializeV();
        } else {
            snake = new SnakeModel(row, col);
            gameHaveExit = true;
            t = new Thread(this);
            t.start();
        }
        requestFocus();
        direction.setX(0);
        direction.setY(1);
        gameScore = 0;
        updateTextFiled("" + gameScore);
        isEnd = false;
    }

    public void stopGame() {
        requestFocus();
        isEnd = true;
    }

    public void resumeGame() {
        requestFocus();
        isEnd = false;
    }

    public int getGameScore() {
        return gameScore;
    }

    private void updateTextFiled(String str) {
        ((SnakeFrame) parent).scoreField.setText(str);
    }

    private void updateBg() {
        snakeBody = snake.getSnake();
        Iterator e = snakeBody.iterator();
        while (e.hasNext()) {
            ArrayIndexReadOnly t = (ArrayIndexReadOnly) (e.next());
            grids[t.getX()][t.getY()].setBackground(bodyColor);
        }
        //设定蛇头颜色
        snakeHead = snake.getSnakeHead();
        grids[snakeHead.getX()][snakeHead.getY()].setBackground(headColor);
        //设定背景颜色
        others = snake.getOthers();
        e = others.iterator();
        while (e.hasNext()) {
            ArrayIndexReadOnly t = (ArrayIndexReadOnly) (e.next());
            grids[t.getX()][t.getY()].setBackground(othersColor);
        }
        //设定临时块的颜色
        tempBlock = snake.getTempBlock();
        grids[tempBlock.getX()][tempBlock.getY()].setBackground(tempColor);
    }

    public boolean isFocusTraversable() {
        return true;
    }
    //实现Runnable接口

    public void run() {
        while (true) {
            try {
                Thread.sleep(speedTime);
            } catch (InterruptedException e) {
            }
            if (!isEnd) {
                isEnd = !snake.move(direction);
                updateBg();
                if (snake.getReadyAddScore()) {
                    gameScore += 1;
                    updateTextFiled("" + gameScore);
                }
            }
        }
    }
    //实现KeyListener接口;;;;;;;;;;;;{

    public void keyPressed(KeyEvent event) {
        int keyCode = event.getKeyCode();
        if (gameHaveExit) {
            if (keyCode == KeyEvent.VK_LEFT) {
                direction.setX(0);
                direction.setY(-1);
            } else if (keyCode == KeyEvent.VK_RIGHT) {
                direction.setX(0);
                direction.setY(1);
            } else if (keyCode == KeyEvent.VK_UP) {
                direction.setX(-1);
                direction.setY(0);
            } else if (keyCode == KeyEvent.VK_DOWN) {
                direction.setX(1);
                direction.setY(0);
            } else if (keyCode == KeyEvent.VK_ENTER) {
                isEnd = !isEnd;
            }
        }
    }

    public void keyReleased(KeyEvent event) {
    }

    public void keyTyped(KeyEvent event) {
    }
    //实现KeyListener接口;;;;;;;;;;;;}
    //数据成员
    JFrame parent = new JFrame();
    private int row = 15;
    private int col = 25;
    private JPanel[][] grids;
    private ArrayIndex direction;
    private SnakeModel snake;
    private LinkedList snakeBody;
    private LinkedList others;
    private ArrayIndexReadOnly snakeHead;
    private ArrayIndexReadOnly tempBlock;
    private long speedTime;
    private Color bodyColor = Color.red;
    private Color headColor = Color.green;
    private Color tempColor = Color.orange;
    private Color othersColor = Color.blue;
    private int gameScore = 0;
    private boolean readyAddScore;
    private Thread t;
    private boolean isEnd;
    private static boolean gameHaveExit;
}

class SnakeModel {

    public ArrayIndexReadOnly getSnakeHead() {
        return (ArrayIndexReadOnly) (snake.getLast());
    }

    public ArrayIndexReadOnly getSnakeTail() {
        return (ArrayIndexReadOnly) (snake.getFirst());
    }

    public ArrayIndex getRuningDiriction() {
        return runingDiriction;
    }

    public LinkedList getSnake() {
        return snake;
    }

    public LinkedList getOthers() {
        return others;
    }

    public int getScore() {
        return gameScore;
    }

    public boolean getReadyAddScore() {
        return readyAddScore;
    }

    private void setSnakeHead(ArrayIndex snakeHead) {
        this.snakeHead = snakeHead;
    }

    public ArrayIndexReadOnly getTempBlock() {
        return tempBlock;
    }

    private void setTempBlock() {
        tempBlock = (ArrayIndexReadOnly) (others.get((int) (Math.random() * others.size())));
    }

    private void moveTo(Object a, LinkedList from, LinkedList to) {
        from.remove(a);
        to.add(a);
    }

    public void initializeV() {
        others.clear();
        snake.clear();
        gameScore = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                others.add(jps[i][j]);
            }
        }
        for (int i = 5; i < 8; i++) {
            moveTo(jps[5][i], others, snake);
        }
        snakeHead = new ArrayIndex(5, 7);
        //设置随机块
        tempBlock = new ArrayIndexReadOnly(0, 0);
        setTempBlock();
        //初始化运动方向
        runingDiriction = new ArrayIndex(0, 1);
    }

    public SnakeModel(int row1, int col1) {
        row = row1;
        col = col1;
        jps = new ArrayIndexReadOnly[row][col];
        snake = new LinkedList();
        others = new LinkedList();
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                jps[i][j] = new ArrayIndexReadOnly(i, j);
                //others.add(jps[i][j]);
            }
        }
        initializeV();
    }
    //如果move成功返回true,否则(结束),返回false
    //参数direction是ArrayIndex类型,
    //direction 的值:(0,1)表示向右(0,-1)表示向左
    //(1,0)表示向下(-1,0)表示向上

    public boolean move(ArrayIndex direction) {
        //判断给的方向是不是跟运行方向相反
        if (direction.reverse(runingDiriction)) {
            snakeHead.setX(snakeHead.getX() + runingDiriction.getX());
            snakeHead.setY(snakeHead.getY() + runingDiriction.getY());
        } else {
            snakeHead.setX(snakeHead.getX() + direction.getX());
            snakeHead.setY(snakeHead.getY() + direction.getY());
        }
        //如果蛇吃了随机块
        try {
            if ((snakeHead.getX() == tempBlock.getX()) && (snakeHead.getY() == tempBlock.getY())) {
                moveTo(jps[snakeHead.getX()][snakeHead.getY()], others, snake);
                setTempBlock();
                gameScore += 1;
                readyAddScore = true;
            } else {
                readyAddScore = false;
                //是否出界
                if ((snakeHead.getX() < row) && (snakeHead.getY() < col)) {
                    //如果不出界,判断是否与自身相交
                    if (snake.contains(jps[snakeHead.getX()][snakeHead.getY()])) {
                        //如果相交,游戏结束
                        return false;
                    } else {
                        //如果不相交,就把snakeHead加到snake里面,并且把尾巴移出
                        moveTo(jps[snakeHead.getX()][snakeHead.getY()], others, snake);
                        moveTo(snake.getFirst(), snake, others);
                    }
                } else {
                    //出界!游戏结束
                    return false;
                }
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            return false;
        }
        //更新运行方向
        if (!(direction.reverse(runingDiriction) || direction.equals(runingDiriction))) {
            runingDiriction.setX(direction.getX());
            runingDiriction.setY(direction.getY());
        }
        return true;
    }
    private int row, col;
    private ArrayIndex snakeHead;
    private ArrayIndexReadOnly[][] jps;
    private LinkedList snake;
    private LinkedList others;
    private ArrayIndexReadOnly tempBlock;
    private ArrayIndex runingDiriction;
    private int gameScore = 0;
    private boolean readyAddScore = false;
}

class ArrayIndex {

    private int x;
    private int y;

    ArrayIndex(int x, int y) {
        this.x = x;
        this.y = y;
    }

    int getX() {
        return x;
    }

    int getY() {
        return y;
    }

    void setX(int x) {
        this.x = x;
    }

    void setY(int y) {
        this.y = y;
    }

    public boolean equalOrRev(ArrayIndex e) {
        return ((e.getX() == getX()) && (e.getY() == getY())) || ((e.getX() == getX()) && (e.getY() == -1 * getY())) || ((e.getX() == -1 * getX()) && (e.getY() == getY()));
    }

    public boolean equals(ArrayIndex e) {
        return (e.getX() == getX()) && (e.getY() == getY());
    }

    public boolean reverse(ArrayIndex e) {
        return ((e.getX() == getX()) && (e.getY() == -1 * getY())) || ((e.getX() == -1 * getX()) && (e.getY() == getY()));
    }
}

class ArrayIndexReadOnly {

    private int x;
    private int y;

    ArrayIndexReadOnly(int x, int y) {
        this.x = x;
        this.y = y;
    }

    int getX() {
        return x;
    }

    int getY() {
        return y;
    }

    public boolean equalOrRev(ArrayIndexReadOnly e) {
        return ((e.getX() == getX()) && (e.getY() == getY())) || ((e.getX() == getX()) && (e.getY() == -1 * getY())) || ((e.getX() == -1 * getX()) && (e.getY() == getY()));

    }

    public boolean equals(ArrayIndexReadOnly e) {
        return (e.getX() == getX()) && (e.getY() == getY());
    }

    public boolean reverse(ArrayIndexReadOnly e) {
        return ((e.getX() == getX()) && (e.getY() == -1 * getY())) || ((e.getX() == -1 * getX()) && (e.getY() == getY()));
    }
}

贪吃蛇游戏 - wwq - ET@quan

网址:http://v.youku.com/v_show/id_XMTM1OTMxMjI4.html

  评论这张
 
阅读(389)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017