Question
the positions of the starfish are randomly generated, if they overlap the shark, they need to be moved so that the player will still be
the positions of the starfish are randomly generated, if they overlap the shark, they need to be moved so that the player will still be able to collect the starfish and win the game. To do this, after each starfish is added to the starfish group, check if that starfish overlaps the shark, and if so, add 100 to the x-coordinate of that starfishs position
java program:
public class StarfishCollector extends Game { Sprite water; Group starfishGroup; Sprite turtle; Sprite winMessage; Sprite shark; Sprite loseMessage;
public void initialize() { setTitle("Starfish Collector"); setWindowSize(800, 600);
water = new Sprite(); water.setTexture( new Texture("images/water.png") ); group.add( water ); shark = new Sprite(); shark.setPosition(250,250); shark.setTexture( new Texture("images/shark.png")); group.add(shark);
starfishGroup = new Group(); Texture starfishTexture = new Texture("images/starfish.png"); int starfishCount = 20; for (int i = 0; i < starfishCount; i++) { Sprite starfish = new Sprite(); double x = Math.random() * 600 + 100; double y = Math.random() * 400 + 100; starfish.setPosition(x, y); starfish.setTexture(starfishTexture); starfishGroup.add( starfish ); } group.add(starfishGroup);
turtle = new Sprite(); turtle.setPosition(50, 50); turtle.setTexture( new Texture("images/turtle.png") ); group.add(turtle);
winMessage = new Sprite(); winMessage.setPosition(250, 200); winMessage.setTexture( new Texture("images/youWin.png") ); winMessage.visible = false; group.add(winMessage); loseMessage = new Sprite(); loseMessage.setPosition(250, 200); loseMessage.setTexture( new Texture("images/youLose.png")); loseMessage.visible = false; group.add(loseMessage); }
public void update() { if (winMessage.visible) return; if (loseMessage.visible) return;
if (input.isKeyPressed("RIGHT")) turtle.position.addValues(2, 0); if (input.isKeyPressed("LEFT")) turtle.position.addValues(-2, 0); if (input.isKeyPressed("UP")) turtle.position.addValues(0, -2); if (input.isKeyPressed("DOWN")) turtle.position.addValues(0, 2);
for ( Entity entity : starfishGroup.getList() ) { Sprite starfish = (Sprite)entity; if ( turtle.overlaps(starfish) ) starfishGroup.remove(starfish); }
if (starfishGroup.size() == 0) winMessage.visible = true; if ( turtle.overlaps(shark) ) loseMessage.visible = true; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started