mardi 21 février 2017

In a game programming project, how do I handle multiple items with multiple instances?

Assuming that I have a 2 player game that has multiple weapons in it. At the start of the game, the players can choose their own weapons and equip it to their characters. So if Right now, I have the following code to implement the said scenario:

public class Weapon {
    private String name;
    private int attackPoints;
    private int effectivity = 100;

    public Weapon(String name, int attackPoints) {
        this.name = name;
        this.attackPoints = attackPoints;
    }
    // ...
}

public class Character {
    private String name;
    private Weapon weapon;

    public Character(String name, Weapon weapon) {
        this.name = name;
        this.weapon = weapon;
    }
    // ...
}

public class Game {
    Scanner scanner = new Scanner(System.in);
    public void createCharacter() {
        String namePlayer = "Knight";
        String nameOpponent = "Thief";

        //Weapon Menu
        System.out.println("Select weapon");
        System.out.println("1. Dagger - Attack: 10");
        System.out.println("2. Sword - Attack 20");

        Character player;
        Character opponent;
        int choice = scanner.nextInt();

        //Weapon assignment
        switch (choice) {
        case 1:
            player = new Character(name, new Weapon("Dagger", 10));
            break;
        case 2:
            player = new Character(name, new Weapon("Sword", 20));
            break;
        }
    }
}

Rephrased the question

My concern is, what if I have to add an additional weapon, say "Ax with 15 damage" for example, then I'd have to modify the weapon menu, and at the same time add an additional case in my switch statement. Is it possible that I'd only have to modify some kind of a list and it'll take care of the list of weapons available for the player to choose and at the same time make the instances of the weapons different for the player and the opponent character?

Old question

My concern is, every time I have a new weapon, I have to modify the weapons menu and at the same time modify the weapon assignment part. Is there a better way for implement it?

Aucun commentaire:

Enregistrer un commentaire