Java swing 写的贪吃蛇代码200行

刚学完书上java的swing,无聊做个贪吃蛇练练, 200多行的代码也写了好几个小时 0.0!
这里写图片描述
代码整体分成三块:
* greedySnackMain:框架类
* snackWin: 面板类,这里主要就是对面板进行操作。
* Snack:蛇类
思想很简单:绘制完框架,新建一个线程让蛇跑起来就可以了。

//类greedySnackMain
package GreedySnack;

import javax.swing.JFrame;


public class greedySnackMain extends JFrame {
    snackWin snackwin;
    static final int Width = 800 , Height = 600 , LocX = 200 , LocY = 80;
    public greedySnackMain() {
        super("GreedySncak_SL");
        snackwin = new snackWin();
        add(snackwin);
        this.setSize(Width, Height);
        this.setVisible(true);
        this.setLocation(LocX, LocY);
        //snackwin.requestFocus();
    }
    public static void main(String[] args) {
        new greedySnackMain();
    }
}
//类snackWin
package GreedySnack;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JPanel;

public class snackWin extends JPanel implements ActionListener, KeyListener {
    static final int Up = 0 , Down = 1 , Left = 2 , Right = 3;
    static final int GameLocX = 50 , GameLocY = 50 , GameWidth = 700 , GameHeight = 500 , Size = 10;
    static int rx , ry , score = 0 , speed = 5;
    boolean startFlag = false;
    JButton startButton , stopButton , quitButton;
    Snack snack;
    public snackWin() {
        snack = new Snack();
        rx = (int)(Math.random() * (GameWidth - 10) + GameLocX);
        ry = (int)(Math.random() * (GameHeight - 10) + GameLocY);
        startButton = new JButton("开始");
        stopButton = new JButton("暂停");
        quitButton = new JButton("退出");
        setLayout(new FlowLayout(FlowLayout.LEFT));
        this.add(startButton);
        this.add(stopButton);
        this.add(quitButton);
        startButton.addActionListener(this);
        stopButton.addActionListener(this);
        quitButton.addActionListener(this);
        this.addKeyListener(this);
        new Thread(new snackThread()).start();  
    }
    public void paint(Graphics g)
    {
        super.paint(g);   //没有会将button刷掉
        g.setColor(Color.white);
        g.fillRect(GameLocX, GameLocY, GameWidth, GameHeight);  //刷新界面
        g.setColor(Color.black);
        g.drawRect(GameLocX, GameLocY, GameWidth, GameHeight);  //绘制边界
        g.drawString("Score: " + score + "        Speed: " + speed + "      速度最大为100" , 250, 25);
        g.setColor(Color.green);
        g.fillRect(rx, ry, 10, 10);   //食物
        snack.draw(g);
    }
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == startButton) {
            startFlag = true;
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
        }
        if(e.getSource() == stopButton) {
            startFlag = false;
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
        }
        if(e.getSource() == quitButton) {
            System.exit(0);
        }
        this.requestFocus();
    }
    public void keyPressed(KeyEvent e) {
        //System.out.println(e.getKeyCode()); 
        if(!startFlag) return ;
        switch(e.getKeyCode()) {
        case KeyEvent.VK_UP:
            if(snack.length() != 1 && snack.getDir() == Down) break;
            snack.changeDir(Up);
            break;
        case KeyEvent.VK_DOWN:
            if(snack.length() != 1 && snack.getDir() == Up) break;
            snack.changeDir(Down);
            break;
        case KeyEvent.VK_LEFT:
            if(snack.length() != 1 && snack.getDir() == Right) break;
            snack.changeDir(Left);
            break;
        case KeyEvent.VK_RIGHT:
            if(snack.length() != 1 && snack.getDir() == Left) break;
            snack.changeDir(Right);
            break;
        }
    }
    public void keyReleased(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}

    class snackThread implements Runnable
    {
        public void run() {
            while(true) {
                try {
                    Thread.sleep(100 - speed >= 0 ? 100 - speed : 0);
                    repaint();
                    if(startFlag) {
                        snack.move();
                    }
                }
                catch(InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
//类snack
package GreedySnack;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

class Node {
    private int x , y;
    public Node() {}
    public Node(int a , int b) {x = a; y = b;}
    public Node(Node tmp) {x = tmp.getX(); y = tmp.getY();}
    int getX() {return x;}
    int getY() {return y;}
    void setX(int a) {x = a;}
    void setY(int b) {y = b;}
}
public class Snack {
    static final int DIR[][] = {{0 , -1} , {0 , 1} , {-1 , 0} , {1 , 0}};
    private List<Node> lt = new ArrayList<Node>();
    private int curDir;
    public Snack() {
        curDir = 3;
        lt.add(new Node(350 , 250));
    }
    int length() {return lt.size();}
    int getDir() {return curDir;}
    void draw(Graphics g) 
    {
        g.setColor(Color.black);
        for(int i = 0; i < lt.size(); i++) {
            g.fillRect(lt.get(i).getX(), lt.get(i).getY(), 10, 10);
        }
    }
    boolean Dead() {
        for(int i = 1; i < lt.size(); i++) {
            if(lt.get(0).getX() == lt.get(i).getX() && lt.get(0).getY() == lt.get(i).getY()) 
                return true;
        }
        return false;
    }
    Node headMove()
    {
        int tx = lt.get(0).getX() + snackWin.Size * DIR[curDir][0];
        int ty = lt.get(0).getY() + snackWin.Size * DIR[curDir][1];
        if(tx > snackWin.GameLocX + snackWin.GameWidth - snackWin.Size) tx = snackWin.GameLocX;
        if(tx < snackWin.GameLocX) tx = snackWin.GameWidth + snackWin.GameLocX - snackWin.Size;
        if(ty > snackWin.GameLocY + snackWin.GameHeight - snackWin.Size) ty = snackWin.GameLocY;
        if(ty < snackWin.GameLocY) ty = snackWin.GameHeight + snackWin.GameLocY - snackWin.Size;
        Node tmp = new Node(tx, ty);
        return tmp;
    }
    void move()
    {
        Node head = headMove() , newNode = new Node();
        boolean eat = false;
        if(Math.abs(head.getX() - snackWin.rx) < 10 && Math.abs(head.getY() - snackWin.ry) < 10) {
            eat = true;
            newNode = new Node(lt.get(lt.size() - 1));
            snackWin.rx = (int)(Math.random() * (snackWin.GameWidth - 10) + snackWin.GameLocX);
            snackWin.ry = (int)(Math.random() * (snackWin.GameHeight - 10) + snackWin.GameLocY);
        }
        for(int i = lt.size() - 1; i > 0; i--) 
            lt.set(i, lt.get(i - 1));
        lt.set(0, head);
        if(Dead()) {
            JOptionPane.showMessageDialog(null, "Snake eating itself", "Message", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        if(eat) {
            lt.add(newNode);
            snackWin.score++;
            snackWin.speed++;
        }
    }
    void changeDir(int dir) {curDir = dir;}
}
  • 29
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
以下是一个简单的Java贪吃蛇代码示例: ``` import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SnakeGame extends JPanel implements ActionListener { private final int WIDTH = 300; private final int HEIGHT = 300; private final int DOT_SIZE = 10; private final int ALL_DOTS = 900; private final int RAND_POS = 29; private final int DELAY = 140; private int x[] = new int[ALL_DOTS]; private int y[] = new int[ALL_DOTS]; private int dots; private int apple_x; private int apple_y; private boolean leftDirection = false; private boolean rightDirection = true; private boolean upDirection = false; private boolean downDirection = false; private boolean inGame = true; private Timer timer; private Image ball; private Image apple; private Image head; public SnakeGame() { addKeyListener(new TAdapter()); setBackground(Color.black); setPreferredSize(new Dimension(WIDTH, HEIGHT)); setFocusable(true); loadImages(); initGame(); } private void loadImages() { ImageIcon iid = new ImageIcon(getClass().getResource("dot.png")); ball = iid.getImage(); ImageIcon iia = new ImageIcon(getClass().getResource("apple.png")); apple = iia.getImage(); ImageIcon iih = new ImageIcon(getClass().getResource("head.png")); head = iih.getImage(); } private void initGame() { dots = 3; for (int z = 0; z < dots; z++) { x[z] = 50 - z * 10; y[z] = 50; } locateApple(); timer = new Timer(DELAY, this); timer.start(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } private void doDrawing(Graphics g) { if (inGame) { g.drawImage(apple, apple_x, apple_y, this); for (int z = 0; z < dots; z++) { if (z == 0) { g.drawImage(head, x[z], y[z], this); } else { g.drawImage(ball, x[z], y[z], this); } } Toolkit.getDefaultToolkit().sync(); } else { gameOver(g); } } private void gameOver(Graphics g) { String msg = "Game Over"; Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2); } private void checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); } } private void move() { for (int z = dots; z > 0; z--) { x[z] = x[(z - 1)]; y[z] = y[(z - 1)]; } if (leftDirection) { x[0] -= DOT_SIZE; } if (rightDirection) { x[0] += DOT_SIZE; } if (upDirection) { y[0] -= DOT_SIZE; } if (downDirection) { y[0] += DOT_SIZE; } } private void checkCollision() { for (int z = dots; z > 0; z--) { if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) { inGame = false; } } if (y[0] >= HEIGHT) { inGame = false; } if (y[0] < 0) { inGame = false; } if (x[0] >= WIDTH) { inGame = false; } if (x[0] < 0) { inGame = false; } if (!inGame) { timer.stop(); } } private void locateApple() { int r = (int) (Math.random() * RAND_POS); apple_x = ((r * DOT_SIZE)); r = (int) (Math.random() * RAND_POS); apple_y = ((r * DOT_SIZE)); } @Override public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); } repaint(); } private class TAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) { leftDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) { rightDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_UP) && (!downDirection)) { upDirection = true; rightDirection = false; leftDirection = false; } if ((key == KeyEvent.VK_DOWN) && (!upDirection)) { downDirection = true; rightDirection = false; leftDirection = false; } } } } ``` 这是一个基本的贪吃蛇游戏,使用Java

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值