欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java实现接月饼小游戏的示例代码

时间:2023-01-11 10:45:55|栏目:JAVA代码|点击:

前言

《接月饼小游戏》是一个基于java的自制游戏,不要被月亮砸到,尽可能地多接月饼。

此小项目可用来巩固JAVA基础语法,swing的技巧用法。

主要设计

  • 设计游戏界面,用swing实现
  • 设计背景
  • 设计得分物体-月饼,碰到加一分
  • 设计障碍物-月亮,碰到会死亡
  • 监听鼠标的左右键,用来控制篮子左右移动
  • 设计积分系统
  • 将resource文件夹设为resource(Project Manage中可以设置),因为要用里面的图片

功能截图

游戏开始界面:

代码实现

游戏启动类

public class Start {
    public static void main(String[] args) throws URISyntaxException {
        new EatGame();
    }
}

核心类

public class EatGame extends JFrame implements ActionListener, MouseListener
{
    private final int WIDTH = 400;
    private final int HEIGHT = 800;
    private int score;
    private int ticks; 
    private boolean gameOver = false;
    private GameControl control; 
    private List<Moon> moons;
    private List<Cake> cakes;
    private Timer timer;
    private ChangeE changeE;
    /**
     * Constructor for objects of class FallingGame
     */
    public EatGame() throws URISyntaxException {


        changeE = new ChangeE(150, 650, "player.jpg", WIDTH);
        moons = new ArrayList<>();
        cakes = new ArrayList<>();
        addMoonAndCake();
        
        control = new GameControl(changeE, moons, cakes);
        timer = new Timer(20, this); 
        
        //add keybinds
        control.addAction("Left", -20, KeyEvent.VK_LEFT);
        control.addAction("Right", 20, KeyEvent.VK_RIGHT);
        
        //add components
        add(control);
        addMouseListener(this);
        control.addMouseListener(this);
        setTitle("吃月饼");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setSize(WIDTH, HEIGHT);
        setResizable(false);
        setVisible(true);
       
        timer.start();

    }

    /**
     * 添加月亮和月饼
     */
    public void addMoonAndCake() {
        Random r = new Random();
        int x, y;
        x = 60 + (r.nextInt(35) * 2);
        y = r.nextInt(20) + moons.size() * 30;
        Moon moon1 = new Moon(x, y, "moon.png");
        moons.add(moon1);

        x = 190 + r.nextInt(35) * 2;
        y = r.nextInt(20) + moons.size() * 30;
        Moon moon2 = new Moon(x, y, "moon.png");
        moons.add(moon2);

        x = 80 + (r.nextInt(35) * 2);
        y = r.nextInt(20) + moons.size() * 50;
        Cake cake = new Cake(x, y, "cake.png");
        cakes.add(cake);
    }

    /**
     * 更新窗口
     */
    private void updateFrame() {
        ticks++;
        for(int i = 0; i < moons.size(); i++)
        {
            Moon moon = moons.get(i);
            if(ticks % 25 == 0 && moon.getSpeed() < 10)
            {
                moon.setSpeed(moon.getSpeed() + 2);
            }
        }
        Iterator<Moon> moonIterator = moons.iterator();
        while (moonIterator.hasNext()) {
            Moon moon = moonIterator.next();
            // 超出屏幕
            if(moon.getY() > HEIGHT) {
                moonIterator.remove();
            } else
                moon.move();
        }
        Iterator<Cake> cakeIterator = cakes.iterator();
        while (cakeIterator.hasNext()) {
            Cake cake = cakeIterator.next();
            // 超出屏幕
            if(cake.getY() > HEIGHT) {
                cakeIterator.remove();
            } else
                cake.move();
        }
        if(moons.size() == 0) {
            addMoonAndCake();
        }
    }

    private boolean checkCollision() {
        Rectangle rectangle = (Rectangle) changeE.getShape();
        for(Moon moon : moons) {
            Ellipse2D circle = (Ellipse2D) moon.getShape();
            // 判断是否与圆形相撞
            if (circle.intersects(rectangle)) {
                gameOver = true;
            }
        }
        Iterator<Cake> cakeIterator = cakes.iterator();
        while (cakeIterator.hasNext()) {
            Cake cake = cakeIterator.next();
            Ellipse2D circle = (Ellipse2D) cake.getShape();
            if (circle.intersects(rectangle)) {
                score ++;   // 得分
                cakeIterator.remove();
            }
        }
        return gameOver;
    }
    public void actionPerformed(ActionEvent e)
    {
        if(gameOver) {
            timer.stop(); 
            control.drawEnd(control.getGraphics(), score);
        } else {
            //continue with game
            updateFrame();
            checkCollision();
            control.repaint(); 
        }
    }
    public void mouseClicked(MouseEvent e) {

    }
    public void mousePressed(MouseEvent e)
    {
        if(gameOver)
        {
            //reset game
            moons.clear();
            control.removeAll(); 
            control.updateUI(); 
            score = 0;
            changeE.setX(150);
            changeE.setY(650);
            addMoonAndCake();
            timer.start();
            repaint();
            gameOver = false; 
        }
    }
    public void mouseReleased(MouseEvent e)
    {
        
    }
    public void mouseEntered(MouseEvent e)
    {
        
    }
    public void mouseExited(MouseEvent e)
    {
        
    }
}

画面绘制

/**
 * 画面绘制
 */
public class GameControl extends JPanel
{
    private InputMap inputMap; 
    private ChangeE myChangeE;
    private List<Moon> moons;
    private List<Cake> cakes;


    public GameControl(ChangeE changeE, List<Moon> moons, List<Cake> cakes)
    {
        this.myChangeE = changeE;
        this.moons = moons;
        this.cakes = cakes;
        setBackground(Color.white);
        inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);  
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        // 绘制背景
        ImageIcon icon=new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("background.png"));
        Image img=icon.getImage();
        g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
        // 绘制玩家
        g.drawImage(myChangeE.getImage(), myChangeE.getX(), myChangeE.getY(), this);
        // 绘制月亮
        for(Moon moon : moons) {
            g.drawImage(moon.getImage(), moon.getX(), moon.getY(), this);
        }
        // 绘制月饼
        for (Cake cake : cakes) {
            g.drawImage(cake.getImage(), cake.getX(), cake.getY(), this);
        }
        
    }


    public void drawEnd(Graphics g, int score)
    {
        g.setColor(Color.WHITE);
        g.fillRect(50, 200, 300, 300);
        g.setColor(Color.RED);
        g.drawString("祝你中秋快乐,阖家欢乐!", 100, 300);
        g.setColor(Color.BLUE);
        g.drawString("您吃的到的月饼个数为:" + score, 100, 350);
        g.setColor(Color.BLACK);
        g.drawString("鼠标点击重玩", 100, 400);
    }


    public void addAction(String name, int deltaX, int keyCode) {
        MoveAction moveAction = new MoveAction(name, deltaX);
        inputMap.put(KeyStroke.getKeyStroke(keyCode, 0), name);
        getActionMap().put(name, moveAction);
    } 


    private class MoveAction extends AbstractAction implements ActionListener {
        private int myDeltaX;


        public MoveAction(String name, int deltaX) {
            super(name);
            myDeltaX = deltaX;
        }

        public void actionPerformed(ActionEvent e) {
            myChangeE.move(myDeltaX);
        }
    }
}

总结

通过此次的《接月饼小游戏》实现,让我对JAVA的相关知识有了进一步的了解,对java这门语言也有了比以前更深刻的认识。

java的一些基本语法,比如数据类型、运算符、程序流程控制和数组等,理解更加透彻。java最核心的核心就是面向对象思想,对于这一个概念,终于悟到了一些。

上一篇:Spring Boot 集成JWT实现前后端认证的示例代码

栏    目:JAVA代码

下一篇:springboot加载复杂的yml文件获取不到值的解决方案

本文标题:Java实现接月饼小游戏的示例代码

本文地址:http://www.codeinn.net/misctech/223419.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有