how can i add a random number of actors while the game is running?


1 | for ( int i = 0 ; i < Greenfoot.getRandomNumber(MAX_ACTORS + 1 - MIN_ACTORS) + MIN_ACTORS; i++) |
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 | import greenfoot.*; public class Space extends World { static final int MAX_BIRDS = 10 ; // adjust this value static final int MIN_BIRDS = 5 ; // adjust this value static final int INTERVAL= 40 ; Long beginTime = System.currentTimeMillis(); public Space() { super ( 600 , 400 , 1 ); addObject( new Gun(), 300 , 200 ); addRandomBirds(); } public void act() { if ((System.currentTimeMillis() - beginTime) / 1000 >= INTERVAL) { addRandomBirds(); beginTime = System.currentTimeMillis(); } } private void addRandomBirds() { for ( int i = 0 ; i < Greenfoot.getRandomNumber(MAX_BIRDS + 1 - MIN_BIRDS) + MIN_BIRDS; i++) addObject( new Bird(), 0 , Greenfoot.getRandomNumber( 400 )); } } |
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 68 69 70 71 72 73 74 75 76 77 78 79 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; /** * Write a description of class Birds here. * * @author (your name) * @version (a version number or a date) */ public class Bird extends Actor { private int count = 0 ; /** * Act - do whatever the Birds wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(); checkCount(); checkMouse(); checkOut(); if (getOneIntersectingObject(Bird. class ) != null ) { Actor bird = getOneIntersectingObject(Bird. class ) ; getWorld().removeObject(bird); getWorld().removeObject( this ); return ; } } public void move() { setLocation( 600 ,Greenfoot.getRandomNumber( 400 )); } public boolean atWorldEdge() { if (getX() == 600 && (getY()==Greenfoot.getRandomNumber( 400 ))) return true ; else return false ; } public boolean isMoving(){ boolean move = true ; if (move) move(); return move; } public void checkMouse(){ if (Greenfoot.mouseClicked(Bird. class )){ getWorld().removeObject( this ); Greenfoot.playSound( "explosion-02.wav" ); } } private void checkOut() { if (atWorldEdge()){ getWorld().removeObject( this ); } count++; Greenfoot.playSound( "fail-buzzer-04.wav" ); } public void drawString(){ getImage().setColor(Color.red); getImage().drawString( "You lost!!!" , 300 , 200 ); } public void checkCount() { if (count> 3 ){ Greenfoot.stop(); drawString(); Greenfoot.playSound( "fail-trombone-03.wav" ); } } } |
1 2 3 4 | move(); checkMouse(); if (getWorld() != null ) checkOut(); if (getWorld() != null && getOneIntersectingObject(Bird. class ) != null ) |