This site requires JavaScript, please enable it in your browser!
Greenfoot back
Dudimus
Dudimus wrote ...

2016/8/18

How to make a Game timer about 60 seconds which will show game over?

Dudimus Dudimus

2016/8/18

#
import greenfoot.*;
import java.awt.Color;
import java.awt.Font;

public class Welt extends World
{
    public static int actionType, actionDistance; // the world bounds action fields for the chasers
    public static Chased chased; // the player
    public int score; // the score
    HealthBar healthbar = new HealthBar();
    AmmoBar ammobar = new AmmoBar();
  private int timer = 1200;
    public Welt()
    {
        super(1000, 600, 1, false);
        Greenfoot.setSpeed(60);
        // create background texts
        GreenfootImage bg = getBackground();
     // create player and reset game
        chased = new Chased();
        setAction(0);
        if (timer>0)
{
    timer--;
    if(timer == 0) Greenfoot.stop();
}
    }
    
    public void act()
    {
     
        if (numberOfObjects() >= 20+score/10) return;
        if (Greenfoot.getRandomNumber(1000) > 30+score/10) return;
        int x = Greenfoot.getRandomNumber(getWidth());
        int y = Greenfoot.getRandomNumber(getHeight());
        int rand = Greenfoot.getRandomNumber(4);
        if (rand < 2) x = (getWidth()-3+actionDistance*2)*rand+1-actionDistance;
        else y = (getHeight()-3+actionDistance*2)*(rand-2)+1-actionDistance;
        // if (Math.abs(x-chased.getX())+Math.abs(y-chased.getY()) < 200) return;
        Chaser chaser = new Chaser();
        addObject(chaser, x, y);
        chaser.turnTowards(400, 300);
    }
    
    public AmmoBar getAmmoBar()
    {
        return ammobar;
    }
    
    public HealthBar getHealthBar()
    {
        return healthbar;
    }
    
    private void setAction(int action)
    {
        addObject (healthbar, 100, 20);
        addObject (ammobar, 100, 40);
        
        int[] distances = { 0, 0, -10, 0, -15 }; // bound ranges
        actionDistance = distances[actionType]; // the range for this action
    
        GreenfootImage bg = getBackground();
      
        score = 0;
        // ensure player is in world
        if (chased.getWorld() == null) addObject(chased, 400, 300);
    }

    public void getActorCounts()
    {
        java.util.List<Object> objects = getObjects(null);
        int n = 0;
        while (!objects.isEmpty())
        {
            String name = objects.get(n).getClass().getName();
            int count = 1;
            int index = 1;
            while (index < objects.size())
            {
                if (name.equals(objects.get(index).getClass().getName()))
                {
                    count++;
                    objects.remove(index);
                }
                else index++;
            }
            System.out.println(name+": "+count);
            objects.remove(0);
        }
    }
}
danpost danpost

2016/8/18

#
Look like all you need to do is adjust the initial timer value (make it more like 3300) and expand the 'if' block at line 25:
if (timer == 0)
{
    Greenfoot.stop();
    // show game over here
}
You can either draw an image onto the background image of the world or create and add an actor to display the "Game Over" message.
Dudimus Dudimus

2016/8/20

#
Thanks for replying. I tried it but it still doesn't work. But I'll just remove the timer. I have another question though, in your game I edited the images of the characters, added health and ammo bars, etc. Now, whenever Chased hits zombies his life lessens by one. But when I don't move him and the zombies go to him, when they are on top of his image, they glitch and then walk away leaving the screen. Why is that happening?
danpost danpost

2016/8/20

#
Dudimus wrote...
whenever Chased hits zombies his life lessens by one. But when I don't move him and the zombies go to him, when they are on top of his image, they glitch and then walk away leaving the screen. Why is that happening?
You will have to show the Chased class code.
Dudimus Dudimus

2016/8/20

#
import greenfoot.*;
import java.awt.Color;

/**
 * Class Chased (subclass of Actor): a user-controlled object with a mouse-controlled gun
 */
public class Chased extends Actor
{
    boolean touchingZ = false;
 
    boolean touchingFire = false;
    Gun gun = new Gun(); // the gun for this actor
    Chaser chaser = new Chaser();
 

    
    int ammo=10;
 
    
    int reloadTime=50;
    int reload=0;
    /**
     * creates image for actor
     */
    public Chased()
    {
        // the image for this actor
        GreenfootImage image = new GreenfootImage(50, 50);
        image.fillOval(0, 0, 50, 50);
        image.setColor(Color.green);
        image.fillOval(7, 7, 36, 36);
        setImage(image);
    }
    
    /**
     * adds the gun for this actor into the world
     *
     * @param world the world this actor was added into
     */
    public void addedToWorld(World world)
    {
        world.addObject(gun, getX(), getY()); // add the gun belonging to this actor into the world
    }
    

      /**
     * move user-controlled actor and its gun; also, check for game over
     */
    public void act()
    {
        // user-controlled movement
        int dx = 0, dy = 0;
        if (Greenfoot.isKeyDown("a")) dx--;
        if (Greenfoot.isKeyDown("d")) dx++;
        if (Greenfoot.isKeyDown("w")) dy--;
        if (Greenfoot.isKeyDown("s")) dy++;
        setLocation(getX()+3*dx, getY()+3*dy);
        // limit to world bounds
        if (getX() < 25) setLocation(25, getY());
        if (getY() < 25) setLocation(getX(), 25);
        if (getX() > getWorld().getWidth()-25) setLocation(getWorld().getWidth()-25, getY());
        if (getY() > getWorld().getHeight()-25) setLocation(getX(), getWorld().getHeight()-25);
        // position gun
        gun.setLocation(getX(), getY());
        // check game over
      
         Actor chaser = getOneIntersectingObject(Chaser.class);
       
         
        if (chaser != null)
                {
            World world = getWorld();
                    Welt welt = (Welt)world;
                    HealthBar healthbar = welt.getHealthBar();
                    if(touchingZ == false)
                    {
                        healthbar.loseHealth();
                        touchingZ = true;
                        if(healthbar.health <=0)
                        {
                         world.removeObjects(world.getObjects(null));
                          Greenfoot.setWorld(new Stats(((Welt)world).score));
                        }
                    }
        }else{
                    touchingZ = false;
                }
               
    }
   
    /**
     * Class: Gun (subclass of Actor -- inner class of Chased): the gun for this actor
     */
    private class Gun extends Actor
    {
        /**
         * creates image for actor
         */
        public Gun()
        {
            // the image for this actor
            GreenfootImage image = new GreenfootImage("Picture1.png");
           
            setImage(image);
        }
         
   
    

    public boolean Munition(){
        if(ammo>0){
            return true;
        }
        else{
            return false;
        }
    }

    private boolean mouseclick;
    /**
         * responds to mouse movement and mouse button clicks
         */
        public void act()
        {
            // turn towards mouse when mouse moves
            if (Greenfoot.mouseMoved(null) || Greenfoot.mouseDragged(null))
            {
                MouseInfo mouse = Greenfoot.getMouseInfo();
                if (mouse != null) turnTowards(mouse.getX(), mouse.getY());
            }
            // detect mouse clicks to fire shot   
           
            World world = getWorld();
                    Welt welt = (Welt)world;
                    AmmoBar ammobar = welt.getAmmoBar();
            if(!mouseclick && (Greenfoot.mouseClicked(null)))
            {
                if(Munition()==true)
                {
                    mouseclick=true;
                    getWorld().addObject(new Shot(), getX(), getY());
                    ammo--;
                    ammobar.loseAmmo();
                }
            }
            if(mouseclick&& !Greenfoot.isKeyDown("space"))
            {
                mouseclick=false;
            }
            
         
            
        }
      
     

        

        /**
         * Class Shot (subclass of QActor -- inner class of Chased.Gun): the shots from this gun
         */
        private class Shot extends QActor
        {
            /**
             * sets bounds fields and creates the image for this actor
             */
            public Shot()
            {
                setBoundedAction(QActor.REMOVE, 5); // set bounds fields
                // create image for this actor
                GreenfootImage image = new GreenfootImage("FIRE.png");
                
                setImage(image);

            }
            
            /**
             * initializes rotation and position of actor
             *
             * @param world the world this actor was added into
             */
            public void addedToWorld(World world)
            {
                setRotation(Gun.this.getRotation()); // set rotation (to that of gun)
                move(5000); // set position (at end of gun)
            }
            
            /**
             * moves actor and checks for removal of actor
             */
            public void act()
            {
                setVX(0);
                setVY(0);
                addForce(0, getRotation()*QVAL);
                move(); // moving (equivalent to 'move(5)' for a non-QActor)
                if (hits(Chaser.class) || atWorldEdge()) getWorld().removeObject(this); // removing
            }
            
                  /**
             * internal method to detect object collision; returns true if collision detected, else false
             *
             * @param cls the class of object to check for collision with
             * @return a flag indicating whether an object of given class was detected or not
             */
            private boolean hits(Class cls)
            {
                // get intersecting object and return result
                Actor clsActor = getOneIntersectingObject(cls);
                if (clsActor != null)
                {
                    // remove intersector and bump score
                    getWorld().removeObject(clsActor);
                    
                    return true; 
                }
                return false;
            }
            /**
             * internal method that returns a flag indicating world edge encroachment
             *
             * @return a flag indicating whether the actor has encroached on a world edge or not
             */
            private boolean atWorldEdge()
            {
                // return state of encroachment on world edge
                return getX() <= 0 || getY() <= 0 ||
                    getX() >= getWorld().getWidth()-1 ||
                    getY() >= getWorld().getHeight()-1;
            }
        }
    }
}
danpost danpost

2016/8/20

#
I'm sorry, I meant the class of the zombies (the behavior of the zombies is what you are having problems with).
Dudimus Dudimus

2016/8/22

#
import greenfoot.*;

public class Chaser extends QActor
{
    int dr = 0; // the current turn rate
    
    public Chaser()
    {
        setBoundedAction(Welt.actionType, Welt.actionDistance); // set bound fields
        // create image for this actor
        GreenfootImage image = new GreenfootImage("Z1.png");
        setImage(image);
    }

    /**
     * turn and move actor
     */
    public void act()
    {
        int dx = 0, dy = 0; // the differences in locational coordinates
        int rate = 0; // the rate of turn and speed
        Actor chased = Welt.chased;
        if (chased != null && chased.getWorld() != null)
        { // set variable values
            dx = getX()-chased.getX();
            dy = getY()-chased.getY();
            rate = 400-(int)Math.abs(dx)-(int)Math.abs(dy);
        }
        if (rate > 100)
        { // chase
            // the next code line does what is described in the following commented lines
               // determine shortest turn direction to face chased
            // int angleDiff = getRotation()-(int)(Math.atan2(dy, dx)*180/Math.PI); // range: -359 to 359
            // int anglet = (angleDiff+360+180)%360-180; // range: -180 to 179 (sign is turn direction)
               // turn and move
            // turn(16*rate*(int)Math.signum(anglet)); 
            turn(16*rate*(int)Math.signum((getRotation()-(int)(Math.atan2(dy, dx)*180/Math.PI)+540)%360-180));
            move(rate/8, getQR()); // between 'move(0.1)' to 'move(0.4)' for a non-QActor, which is not possible
        }
        else
        { // wander
            // vary turn rate
            dr += 2-Greenfoot.getRandomNumber(5)-(int)Math.signum(dr);
            // limit turn rate to between 40 q-rotation units left and right
            if (dr < -40) dr = -40;
            if (dr > 40) dr = 40;
            // turn and move
            turn(dr);
            move(10);
        }
    }
}
danpost danpost

2016/8/22

#
My demo was designed to stop when the Chased object was caught by a Chaser object; so, behavior beyond the initial contact between the two was not observed or relevant to that demo. However, after now observing such behavior, which appears to me as the Chaser objects hovering over the Chased object until they are at the same exact int coordinate location in the world, at which point the Chaser object will not be able to do a turnTowards operation (it is impossible to turn towards the location where you are already at). So, it just moves. If its rotation is zero, which it tends toward while hovering, then it will move left or right away from the chased. It seems that at this point the chaser is blind to the location of the chased until the chased moves vertically, enough to create an angle where the chaser will know which direction to turn around in (I guess it is indecisive, otherwise).
Dudimus Dudimus

2016/8/22

#
Where can I change the code that if chaser hits Chased, the world will be terminated? I kept searching for it in welt, chased, and chaser but I just can't seem to find it.
Dudimus Dudimus

2016/8/22

#
Oh, wait, what can I do to fix the problem?
danpost danpost

2016/8/22

#
Dudimus wrote...
Oh, wait, what can I do to fix the problem?
I guess you first need to determine what behavior you do want from the chasers when touching the chased and then write some code to implement that behavior. This may involve making the touching chasers ignore the chased for some time (number of act methods). Or, it may involve making the chaser immediately turn around so that the chased cannot just stay with the chaser to avoid more damage to its health. It may take some trial and error to get some desired behavior that works with consistency.
Dudimus Dudimus

2016/8/23

#
I guess I'll find other scenarios with zombies and see what works. Another question, :) In the game I changed the bullets to a fire image. It works but the problem is that it follows the rotation of the gun as stated in the code. Is there a way I can make it come out at the end of the gun but the image will always stay upright no matter where or what direction I shoot it?
danpost danpost

2016/8/23

#
Dudimus wrote...
In the game I changed the bullets to a fire image. It works but the problem is that it follows the rotation of the gun as stated in the code. Is there a way I can make it come out at the end of the gun but the image will always stay upright no matter where or what direction I shoot it?
Yes. You will need a field to hold the qRotation value in the subclass of QActor (the class of the fire bullet). Then at the beginning of its act method set the qRotation to that of the field and at the end set the field to the new qRotation and set the actual rotation back to zero. So, something like this:
// add instance field
private int rotation;

// first line in act method
setQRotation(rotation);

// last lines in act method
rotation = getQR();
setRotation(0);
Dudimus Dudimus

2016/8/24

#
It works! Thanks so much. But, is there any code I could type that would make the zombies' image not go on top of Chased's picture at all (hopefully solving the glitch problem)?
danpost danpost

2016/8/25

#
Dudimus wrote...
is there any code I could type that would make the zombies' image not go on top of Chased's picture at all (hopefully solving the glitch problem)?
There is the 'setLocation' method. When touch occurs, you can use it to separate the two actors so they are not touching. But, you will need to do more to ensure that the zombie does not immediately move back into the chased and cause more lose of health before some time (your preference as to how long) has elapsed.
You need to login to post a reply.