top of page

// fields
private Actor unitsDisplay;
private int units = 5;
private int maxUnits = units;

​

// in constructor
unitsDisplay = new SimpleActor();
updateUnitsDisplay();
addObject(unitsDisplay, 80, 20);

​

// changing number of units
public void adjustUnits(int amount)
{
    units += amount;
    if (units < 0) units = 0;
    if (units > maxUnits) units = maxUnits;
    updateUnitsDisplay();
}

​

// updating units display image
private void updateUnitsDisplay()
{
   
// create image of a unit
    GreenfootImage unitImage = new GreenfootImage("hertz.png");
    unitImage.scale(40, 40); // optional
   
// dimensions of unit image
    int wide = unitImage.getWidth();
    int high = unitImage.getHeight();
   
// create actor image
    GreenfootImage image = new GreenfootImage(wide*maxUnits, high);
    for (int i=0; i<units; i++) image.drawImage(unitImage, i*wide, 0);
    unitsDisplay.setImage(image);
}

SIMPLE COUNTING SET CODING

bottom of page