IT干货网

GUI实例:贪吃蛇

developer 2022年03月12日 编程设计 176 0

GUI实例:贪吃蛇

以下代码实现贪吃蛇小游戏。

代码分成三部分,分别用作承载游戏的窗口(StartGame.java),游戏界面(GamePanel.java)和图片素材(Data.java)。

StartGame.java

代码如下:

package com.cxf.gui.snake; 
 
import javax.swing.*; 
 
public class StartGame { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame(); 
        frame.setBounds(10,10,900,730); 
        frame.setResizable(false); 
        GamePanel gamePanel = new GamePanel(); 
 
        frame.add(gamePanel); 
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
        frame.setVisible(true); 
    } 
} 
 

这部分代码创建并设置frame窗口,把游戏面板放在窗口上。

GamePanel.java

代码如下:

package com.cxf.gui.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 length; 
    int[] snakeX = new int[600]; 
    int[] snakeY = new int[600]; 
    String direct; 
    boolean isStart; 
    int foodx; 
    int foody; 
    Random random = new Random(); 
    boolean isFail; 
    int score; 
 
    Timer timer = new Timer(100,this); 
 
    public GamePanel(){ 
        init(); 
        this.setFocusable(true); 
        this.addKeyListener(this); 
        timer.start(); 
    } 
 
    public void init(){ 
        length = 3; 
        snakeX[0] = 100;snakeY[0] = 100; 
        snakeX[1] = 75;snakeY[1] = 100; 
        snakeX[2] = 50;snakeY[2] = 100; 
        direct = "R"; 
        isStart = false; 
        foodx = 25 + 25*random.nextInt(34); 
        foody = 75 + 25*random.nextInt(24); 
        isFail = false; 
        score = 0; 
    } 
 
 
    @Override 
    protected void paintComponent(Graphics g) { 
        super.paintComponent(g); 
        setBackground(Color.white ); 
        //Data.header.paintIcon(this,g,25,11); 
        g.setColor(Color.black); 
        g.setFont(new Font("微软雅黑",Font.BOLD,40)); 
        g.drawString("疯~狂~贪~吃~蛇~",300,41); 
 
        g.fillRect(25,75,850,600); 
 
        Data.food.paintIcon(this,g,foodx,foody); 
 
        g.setColor(Color.blue); 
        g.setFont(new Font("微软雅黑",Font.BOLD,20)); 
        g.drawString("长度:"+length,750,35); 
 
        //draw head 
        switch (direct) { 
            case "R": 
                Data.right.paintIcon(this, g, snakeX[0], snakeY[0]); 
                break; 
            case "L": 
                Data.left.paintIcon(this, g, snakeX[0], snakeY[0]); 
                break; 
            case "U": 
                Data.up.paintIcon(this, g, snakeX[0], snakeY[0]); 
                break; 
            case "D": 
                Data.down.paintIcon(this, g, snakeX[0], snakeY[0]); 
                break; 
        } 
 
        for(int i =1;i<length;i++){ 
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);//body is always existing,just draw the first few bodies 
        } 
 
        if(!isStart){ 
            g.setColor(Color.white); 
            g.setFont(new Font("微软雅黑",Font.BOLD,40)); 
            g.drawString("按下空格以开始游戏",200,200); 
        } 
 
        if(isFail){ 
            g.setColor(Color.white); 
            g.setFont(new Font("微软雅黑",Font.BOLD,40)); 
            g.drawString("失败,按下空格以重开",200,200); 
            g.drawString("得分:"+length,200,270); 
        } 
    } 
 
 
    @Override 
    public void keyTyped(KeyEvent e) { 
 
    } 
 
    @Override 
    public void keyPressed(KeyEvent e) { 
        int keyCode = e.getKeyCode(); 
        if(keyCode==KeyEvent.VK_SPACE){ 
            if(isFail){ 
                init(); 
            }else{ 
                isStart = !isStart; 
            } 
            repaint(); 
        } 
        if(keyCode == KeyEvent.VK_UP && !direct.equals("D")){ 
            direct = "U"; 
        } 
        else if(keyCode == KeyEvent.VK_DOWN&& !direct.equals("U")) { 
            direct = "D"; 
        } 
        else if(keyCode == KeyEvent.VK_LEFT&& !direct.equals("R")){ 
            direct = "L"; 
        } 
        else if(keyCode == KeyEvent.VK_RIGHT&& !direct.equals("L")){ 
            direct = "R"; 
        } 
    } 
 
    @Override 
    public void keyReleased(KeyEvent e) { 
 
    } 
 
    @Override 
    public void actionPerformed(ActionEvent e) {//no need to add 
        if(isStart && !isFail){ 
 
            if(snakeX[0]==foodx && snakeY[0]==foody){ 
                length++; 
                foodx = 25 + 25*random.nextInt(34); 
                foody = 75 + 25*random.nextInt(24); 
            } 
 
            for(int i = length-1;i>0;i--){ 
                snakeX[i]=snakeX[i-1]; 
                snakeY[i]=snakeY[i-1]; 
            } 
 
 
            switch (direct) { 
                case "R": 
                    snakeX[0] = snakeX[0] + 25; 
                    if (snakeX[0] > 850) { 
                        //snakeX[0] = 25; 
                        isFail =true; 
                    } 
                    break; 
                case "L": 
                    snakeX[0] = snakeX[0] - 25; 
                    if (snakeX[0] < 25) { 
                        //snakeX[0] = 850; 
                        isFail =true; 
                    } 
                    break; 
                case "U": 
                    snakeY[0] = snakeY[0] - 25; 
                    if (snakeY[0] < 75) { 
                        //snakeY[0] = 650; 
                        isFail =true; 
                    } 
                    break; 
                case "D": 
                    snakeY[0] = snakeY[0] + 25; 
                    if (snakeY[0] > 650) { 
                       // snakeY[0] = 75; 
                        isFail =true; 
                    } 
                    break; 
            } 
 
            for(int i = 1;i<length;i++){ 
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) { 
                    isFail = true; 
                    break; 
                } 
            } 
 
            repaint(); 
        } 
    } 
} 
 

这部分既是游戏面板,又是监听器,所以它可以把自己(监听器)加到自己(游戏面板)上面去。

首先定义变量,创建游戏所需的变量。

接着初始化,设置游戏刚开始时的变量值。

然后用paintComponent函数在面板上作图。首先绘制标题和游戏分数记录,然后画出蛇头和蛇的身体,再画暂停时的界面和游戏失败结束时的界面。这部分内容在构造panel类时会调用一次,之后每次repaint操作都会再调用一次。

接下来是键盘监听,空格暂停或者继续或者重开,上下左右控制蛇前进的方向。

最后一个是事件监听,判断是否吃到食物以及吃到以后要做的事,蛇身前进,前进方向判断,判断游戏是否失败。这些事情是游戏进行中需要不断进行的,而计算机离散的特点使它无法做到连续不断进行,因此这里采用Timer计时器,每100毫秒进行一次事件监听所包含的操作。

Data.java

代码如下:

package com.cxf.gui.snake; 
 
import javax.swing.*; 
import java.net.URL; 
 
public class Data { 
    public static URL headerURL = Data.class.getResource("statics/head.png"); 
    public static ImageIcon header; 
 
    static { 
        assert headerURL != null; 
        header = new ImageIcon(headerURL); 
    } 
 
    public static URL upURL = Data.class.getResource("statics/up.png"); 
    public static URL downURL = Data.class.getResource("statics/down.png"); 
    public static URL leftURL = Data.class.getResource("statics/left.png"); 
    public static URL rightURL = Data.class.getResource("statics/right.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("statics/body.png"); 
    public static ImageIcon body; 
 
    static { 
        assert bodyURL != null; 
        body = new ImageIcon(bodyURL); 
    } 
 
    public static URL foodURL = Data.class.getResource("statics/food.png"); 
    public static ImageIcon food; 
 
    static { 
        assert foodURL != null; 
        food = new ImageIcon(foodURL); 
    } 
} 
 

这部分代码把图片转化为图标,便于在GamePanel中直接绘制。

输出结果:


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

在界面添加密码框