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

2023/6/13

My hp isn't decreasing in subsequent order ;-;

Bee Bee

2023/6/13

#
public class hp extends Actor
{
    /**
     * Act - do whatever the hp wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public int hp = 100;
    
    public hp()
    {
        update();
    }
    public void act()
    {
        
        while(Greenfoot.isKeyDown("enter")){
            hp = hp - 10;
            update();
        }
    }   
    
    public int getHp(){
        return hp;
    }
    
    public void update()
    {
        setImage(new GreenfootImage("Health: "+hp, 18, Color.BLACK, Color.GREEN));
    }
}
danpost danpost

2023/6/13

#
Bee wrote...
My hp isn't decreasing in subsequent order << Code Omitted >>
The isKeyDown method returns true every act cycle the key is held down. Since one keystroke, even if somewhat quick, will take at minimum 2 or 3 act cycles. So, yeah -- your hp will not go down sequentially. Oh, and the use of while could be problematic for this case. I do not like using the getKey method for things that are not external actions without the game itself, I will go with a boolean in conjunction with the isKeyDown method:
public class hp extends Actor
{
    private int hp = 100;
    private boolean enterDown = false;
    
    public hp() {
        update();
    }
    
    public void act() {
        if (enterDown != Greenfoot.isKeyDown("enter")) {
            enterDown = ! enterDown;
            if (enterDown) {
                hp = hp - 10;
                update();
            }
        }
    }   
     
    public int getHp(){
        return hp;
    }
     
    private void update() {
        setImage(new GreenfootImage("Health: "+hp, 18, Color.BLACK, Color.GREEN));
    }
}
Bee Bee

2023/6/13

#
Thank you so much! It works now! But if you don't mind, I'm a little lost as to what happened. I'm still a bit new to Greenfoot and coding in general.
danpost danpost

2023/6/13

#
Bee wrote...
Thank you so much! It works now! But if you don't mind, I'm a little lost as to what happened. I'm still a bit new to Greenfoot and coding in general.
The enterDown boolean tracks the state of the "enter" key (holds the last known state of the key). Line 11 checks to see if that state has changed. Line 12 saves the new state. Line 13, which executes at a time when the key is changing states, asks if the change is from an up state to a down state, allowing the hp to only be reduced when the key is initially pressed and not just while the key is being held down.
Bee Bee

2023/6/19

#
Thank you so much!
You need to login to post a reply.