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

2017/5/18

text doesn't update (counter) – please help

ProgrammingPanda ProgrammingPanda

2017/5/18

#
Hi, I have a code where two players eat victims and the one that eats the most victims wins. I don't it to show the player the specific counter of how many victims they've eaten, I just want it show who's in the lead (or if it's a draw). I've made a Counter class, a subclass of Actor and the text shows but it's stuck on "It's tied!" because that's what it shows at the start of course since its 0:0 at the beginning.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Counter extends Actor
{
    public int victimsEatenP1;
    public int victimsEatenP2;
    
    public void act() //zeigt an, welcher Spieler gerade in Führung ist (= mehr victims gefressen hat)
    {
        if (victimsEatenP1 > victimsEatenP2) // vergleicht die gegessenen victims und liefert je nach dem den richtigen Text
        setImage(new GreenfootImage("Player 1 is in the lead", 40, Color.WHITE, new Color(0, 0, 0, 0)));
        
        if (victimsEatenP2 > victimsEatenP2)
        setImage(new GreenfootImage("Player 2 is in the lead", 40, Color.WHITE, new Color(0, 0, 0, 0)));
    
        if (victimsEatenP1 == victimsEatenP2)
        setImage(new GreenfootImage("It's tied!", 40, Color.WHITE, new Color(0, 0, 0, 0)));
    }    
}
Thanks in advance :)
danpost danpost

2017/5/18

#
You really should not create a new GreenfootImage object every act cycle if not necessary. Add methods to the class that the player classes can call to bump the score (instead of changing the field values directly) and update the image only when the score changes:
public void adjustP1(int amount)
{
    victimsEatenP1 += amount;
    update();
}

public void adjustP2(int amount)
{
    victimsEatenP2 += amount;
    update();
}

private void update()
{
    int comp = (int)Math.signum(victimsEatenP1-victimsEatenP2);
    String[] texts = { "Player 2 is in the lead", "It' tied!", "Player 1 is in the lead" };
    setImage(new GreenfootImage(texts[comp+1], 40, Color.WHITE, new Color(0, 0, 0, 0)));
}
You need to login to post a reply.