Java – battleship game – ship overlap
•
Java
I am using ACM library to write a simple warship game in Java
My code is: @ h_ 502_ 4@
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); } }
As you can see, I put a while loop in the for loop, but it doesn't help@ H_ 502_ 4@
Solution
First, I suggest you split the model layer and the presentation layer
In other words, you can define the class battleship, which will save the ship position, size and another attribute. It can also contain methods to check whether it intersects with another ship@ H_ 502_ 4@
Then, you can create instances and add them to the collection only if they do not intersect any instances that exist in the collection@ H_ 502_ 4@
Then you can render them on the screen at once@ H_ 502_ 4@
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码