Java编写简易贪吃蛇

Java编写简易贪吃蛇

先写一个启动程序

import javax.swing.*;
//游戏主启动类
public class StartGame {
    public static void main(String[] args) {
        JFrame frame= new JFrame();

        frame.setTitle("贪吃蛇1.0");
        frame.setBounds(10,10,900,725);
        frame.setResizable(false);    //窗口大小不可变
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(new GamePanel());
        frame.setVisible(true);

    }
}

绘制游戏的面板

package com.kevin.lesson.Snake;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;

//游戏面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {

    int lenth; //蛇的长度
    int[] snakeX= new int[600];  //蛇的横坐标
    int[] snakeY= new int[500]; //蛇的纵坐标
    String fx ;                //R右 L左 U上 D下
    boolean isStart = false;  //游戏是否开始
    Timer timer = new Timer(100, this);
    //定义一个食物
    int foodx;
    int foody;
    Random random = new Random();

    boolean isFail = false;     //判断死亡
    int score;                //积分系统


    //构造器
    public GamePanel(){
        init();
        this.setFocusable(true);
        this.addKeyListener(this);
        timer.start();
    }

    //初始化数据
    public void init(){
        lenth =3;
        snakeX[0]=100; snakeY[0]=100;
        snakeX[1]=75;  snakeY[1]=100;
        snakeX[2]=50;  snakeY[2]=100;
        fx="R";
        foodx=25 + 25* random.nextInt(32);
        foody=75 + 25* random.nextInt(22);
        score=0;
    }

    //绘制画板
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);  //清屏
        //绘制静态面板
        this.setBackground(Color.WHITE);
        Data.head.paintIcon(this,g,25,0);
        g.fillRect(25,75,850,600);

        //画一条静态的蛇
        if (fx.equals("R")){
            Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (fx.equals("L")){
            Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (fx.equals("U")){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (fx.equals("D")){
            Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }

        for (int i = 1; i <lenth ; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }

        //画积分
        g.setColor(Color.BLACK);
        g.setFont(new Font("微软雅黑",Font.BOLD,20));
        g.drawString("分数"+score,750,50);

        //画食物
        Data.food.paintIcon(this,g,foodx,foody);

        //游戏提示:是否开始
        if (isStart==false){
            g.setColor(Color.WHITE);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("按下空格开始",350,350);
        }
        //失败提醒
        if (isFail){
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("游戏失败,按下空格开始",250,350);
        }
    }
    //接收键盘的输入:监听
    @Override
    public void keyTyped(KeyEvent e) {
        //键盘按下并弹起,敲击
    }
    @Override
    public void keyPressed(KeyEvent e) {
        //键盘按下未弹起
        int keyCode = e.getKeyCode();
        if (keyCode==KeyEvent.VK_SPACE){
            if (isFail){
                isFail=false;
                init();
            }else {
                isStart= !isStart;
            }
            repaint();   //刷新界面
        }
        if (keyCode==KeyEvent.VK_UP){
            fx="U";
        }else if (keyCode==KeyEvent.VK_DOWN){
            fx="D";
        }else if (keyCode==KeyEvent.VK_RIGHT){
            fx="R";
        }else if (keyCode==KeyEvent.VK_LEFT){
            fx="L";
        }

    }
    @Override
    public void keyReleased(KeyEvent e) {
         //键盘弹起
    }
    //定时器 监听时间
    @Override
    public void actionPerformed(ActionEvent e) {
        //游戏处于开始状态,并且游戏没有结束
        if (isStart &&isFail==false){
            for (int i = lenth-1; i >0 ; i--) {
                snakeX[i]=snakeX[i-1];
                snakeY[i]=snakeY[i-1];
            }

            //通过控制器让头部移动
            if (fx.equals("R")){
                snakeX[0]=snakeX[0]+25;
                if (snakeX[0]>900){ snakeX[0]=25; }
            }else if (fx.equals("L")){
                snakeX[0]=snakeX[0]-25;
                if (snakeX[0]<25){ snakeX[0]=900; }
            }else if (fx.equals("U")){
                snakeY[0]=snakeY[0]-25;
                if (snakeY[0]<75){ snakeY[0]=650; }
            }else if (fx.equals("D")){
                snakeY[0]=snakeY[0]+25;
                if (snakeY[0]>650){ snakeY[0]=75; }
            }
            //如果蛇头和身体重叠
            if (snakeX[0]==foodx && snakeY[0]==foody){
                lenth++;
                score=score + 10;
                foodx=25 + 25 * random.nextInt(32);
                foody=75 + 25 * random.nextInt(22);
            }
            //结束判断
            for (int i = 1; i <lenth ; i++) {
                if (snakeX[0]==snakeX[i] && snakeY[0]==snakeY[i]){
                    isFail=true;
                }
            }
            repaint();
        }
        timer.start();
    }
}

创建一个类存放数据,小蛇的图像

//图片存放在同目录下,直接调用即可
import javax.swing.*;
import java.net.URL;

public class Data {
    public static URL headURL =Data.class.getResource("Static/head3.png");  //一个标题
    public static ImageIcon head = new ImageIcon(headURL);

    public static URL upURL =Data.class.getResource("Static/up2.png");    //蛇头向上
    public static URL downURL =Data.class.getResource("Static/down2.png"); //蛇头向下
    public static URL leftURL =Data.class.getResource("Static/left2.png");  //蛇头向左
    public static URL rightURL =Data.class.getResource("Static/right2.png");  //蛇头向右
    public static ImageIcon up = new ImageIcon(upURL);
    public static ImageIcon down = new ImageIcon(downURL);
    public static ImageIcon left = new ImageIcon(leftURL);
    public static ImageIcon right = new ImageIcon(rightURL);

    public static URL bodyURL =Data.class.getResource("Static/body2.png");   //蛇身体
    public static ImageIcon body= new ImageIcon(bodyURL);
    public static URL foodURL =Data.class.getResource("Static/food.png");     //食物
    public static ImageIcon food= new ImageIcon(foodURL);

    public Data(long currentTimeMillis) {
    }
}
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class snate extends JFrame implements KeyListener,Runnable { JLabel j; Canvas j1; public static final int canvasWidth = 200; public static final int canvasHeight = 300; public static final int nodeWidth = 10; public static final int nodeHeight = 10; //SnakeModel se=null; //222222 // boolean[][] matrix; LinkedList nodeArray = new LinkedList();//表 Node food;//节点 int maxX; int maxY; int direction = 2; boolean running = false; int timeInterval = 200; double speedChangeRate = 0.75; boolean paused = false; int score = 0; int countMove = 0; // UP and DOWN should be even // RIGHT and LEFT should be odd public static final int UP = 2; public static final int DOWN = 4; public static final int LEFT = 1; public static final int RIGHT = 3; snate() { super(); //setSize(500,400); Container c=getContentPane(); j=new JLabel("Score:"); c.add(j,BorderLayout.NORTH); j1=new Canvas(); j1.setSize(canvasWidth+1,canvasHeight+1); j1.addKeyListener(this); c.add(j1,BorderLayout.CENTER); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); JLabel j2; j2 = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER); p1.add(j2, BorderLayout.NORTH); j2 = new JLabel("ENTER or R or S for start;", JLabel.CENTER); p1.add(j2, BorderLayout.CENTER); j2 = new JLabel("SPACE or P for pause",JLabel.CENTER); p1.add(j2, BorderLayout.SOUTH); c.add(p1,BorderLayout.SOUTH); addKeyListener(this); pack(); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); // begin(); // //2222222 // this.gs = gs; this.maxX = maxX; this.maxY = maxY; // initial matirx matrix = new boolean[maxX][]; for(int i=0; i<maxX; ++i){ matrix[i] = new boolean[maxY]; Arrays.fill(matrix[i],false); } // initial the snake int initArrayLength = maxX > 20 ? 10 : maxX/2; for(int i = 0; i < initArrayLength; ++i){ int x = maxX/2+i; int y = maxY/2; nodeArray.addLast(new Node(x, y)); matrix[x][y] = true; } food = createFood(); matrix[food.x][food.y] = true; } public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_UP) { //se.changeDirection(SnakeModel.UP); } if(e.getKeyCode()==KeyEvent.VK_DOWN) { //se.changeDirection(SnakeModel.DOWN); } if(e.getKeyCode()==KeyEvent.VK_LEFT) { //se.changeDirection(SnakeModel.LEFT); } if(e.getKeyCode()==KeyEvent.VK_RIGHT) { //se.changeDirection(SnakeModel.RIGHT); } if(e.getKeyCode()==KeyEvent.VK_R||e.getKeyCode()==KeyEvent.VK_S||e.getKeyCode()==KeyEvent.VK_ENTER) { } } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void repaint() { Graphics g = j1.getGraphics(); //背景 g.setColor(Color.red); g.fillRect(0,0,canvasWidth,canvasHeight); //蛇 //g.setColor(Color.BLUE); } public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(10,10,10,10); } // //222222 // public void changeDirection(int newDirection){ if (direction % 2 != newDirection % 2){ direction = newDirection; } } public boolean moveOn(){ Node n = (Node)nodeArray.getFirst(); int x = n.x; int y = n.y; switch(direction){ case UP: y--; break; case DOWN: y++; break; case LEFT: x--; break; case RIGHT: x++; break; } if ((0 <= x && x < maxX) && (0 <= y && y < maxY)){ if (matrix[x][y]){ if(x == food.x && y == food.y){ nodeArray.addFirst(food); int scoreGet = (10000 - 200 * countMove) / timeInterval; score += scoreGet > 0? scoreGet : 10; countMove = 0; food = createFood(); matrix[food.x][food.y] = true; return true; } else return false; } else{ nodeArray.addFirst(new Node(x,y)); matrix[x][y] = true; n = (Node)nodeArray.removeLast(); matrix[n.x][n.y] = false; countMove++; return true; } } return false; } public void run(){ running = true; while (running){ try{ Thread.sleep(timeInterval); } catch(Exception e){ break; } if(!paused){ if (moveOn()){ gs.repaint(); } else{ JOptionPane.showMessageDialog( null, "you failed", "Game Over", JOptionPane.INFORMATION_MESSAGE); break; } } } running = false; } private Node createFood(){ int x = 0; int y = 0; do{ Random r = new Random(); x = r.nextInt(maxX); y = r.nextInt(maxY); }while(matrix[x][y]); return new Node(x,y); } public void speedUp(){ timeInterval *= speedChangeRate; } public void speedDown(){ timeInterval /= speedChangeRate; } public void changePauseState(){ paused = !paused; } public String toString(){ String result = ""; for(int i=0; i<nodeArray.size(); ++i){ Node n = (Node)nodeArray.get(i); result += "[" + n.x + "," + n.y + "]"; } return result; } } class Node{ int x; int y; Node(int x, int y){ this.x = x; this.y = y; } } public static void main(String[] args) { //Graphics g=j1.getGraphics(); snate s=new snate(); //s.draw_something(g); //s.setVisible(true); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值