首页 \ 问答 \ Java抓球游戏(Java catch the ball Game)

Java抓球游戏(Java catch the ball Game)

我的学校Java项目遇到了麻烦。 计划是制作一个简单的游戏,你需要接球,如果你接球,你将获得积分。 目前我有两个问题:

  • 我不知道如何使球以随机宽度出现并使其保持在该宽度(导致随机值不断变化)。
  • 如何制作一个声明,检查捕手是否接球?

这是我目前的代码:

import instruct.*;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.Timer;

public class opdracht extends WindowPanel implements MouseMotionListener {
    List<comet> comets;
    Image afb1;
    Image afb2;
    Image comet;
    int xmuis;
    int score;
    int random;
    int h;
    int plaats;
    static int randomNum;
    private static final int D_W = 700;
    private static final int X_INC = 10;

    public opdracht() throws IOException {
        score = 0;
        h = -100;
        afb1 = ImageIO.read(new File("afb/space.jpg"));
        afb2 = ImageIO.read(new File("afb/pipe.png"));
        BufferedImage cometbuf = ImageIO.read(new File("afb/comet.png"));
        File output = new File("comet.png");
        ImageIO.write(cometbuf, "png", output);
        comet = ImageIO.read(new File("comet.png"));
        addMouseMotionListener(this);
        try {
            drawcomet();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        plaats = randomNum;
        comets = new LinkedList<>();

        Timer timer = new Timer(40, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Iterator<comet> it = comets.iterator();
                while (it.hasNext()) {
                    comet ball = it.next();
                    if (ball.h > D_W) {
                        it.remove();
                        System.out.println(comets.size());
                    } else {
                        ball.h += X_INC;
                        repaint();
                    }
                }
            }
        });
        timer.start();
    }

    public void paintComponent(Graphics g) {
        g.drawImage(afb1, 0, 0, 1200, 800, this);
        g.setColor(Color.yellow);
        g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
        g.drawString("score = " + score, 1020, 30);
        for (comet ball : comets) {
            ball.drawcomet(g);
        }
        g.drawImage(afb2, xmuis, 730, 70, 75, this);
    }

    public static void randInt(int min, int max) {
        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        randomNum = rand.nextInt((max - min) + 1) + min;

        System.out.print(randomNum);
    }

    public void drawcomet() throws InterruptedException {
        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                comets.add(new comet(comet));
            }
        }, 0, 2, TimeUnit.SECONDS);
    }

    public class comet {
        protected int h;
        Image comet;

        public comet(Image image) {
            comet = image;
        }

        public void drawcomet(Graphics g) {
            g.drawImage(comet, plaats, h, 75, 50, null);
        }
    }

    public void mouseMoved(MouseEvent e) {
        xmuis = e.getX();
        repaint();
    }

    public void mouseDragged(MouseEvent e) {
        // do something
    }

    public static void main(String[] a) throws IOException {
        new opdracht().createGUI();
    }
}

package instruct;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class WindowPanel extends JPanel {
    JFrame frame;

    public WindowPanel() {
        this.setPreferredSize(new Dimension(1200, 800));
        this.setFocusable(true);
        this.requestFocusInWindow();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // System.out.println( "class: "+ getClass().getName() );
        frame.setTitle("Space Game");
    }

    protected void createAndShowGUI() {
        frame = new JFrame();
        frame.setSize(1200, 800);
        frame.setLocation(300, 100);
        frame.setResizable(false);
        frame.add(this);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);

        // Create a new blank cursor.
        Cursor blankCursor =
                        Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, new Point(0, 0),
                                        "blank cursor");

        // Set the blank cursor to the JFrame.
        frame.getContentPane().setCursor(blankCursor);
    }

    public void createGUI() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public JFrame getFrame() {
        return frame;
    }
}

I am having trouble with my Java project for school. The plan was to make a simple game where you need to catch the ball and if you catch the ball you will get points. At the moment I have 2 problems:

  • I have no idea how I make the balls appear at a random width and make it stay at that width (cause random value is constantly changing ).
  • How can I make a statement that checks if the catcher caught the ball?

This is my current code:

import instruct.*;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.Timer;

public class opdracht extends WindowPanel implements MouseMotionListener {
    List<comet> comets;
    Image afb1;
    Image afb2;
    Image comet;
    int xmuis;
    int score;
    int random;
    int h;
    int plaats;
    static int randomNum;
    private static final int D_W = 700;
    private static final int X_INC = 10;

    public opdracht() throws IOException {
        score = 0;
        h = -100;
        afb1 = ImageIO.read(new File("afb/space.jpg"));
        afb2 = ImageIO.read(new File("afb/pipe.png"));
        BufferedImage cometbuf = ImageIO.read(new File("afb/comet.png"));
        File output = new File("comet.png");
        ImageIO.write(cometbuf, "png", output);
        comet = ImageIO.read(new File("comet.png"));
        addMouseMotionListener(this);
        try {
            drawcomet();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        plaats = randomNum;
        comets = new LinkedList<>();

        Timer timer = new Timer(40, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Iterator<comet> it = comets.iterator();
                while (it.hasNext()) {
                    comet ball = it.next();
                    if (ball.h > D_W) {
                        it.remove();
                        System.out.println(comets.size());
                    } else {
                        ball.h += X_INC;
                        repaint();
                    }
                }
            }
        });
        timer.start();
    }

    public void paintComponent(Graphics g) {
        g.drawImage(afb1, 0, 0, 1200, 800, this);
        g.setColor(Color.yellow);
        g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
        g.drawString("score = " + score, 1020, 30);
        for (comet ball : comets) {
            ball.drawcomet(g);
        }
        g.drawImage(afb2, xmuis, 730, 70, 75, this);
    }

    public static void randInt(int min, int max) {
        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        randomNum = rand.nextInt((max - min) + 1) + min;

        System.out.print(randomNum);
    }

    public void drawcomet() throws InterruptedException {
        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                comets.add(new comet(comet));
            }
        }, 0, 2, TimeUnit.SECONDS);
    }

    public class comet {
        protected int h;
        Image comet;

        public comet(Image image) {
            comet = image;
        }

        public void drawcomet(Graphics g) {
            g.drawImage(comet, plaats, h, 75, 50, null);
        }
    }

    public void mouseMoved(MouseEvent e) {
        xmuis = e.getX();
        repaint();
    }

    public void mouseDragged(MouseEvent e) {
        // do something
    }

    public static void main(String[] a) throws IOException {
        new opdracht().createGUI();
    }
}

package instruct;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class WindowPanel extends JPanel {
    JFrame frame;

    public WindowPanel() {
        this.setPreferredSize(new Dimension(1200, 800));
        this.setFocusable(true);
        this.requestFocusInWindow();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // System.out.println( "class: "+ getClass().getName() );
        frame.setTitle("Space Game");
    }

    protected void createAndShowGUI() {
        frame = new JFrame();
        frame.setSize(1200, 800);
        frame.setLocation(300, 100);
        frame.setResizable(false);
        frame.add(this);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);

        // Create a new blank cursor.
        Cursor blankCursor =
                        Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, new Point(0, 0),
                                        "blank cursor");

        // Set the blank cursor to the JFrame.
        frame.getContentPane().setCursor(blankCursor);
    }

    public void createGUI() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public JFrame getFrame() {
        return frame;
    }
}

原文:https://stackoverflow.com/questions/30718435
更新时间:2022-04-25 22:04

最满意答案

$ projection仅适用于数组。 您需要使用$ where来评估每个文档:

db.User.find( { $where: function() {
    for (var i=0 in this.booksRecords) {
        if (this.booksRecords[i].currLevel === 'nursery') {
            return true;
        }
    }
    return false;
} }); 

$ projection applies to array only. You need to use $where to evaluate each document:

db.User.find( { $where: function() {
    for (var i=0 in this.booksRecords) {
        if (this.booksRecords[i].currLevel === 'nursery') {
            return true;
        }
    }
    return false;
} }); 

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)