我将尝试给您一个有关如何设计军械库和军械库的示例。
我们的目标是使实体脱钩,因此武器应该是接口。
interface Weapon {
public int getDamage();
}
假设每个玩家只能拥有一个武器,我们可以使用Strategy pattern
以便轻松更换武器。
class Knife implements Weapon {
private int damage = 10;
@Override
public int getDamage() {
return this.damage;
}
}
class Sword implements Weapon {
private int damage = 40;
@Override
public int getDamage() {
return this.damage;
}
}
另一个有用的模式是“ 空对象模式”,以防玩家没有武装。
class Weaponless implements Weapon {
private int damage = 0;
@Override
public int getDamage() {
return this.damage;
}
}
至于军械库,我们可以穿多种防御装备。
// Defence classes,interfaces
interface Armor {
public int defend();
}
class Defenseless implements Armor {
@Override
public int defend() {
return 0;
}
}
abstract class Armory implements Armor {
private Armor armory;
protected int defence;
public Armory() {
this(new Defenseless());
}
public Armory(Armor force) {
this.armory = force;
}
@Override
public int defend() {
return this.armory.defend() + this.defence;
}
}
// Defence implementations
class Helmet extends Armory {
{
this.defence = 30;
}
}
class Gloves extends Armory {
{
this.defence = 10;
}
}
class Boots extends Armory {
{
this.defence = 10;
}
}
为了解耦,我为防御者创建了一个接口。
interface Defender {
int getDefended();
}
和Player
班级。
class Player implements Defender {
private String title;
private int health = 100;
private Weapon weapon = new Weaponless();
private List<Armor> armory = new ArrayList<Armor>(){{ new Defenseless(); }};
public Player(String name) {
this.title = name;
}
public Player() {
this("John Doe");
}
public String getName() {
return this.title;
}
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
public void attack(Player enemy) {
System.out.println(this.getName() + " attacked " + enemy.getName());
int attack = enemy.getDefended() + enemy.getHealth()- this.weapon.getDamage();
int health = Math.min(enemy.getHealth(),attack);
System.out.println("After attack " + enemy.getName() + " health is " + health);
enemy.setHealth(health);
}
public int getHealth() {
return health;
}
private void setHealth(int health) {
/* Check for die */
this.health = health;
}
public void addArmory(Armor armor) {
this.armory.add(armor);
}
@Override
public int getDefended() {
int defence = this.armory.stream().mapToInt(armor -> armor.defend()).sum();
System.out.println(this.getName() + " defended , armory points are " + defence);
return defence;
}
}
让我们添加一些游戏玩法。
public class Game {
public static void main(String[] args) {
Player yannis = new Player("yannis");
Player sven = new Player("sven");
yannis.setWeapon(new Knife());
sven.setWeapon(new Sword());
sven.addArmory(new Helmet());
sven.addArmory(new Boots());
yannis.attack(sven);
sven.attack(yannis);
}
}
瞧!