关闭

Java swing 写的贪吃蛇代码200行

标签: javaswing贪吃蛇
9672人阅读 评论(1) 收藏 举报
分类:

刚学完书上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;}
}
7
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:41859次
    • 积分:1302
    • 等级:
    • 排名:千里之外
    • 原创:89篇
    • 转载:10篇
    • 译文:0篇
    • 评论:2条
    最新评论