32 ms·
> when class Player hits() a class Monster, where exactly do we modify data? Monster's hp has to decrease by Player's attackPower, Player's xps increase by Mons
by geowwy 8y ago
> when class Player hits() a class Monster, where exactly do we modify data? Monster's hp has to decrease by Player's attackPower, Player's xps increase by Monster's level if Monster got killed. Does it happen in Player.hits(Monster m) or Monster.isHitBy(Player p). What if there's a class Weapon involved? Do we pass it as an argument to isHitBy or does Player has a currentWeapon() getter?
I don't see how this is a problem unless you think programming objects correspond with physical objects.
My first thought is make a separate Swing class representing the player swinging their weapon. There's probably an even better way to do it but this gets around the issues mentioned above.
class Player {
fun takeSwing {
swing = new Swing(
this.currentWeapon,
this.location.offset(this.direction)
)
if swing.killedMonster {
this.xp += swing.monster.level
}
}
}
class Swing {
fun new(weapon, location) {
this.weapon = weapon
this.monster = findMonster(location)
if this.monster != null { this.monster.takeHit(this) }
this.killedMonster = this.monster != null && this.monster.dead
}
fun damage {
return this.weapon.baseDamage
+ this.weapon.bonusDamage
}
}
class Monster {
fun takeHit(swing) {
this.hp -= swing.damage - this.defence
if this.hp <= 1 { this.die }
}
}
- coldtea 8y ago>I don't see how this is a problem unless you think programming objects correspond with physical objects. This is a problem because we don't just want "any old design that sorta kinda works" but a guiding principle to our design, and to find the optimal place for each action/data.
- segmondy 8y agoGood example, I think that's why people struggle with OOP, they do think that "programming objects correspond with physical objects". This is the same reason they struggle with storing states in databases because they try to map OOP to tables.