java – 战舰游戏 – 船舶重叠
发布时间:2020-12-15 00:50:36 所属栏目:Java 来源:网络整理
导读:我正在使用ACM库在 Java中编写一个简单的战舰游戏. 游戏开始后,应该将船只放在画布上的随机位置,但问题是船只可能会互相覆盖,这在游戏中是不允许的.如何避免将船放在彼此之上? 我的代码是: private void putSmallShips() { for (int i = 0; i SMALL_SHIP_Q
我正在使用ACM库在
Java中编写一个简单的战舰游戏.
游戏开始后,应该将船只放在画布上的随机位置,但问题是船只可能会互相覆盖,这在游戏中是不允许的.如何避免将船放在彼此之上? 我的代码是: private void putSmallShips() { for (int i = 0; i < SMALL_SHIP_QUANTITY; i++){ smallShip = new GRect(SMALL_SHIP_WIDTH,SHIP_HEIGHT); int x = rgen.nextInt(10,510); int y = rgen.nextInt(10,510); while (true){ gobj = getElementAt(x,y); if (gobj == null) break; x = rgen.nextInt(10,510); y = rgen.nextInt(10,510); } smallShip.setLocation(x,y); add(smallShip); } } private void putMiddleShips() { for (int i = 0; i < MIDDLE_SHIP_QUANTITY; i++){ middleShip = new GRect(MIDDLE_SHIP_WIDTH,530); int y = rgen.nextInt(10,530); while (true){ gobj = getElementAt(x,y); if (gobj == null) break; System.out.println("opa!"); x = rgen.nextInt(10,530); y = rgen.nextInt(10,530); } x = x + i * 10; y = y + i * 10; middleShip.setLocation(x,y); add(middleShip); } } private void putBigShips() { for (int i = 0; i < BIG_SHIP_QUANTITY; i++){ bigShip = new GRect(BIG_SHIP_WIDTH,550); int y = rgen.nextInt(10,550); while (true){ gobj = getElementAt(x,550); y = rgen.nextInt(10,550); } bigShip.setLocation(x,y); add(bigShip); } } 如你所见,我在for循环中放了一个while循环,但它没有帮助. 解决方法
首先,我建议你拆分模型层和表示层.
换句话说,您可以定义类BattleShip,该类将保存船舶位置,大小和另一个属性,它还可以包含检查它是否与另一艘船相交的方法. 然后,只有当实例不与集合中存在的任何实例相交时,您才可以创建实例并将它们添加到集合中. 然后你可以一次性在屏幕上渲染它们. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |