标题:我这个贪吃蛇的代码怎么错了。。。
只看楼主
我想成为大神
Rank: 1
等 级:新手上路
帖 子:14
专家分:0
注 册:2014-9-21
结帖率:75%
 问题点数:0 回复次数:2 
我这个贪吃蛇的代码怎么错了。。。
package 贪吃蛇;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;



public class Cell {// 格子:食物或者蛇的节点
    private int x;
    private int y;
    private Color color;// 颜色

    public Cell() {

    }

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

    public Cell(int x, int y, Color color) {
        this.color = color;
        this.x = x;
        this.y = y;
    }

    public Color getColor() {
        return color;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

        @Override
    public String toString() {
        return "[" + x + "]" + "[" + y + "]";
    }
}

public class Worm {
    private int currentDirection;
    // 蛇包含的格子
    private Cell[] cells;
    private final Color color;
    public static final int UP = 1;
    public static final int DOWN = -1;
    public static final int RIGHT = 2;
    public static final int LEFT = -2;

    // 创建对象 创建默认的蛇:(0,0)(1,0)(2,0)······(11,0)
    public Worm() {// 构造器初始化对象
        color = Color.pink;// 蛇的颜色
        cells = new Cell[12];// 创建数组对象
        for (int x = 0, y = 0, i = 0; x < 12; x++) {
            // for(int y=0;;){}
            cells[i++] = new Cell(x, y, color);// 添加数组元素
        }
        currentDirection = DOWN;
    }

    public boolean contains(int x, int y) {
            // 数组迭代
            for (Cell cell : cells) {
                if (cell.getX() == x && cell.getY() == y) {
                    return true;
                }
            }
        return false;
    }

        @Override
    public String toString() {
        return Arrays.toString(cells);
    }

    public void creep() {
        for (int i = this.cells.length - 1; i >= 1; i--) {
            cells[i] = cells[i - 1];
        }

        cells[0] = createHead(currentDirection);
    }// 按照默认方法爬一步

    private Cell createHead(int direction) {// 根据方向,和当前(this)的头结点,创建新的头结点
        int x = cells[0].getX();
        int y = cells[0].getY();
        switch (direction) {
        case DOWN:
            y++;
            break;
        case UP:
            y--;
            break;
        case RIGHT:
            x++;
            break;
        case LEFT:
            x--;
            break;

        }
        return new Cell(x, y);
    }

    /**
     * food 食物
     *
     * @param food
     * @return
     */
    public boolean creep(Cell food) {
        Cell head = createHead(currentDirection);
        boolean eat = head.getX() == food.getX() && head.getY() == food.getY();
        if (eat) {
            Cell[] ary = Arrays.copyOf(cells, cells.length + 1);
            cells = ary;// 丢弃原数组
        }
        for (int i = cells.length - 1; i >= 1; i--) {
            cells[i] = cells[i - 1];
        }
        cells[0] = head;
        return eat;
    }

    // 吃到东西就变长一格
    public boolean creep(int direction, Cell food) {

        if (currentDirection + direction == 0) {
            return false;
        }
        this.currentDirection = direction;
        Cell head = createHead(currentDirection);
        boolean eat = head.getX() == food.getX() && head.getY() == food.getY();
        if (eat) {
            Cell[] ary = Arrays.copyOf(cells, cells.length + 1);
            cells = ary;// 丢弃原数组
        }
        for (int i = cells.length - 1; i >= 1; i--) {
            cells[i] = cells[i - 1];
        }
        cells[0] = head;
        return eat;
    }

    // 检测在新的运动方向上是否能够碰到边界和自己(this 蛇)
    public boolean hit(int direction) {
        // 生成下个新头节点位置
        // 如果新头节点出界返回true,表示碰撞边界
        // ···············
        if (currentDirection + direction == 0) {
            return false;
        }
        Cell head = createHead(direction);
        if (head.getX() < 0 || head.getX() >= WormStage.COLS || head.getY() < 0
                || head.getY() >= WormStage.ROWS) {
            return true;
        }
        for (int i = 0; i < cells.length - 1; i++) {
            if (cells[i].getX() == head.getX()
                    && cells[i].getY() == head.getY()) {
                return true;
            }
        }
        return false;
    }

    public boolean hit() {
        return hit(currentDirection);
    }

    // 为蛇添加会制方法
    // 利用来自舞台面板的画笔绘制蛇
    public void paint(Graphics g) {
        g.setColor(this.color);
            for (Cell cell : cells) {
                g.fill3DRect(cell.getX() * WormStage.CELL_SIZE, cell.getY()
                        * WormStage.CELL_SIZE, WormStage.CELL_SIZE,
                        WormStage.CELL_SIZE, true);
            }
    }
}




    public class WormStage extends JPanel {
    /** 舞台的列数 */
    public static final int COLS = 35;
    /** 舞台的行数 */
    public static final int ROWS = 35;
    /** 舞台格子的大小 */
    public static final int CELL_SIZE = 10;
    private Worm worm;
    private Cell food;

    public WormStage() {
        worm = new Worm();
        food = createFood();
    }

    /**
     * 随机生成食物,要避开蛇的身体 1 生成随机数 x, y 2 检查蛇是否包含(x,y)
     * 3 如果包含(x,y) 返回 1 4 创建食物节点
     * */
    private Cell createFood() {
        Random random = new Random();
        int x, y;
        do {
            x = random.nextInt(COLS);// COLS列数
            y = random.nextInt(ROWS);// WOWS行数
        } while (worm.contains(x, y));
        return new Cell(x, y, Color.green);// 食物颜色
    }

    /** 初始化的舞台单元测试 */
    public static void test() {
        WormStage stage = new WormStage();
        System.out.println(stage.worm);
        System.out.println(stage.food);
    }

    /**
     * 重写JPanel绘制方法 paint:绘制,绘画,涂抹 Graphics 绘图,
     * 理解为:绑定到当前面板的画笔
     */
        @Override
    public void paint(Graphics g) {
        // 添加自定义绘制!
        // 绘制背景
        g.setColor(Color.darkGray);// 背景色
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.cyan);// 边框上的颜色
        // draw 绘制 Rect矩形
        g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
        // 绘制食物
        g.setColor(food.getColor());
        // fill 填充 3D 3维 Rect矩形 突起的立体按钮形状
        g.fill3DRect(food.getX() * CELL_SIZE, food.getY() * CELL_SIZE,
                CELL_SIZE, CELL_SIZE, true);
        // 绘制蛇
        worm.paint(g);// 让蛇自己去利用画笔绘制
    }

    private Timer timer;

    /**
     * 启动定时器驱动蛇的运行 1 检查碰撞是否将要发生
     * 2 如果发生碰撞:创建新的蛇和食物,重写开始
     * 3 如果没有碰撞就爬行,并检查是否能够吃到食物
     * 4如果吃到食物:重新创建新的食物
     * 5 启动重新绘制界面功能 repaint() 更新界面显示效果! repaint()
     * 方法会尽快调用paint(g) 更新界面!
     */
    private void go() {
        if (timer == null)
            timer = new Timer();
        timer.schedule(new TimerTask() {
                        @Override
            public void run() {
                if (worm.hit()) {// 如果蛇碰到边界或自己
                    worm = new Worm();// 创建新的蛇
                    food = createFood();// 创建新食物
                } else {// 如果没有碰到自己
                    boolean eat = worm.creep(food);
                    // 蛇向前(当前方向)爬行,返回结果表示是否吃到食物
                    if (eat) {// 如果吃到食物,就生成新食物
                        food = createFood();
                    }
                }
                repaint();
            }
        }, 0, 1000 / 5);
        this.requestFocus();
        this.addKeyListener(new KeyAdapter() {
                        @Override
            public void keyPressed(KeyEvent e) {
                int key = e.getKeyCode();
                switch (key) {
                case KeyEvent.VK_UP:
                    creepForFood(Worm.UP);
                    break;
                case KeyEvent.VK_DOWN:
                    creepForFood(Worm.DOWN);
                    break;
                case KeyEvent.VK_LEFT:
                    creepForFood(Worm.LEFT);
                    break;
                case KeyEvent.VK_RIGHT:
                    creepForFood(Worm.RIGHT);
                    break;
                }
            }

        });
    }

    private void creepForFood(int direction) {
        if (worm.hit(direction)) {
            worm = new Worm();
            food = createFood();
        } else {
            boolean eat = worm.creep(direction, food);
            if (eat) {
                food = createFood();
            }
        }
    }

    /**
     * @param args 软件启动的入口方法 */
    public static void main(String[] args) {
        // 启动软件....
        JFrame frame = new JFrame("贪吃蛇");// 一个画框对象
        frame.setSize(450, 480);// size 大小,setSize 设置大小
        // frame.setLocation(100,50);//Locationq位置
        frame.setLocationRelativeTo(null);// 居中
        // 设置默认的关闭操作为在关闭时候离开软件
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);// Visible可见的 设置可见性
        frame.setLayout(null);// 关闭默认布局管理,避免面板充满窗口

        WormStage stage = new WormStage();
        // System.out.println("CELL_SIZE * COLS:"+CELL_SIZE * COLS);
        stage.setSize(CELL_SIZE * COLS, CELL_SIZE * ROWS);
        stage.setLocation(40, 50);
        stage.setBorder(new LineBorder(Color.BLACK));
        frame.add(stage);// 在窗口添加舞台

        stage.go();// 启动定时器驱动蛇自动运行
    }
}
搜索更多相关主题的帖子: private package 贪吃蛇 public import 
2014-10-10 07:15
日知己所无
Rank: 11Rank: 11Rank: 11Rank: 11
等 级:贵宾
威 望:38
帖 子:427
专家分:2071
注 册:2014-3-22
得分:0 
什么现象?
2014-10-10 20:56



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-437051-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.107463 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved