vendredi 4 novembre 2016

Use class functions after identify the class itself

I have a problem with my current code. I'd like to write a simple monopoly-like game to excercise. There's not much to finish it, but I've stuck at one thing.

I've got a Field class which is extended by a Luck, Property and a Service class. Luck and Service almost are the same.

package field;

public class Luck extends Field {
    private final int price;

    public Luck(int price) {
        this.price = price;
    }

    public int getPrice() {
        return price;
    }
}

I have the following problem. I create and store them in a List (as the map goes, 0. element in list is the 1. field on the map, 1. element is the 2. field, etc.)

List<Field> fields = new ArrayList<>();

Now if one player rolls then move, I should check if he stepped on a Luck or Service field so I could get him the money.

Field f = fields.get(player.getPosition());

            if (f.getClass().equals(Luck.class)) { player.income(fields.get(player.getPosition()).getPrice()); }
            else if (f.getClass().equals(Service.class)) { player.expense(fields.get(player.getPosition()).getPrice()); }
            else {}

The player looks like this:

public abstract class Player {
    String name;
    private int wealth;
    private int position;

    public Player(String name) {
        this.name = name;
        wealth = 10000;
        position = 0;
    }

    public void expense(int price) {
        wealth -= price;
    }

    public void income(int price) {
        wealth += price;
    }

How could I use the Luck class' functions after

if (f.getClass().equals(Luck.class)) { player.income(fields.get(player.getPosition()).getPrice()); }

? The error is it can't find the Price symbol which I understand. It's not declared in Fields.java (since not all 3 field has price tag), but I should be able to use it after I've already checked if the class equals Luck, shouldn't I?

Aucun commentaire:

Enregistrer un commentaire