Monday, February 10, 2014

Starting a New Platformer: Mario! (Part 1)

We're going to build a new scrolling platformer, but this time we're taking it old-school and recreating a Mario game.



  1. Create a New Scenario
  2. Go to Scenario > Scenario Information
    1. Edit the contents of the Readme
  3. Save the Mario images to your Images folder.
  4. Copy the Counter Class (below)
  5. Create a series of new classes (see right)
  6. Edit the Levels class to be 1050x500
import greenfoot.*;  
import java.awt.Color;
import java.awt.Font;   

/**
 * Generic counter class, it is used to count statistics such as remaining lives, number of coins and amount of points.
 * @author
 * @version 1.1
 */
public class Counter extends Actor  
{  
    private static final Color TRANSPARENT = new Color(0, 0, 0, 0);  
    public int value;  
    private Color textColor = Color.WHITE;  
    protected int target;
    private String prefix;

    public Counter()  
    {  
        value = 0;
        target = 0;
        this.prefix = prefix;
        updateImage();
        GreenfootImage image = getImage();
        Font font = image.getFont();
    }  

    public void act() 
    {
        if (value < target) {
            value++;
            updateImage();
        }
        else if (value > target) {
            value--;
            updateImage();
        }
    }

    private void updateImage()  
    {  
        int fontSize =24;
        setImage(new GreenfootImage(prefix+" "+value, fontSize, textColor, TRANSPARENT)); 
    }  

    public void setTextColor(Color color)  
    {  
        textColor = color;  
        updateImage();  
    }  

    public void setPrefix(String text)  
    {  
        prefix = text;  
        updateImage();  
    }  

    public Counter(String text)  
    {  
        prefix = text;  
        updateImage();  
    } 

    public void add(int score)  
    {  
        target += score;
        updateImage();  
    } 

    public void subtract(int score)  
    {  
        target -= score;
        updateImage();  
    } 

    public void setValue(int newValue)  
    {  
        target = newValue;
        value = newValue;
        updateImage();  
    }  

    public int getValue()  
    {  
        return target;  
    }  
} 
Open your Mario class and add the following method before the "Act" method:

private final GreenfootImage idle = new GreenfootImage("mario-idle.gif");
public Mario()
{
    setImage(idle);
    idle.scale(38,50);
}
Next, close the Mario class and Compile your code. Now, add a new Mario to your empty world.

No comments:

Post a Comment