码迷,mamicode.com
首页 > 编程语言 > 详细

简易贪吃蛇[Java]

时间:2015-12-10 18:49:53      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

偶然来了兴趣,简单的制作了一下

需要的同学可以进行参考

后续的很多功能大家还可以继续完善 技术分享

图片文件 技术分享 自己更改

新建package - model  技术分享

新建Cell.java

技术分享
package model;

public class Cell {
    public int x;
    public int y;
    // d direction 方向
    public int d;
    // 设定常量:L 0 R 1 T 2 B 3
    public static final int L=0;
    public static final int R=1;
    public static final int T=2;
    public static final int B=3;
    
    public Cell(int x, int y, int d) {
        super();
        this.x = x;
        this.y = y;
        this.d = d;
    }
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
    public int getD() {
        return d;
    }
    public void setD(int d) {
        this.d = d;
    }
    @Override
    public String toString() {
        return "(" + x + ", " + y + ", " + d + ")";
    }
}
Cell.java

新建Food.java

技术分享
package model;

public class Food {
    public int x;
    public int y;
    public Food() {
        initFood();
    }
    public void initFood(){
        x=(int)(Math.random()*28)+1;
        y=(int)(Math.random()*28)+1;
    }
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
}
Food.java

新建package - run

新建Main.java

技术分享
package run;

import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

import model.Cell;
import model.Food;

@SuppressWarnings("serial")
public class Main extends JFrame implements KeyListener {
    // 物块
    public Cell[] snake;
    public Food food;
    public Cell head;
    public int width = 15;
    // 界面
    public JPanel jpanel_main;
    public JPanel jpanel_score;
    // 数值
    public static int score=0;
    public int level=1;
    //判定
    public boolean byEat=false;
    //增加图片
    public static Image bgimg1;
    public static Image bgimg2;
    public static Image snakebodyimg;
    public static Image foodimg;
    public static Image snakeheadimg;
    static{
        snakeheadimg=new ImageIcon("3.jpg").getImage();
        foodimg=new ImageIcon("4.jpg").getImage();
        bgimg1=new ImageIcon("bg1.jpg").getImage();
        bgimg2=new ImageIcon("bg2.jpg").getImage();
    }
    //游戏状态
    /*懒得写了*/
    
    
    public Main() {
        // 设定窗体基本属性
        setTitle("Snake");
        setBounds(450, 150, 600, 470);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 主界面设置
        jpanel_main = new JPanel(null) {
            @Override
            public void paint(Graphics g) {
                /* 添加背景图 */
                drawSnake(g);
                drawFood(g);
            }
        };
        jpanel_main.setBounds(0, 0, 450, 450);

        // 物块初始化
        snake = new Cell[6];
        for (int i = 0; i < snake.length; i++) {
            snake[i] = new Cell(i, 0, Cell.R);
        }
        head = snake[snake.length - 1];
        foodRandom();
        
        // 分数界面设置
        jpanel_score = new JPanel(null){
            @Override
            public void paint(Graphics g) {
                /* 添加背景图 */
                g.drawImage(bgimg2,0,0,150,450 , null);
                g.drawString("Score:"+score,0,100);
                g.drawString("Levle:"+level,0,145);
            }
        };
        jpanel_score.setBounds(450, 0, 150, 450);

        // 添加界面
        Container cp=getContentPane();//初始化容器
        cp.setLayout(null);
        cp.setBackground(Color.white);
        cp.add(jpanel_main);
        cp.add(jpanel_score);
        // 添加监听
        addKeyListener(this);
    }

    public void drawSnake(Graphics g) {
        g.setColor(Color.black);
        for (int i = 0; i < snake.length; i++) {
            if(i==snake.length-1){
//                g.setColor(Color.red);
            }
            /* 添加背景图 */
//            g.fillRect(snake[i].x * width, snake[i].y * width, width, width);
            g.drawImage(snakeheadimg,snake[i].x * width, snake[i].y * width,  width, width , null);
        }
    }
    
    public void drawFood(Graphics g) {
        g.setColor(Color.green);
        /* 添加背景图 */
        g.drawImage(foodimg,food.x * width, food.y * width,  width, width , null);
//        g.fillRect(food.x * width, food.y * width, width, width);
    }
    //snake 移动
    public void moveSnake(int direction) {
        Cell[] moveSnake = new Cell[snake.length];
        System.arraycopy(snake,1, moveSnake,0, snake.length-1);
        Cell moveCell=new Cell(head.x,head.y,head.d);
        switch (head.d) {
        case Cell.L:
            moveCell.x--;
            break;
        case Cell.R:
            moveCell.x++;
            break;
        case Cell.T:
            moveCell.y--;
            break;
        case Cell.B:
            moveCell.y++;
            break;
        }
        moveSnake[snake.length-1]=moveCell;
        snake=moveSnake;
        head=snake[snake.length-1];
        Food current=new Food();
        current.x=food.x;
        current.y=food.y;
        /* 当eat food 该如何? */
        /*(6, 21, 1)
         * 7
         * (20, 13, 1)
         * 8
         * (20, 13, 1)
         * 9
         * (20, 13, 1)
         * 10
         */
        eat(food);
        if(die()){
            System.out.println("Game over!");
        }
        repaint();
    }
    //snake eat
    public void eat(Food food){
        if(head.x==food.x&&head.y==food.y){
            snake=Arrays.copyOf(snake, snake.length+1);
            System.out.println(Arrays.toString(snake));
            Cell foodCell=new Cell(food.x,food.y,head.d);
            switch (head.d) {
            case Cell.L:
                foodCell.x--;
                break;
            case Cell.R:
                foodCell.x++;
                break;
            case Cell.T:
                foodCell.y--;
                break;
            case Cell.B:
                foodCell.y++;
                break;
            }
            System.out.println(foodCell);
            snake[snake.length-1]=foodCell;
            System.out.println(Arrays.toString(snake));
            head=snake[snake.length-1];
            System.out.println(snake.length);
            byEat=true;
            foodRandom();
            score+=100;
            if(score>=200){
                level=score/100;
            }
        }
    }
    //snake die
    public boolean die(){
        if(head.x<0||head.y<0||head.x>=30||head.y>=30){
            return true;
        }
        for (int i = 0; i < snake.length-1; i++) {
            if(head.x==snake[i].x&&head.y==snake[i].y){
                return true;
            }
        }
        return false;
    }
    public void foodRandom(){
        food = new Food();
        /* 是否放在定时器的位置 - 决定封装起来 */
        for (int i = 0; i < snake.length; i++) {
            if (snake[i].x == food.x && snake[i].y == food.y) {
                food.initFood();
            }
        }
    }
    //定时器action   后期可扩展状态等
    public void action() {
        ScheduledExecutorService ses=Executors.newScheduledThreadPool(1);
        ses.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                moveSnake(head.d);
            }
        },0,1000/level,TimeUnit.MILLISECONDS);//毫秒
        //schedule 调度 Fixe 固定的 Rate 速度
    }
    // 实现键盘监听
    @Override
    public void keyPressed(KeyEvent e) {
        // 上 38 下 40 左 37 右 39
        switch (e.getKeyCode()) {
        case 37:
            head.d = Cell.L;
            break;
        case 38:
            head.d = Cell.T;
            break;
        case 39:
            head.d = Cell.R;
            break;
        case 40:
            head.d = Cell.B;
            break;
        }
        moveSnake(head.d);
    }
    @Override
    public void keyReleased(KeyEvent e) {
    }
    @Override
    public void keyTyped(KeyEvent e) {
    }
}
Main.java

新建Test.java

技术分享
package run;

public class Test {
    public static void main(String[] args) {
        Main main=new Main();
        main.setVisible(true);
        main.action();
    }
}
Test.java

注意:涉及到图片插入的地方 可以先暂时使用fillRect测试 注释掉drawImage

简易贪吃蛇[Java]

标签:

原文地址:http://www.cnblogs.com/Zoran/p/5036788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!