I am trying to get a door to open after the player has acquired a key. I originally used the following code provided by danpost:
if ( getWorld().getObjects(Key.class).isEmpty() && Greenfoot.mouseClicked(this) )
This did the trick; however, I have noticed that the code only seems to work if the key.class and the location.class are populated from the World.class at the start of the game. Is there any way to adjust the code so the door will unlock if the key is added from anywhere in the game? For example, there is a door on Location_03, but the player has to go to Location_04 or 05 to get the key and then go back to Location_03 to unlock the door. How would I approach creating code for that scenario? Any ideas?
Thank you,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | public class Key extends Actor { /** * Act - do whatever the Key wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { { MouseInfo mouse = Greenfoot.getMouseInfo(); { if (Greenfoot.mouseClicked( this )) { getWorld().removeObject( this ); } } } } } ----------------------- import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Location_02 extends Actor { public Location_02() { GreenfootImage myPic = new GreenfootImage( 1024 , 640 ); myPic.fill(); myPic.drawImage( new GreenfootImage( "Location_02.jpg" ), 0 , 0 ); setImage(myPic); } public void act() { MouseInfo mouse = Greenfoot.getMouseInfo(); { if ( !getWorld().getObjects(Key. class ).isEmpty()&& Greenfoot.mouseClicked( this ) && mouse.getX() > 644 && mouse.getX() < 900 && mouse.getY() > 75 && mouse.getY() < 524 ) { getWorld().addObject( new Dialog_01(), 509 , 577 ); getWorld().addObject( new Direction_01(), 90 , 267 ); // getWorld().removeObject(this); } else if ( getWorld().getObjects(Key. class ).isEmpty() && Greenfoot.mouseClicked( this ) && mouse.getX() > 644 && mouse.getX() < 900 && mouse.getY() > 75 && mouse.getY() < 524 ) { getWorld().addObject( new Location_03(), 512 , 320 ); // getWorld().addObject(new Box(), 244,260); getWorld().removeObject( this ); } } } } ------------------- |