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; } });
相关问答
更多-
如何查询嵌套对象?(How to query nested objects?)[2022-04-13]
db.messages.find( { headers : { From: "reservations@marriott.com" } } ) 这查询headers 等于 { From: ... }文档,即不包含其他字段。 db.messages.find( { 'headers.From': "reservations@marriott.com" } ) 这只会查看headers.From字段,不受headers包含或丢失的其他字段的影响。 点符号文档 db.messages.find( { header ... -
可悲的是,位置运算符只能保持一个值。 我不认为你可以用你当前的数据结构以单个镜头执行这个更新。 您可以执行一次查找以获取第一个数组索引,然后使用位置运算符执行第二次查找,但此时您可以遍历该数组并重新保存该文档。 通过对您的集合进行一些重构,您可以将更新下载到单个操作。 检查MongooseJS 填充 。 Sadly no, the positional operator can only hold a single value. I don't think you can perform this upda ...
-
MongoDB通过自定义键查询集合并返回限制的嵌套对象(MongoDB query collection by custom key and return nested objects with limit)[2024-03-10]
Yoe可以使用值为-2 $ slice作为投影,从嵌套数组中获取最后两个文档。 db.collection.find({ "uuid": "16" }, { "location_history.loc": { $slice: -2 } }) Yoe can use $slice with value -2 as a projection to get the last two documents from nested array. db.collection.find({ "uuid": "16" }, ... -
$ projection仅适用于数组。 您需要使用$ where来评估每个文档: db.User.find( { $where: function() { for (var i=0 in this.booksRecords) { if (this.booksRecords[i].currLevel === 'nursery') { return true; } } return false; } }); $ projecti ...
-
对嵌套对象执行$lte查询的唯一正确方法是使用点符号( 这里是docs) 您的第二个查询只是检查文档是否具有指定的结构,因此它只会返回以下文档: { "since" : { "date" : { "$lte" : ISODate("2018-07-11T09:00:00Z") } } } 但它不会返回如下文件: { "since" : { "date" : ISODate("2018-07-11T09:00:00Z") } } { "since" : { "date" : { "a" : 3, "$lte ...
-
您可以使用$ group阶段按SongList项的ID对聚合进行分组,类似于以下内容: db.Albums.aggregate([ {$match: {AlbumName: 'Blurryface'}}, {$unwind: '$Songlist'}, {$group: { _id: '$_id', nPlays: {$first: '$nPlays'} } } ]) 这将按Song _id对项目进行分组,这应该会产生一系列单 ...
-
如何在MongoDB中增加具有变量名称的嵌套对象(How to increment nested objects with variable names in MongoDB)[2022-02-04]
如果你想以非动态的方式写出来,你会做: var id = Session.get('currentChat'); Threads.update(id, {$inc: {'action.unread.234567': 1}}); $inc需要使用基于partnerId的动态创建的键来获取对象,如下所示: var partnerId = 234567; var key = 'action.unread.' + partnerId; var obj = {}; obj[key] = 1; 现在obj看起来像: ... -
MongoDB:查询嵌套在集合属性中的对象数组的元素(MongoDB: Query elements of an array of objects nested in a collection property)[2022-07-01]
这应该让你开始: Race.aggregate([ { $match: { "year": req.params.year // filter out all documents that we're not interested in } }, { $project: { _id: 0 "runners": { $filter: { input: "$runners", // ... -
如果您要更新“节点”数组中您不知道位置但您知道匹配该项的“条件”的$elemMatch项目,那么您需要$elemMatch运算符以及位置$运算符。更新方: db.game.update( { "gameID" : "66f2497c-7a2b-4210-a06b-80be0e6a8fd8", "nodes": { "$elemMatch": { "g": 1, "r": 0 } } }, { "$set": { "nodes.$.c":"0", "n ...
-
MongoDB删除嵌套对象(MongoDB remove nested objects)[2022-02-25]
如果您的字段不总是以相同的顺序,您也可以使用$or查询和点表示法执行此操作: db.persons.remove({ "$or": [ { "_id.name": "name1", "_id.family": "family1" }, { "_id.name": "name2", "_id.family": "family2" }, } }) 不是mongoose语法,但你明白了。 它在逻辑上是相同的,但字段顺序不依赖于您指定为$in的完整对象。 You c ...