index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const { Document } = require('camo')
  2. const battleAIs = require('../battle/ai')
  3. const Move = require('../battle/move')
  4. const tinygradient = require('tinygradient')
  5. const tinycolor = require('tinycolor2')
  6. const healthGradient = tinygradient(['#BA0020', '#ffbf00', '#77dd77'])
  7. const colorDead = '#36454f'
  8. // A Character refers to both a player and an enemy. The difference is in
  9. // their `ai` that controls their actions (for players, this is DiscordAI).
  10. class Character extends Document {
  11. constructor() {
  12. super()
  13. this.schema({
  14. discordID: {type: String, required: false},
  15. battleAI: {type: String, required: true, choices: Object.keys(battleAIs)},
  16. health: {type: Number, default: 5, min: 0},
  17. maxHealth: {type: Number, default: 5, min: 1},
  18. moves: [Move],
  19. })
  20. }
  21. // Rather than a string (this.battleAI), returns the class itself.
  22. get BattleAI() {
  23. return battleAIs[this.battleAI]
  24. }
  25. async modHealth(by, guild) {
  26. this.health += by
  27. if (this.health > this.maxHealth) this.health = this.maxHealth
  28. if (this.health < 0) this.health = 0
  29. if (guild) await this.healthUpdate(guild)
  30. return this.healthState
  31. }
  32. async healthUpdate(guild) {
  33. await this.save()
  34. if (!this.discordID) return
  35. const member = guild.members.get(this.discordID)
  36. // Remove existing health role, if any
  37. const roleExisting = member.roles.find(role => role.name.endsWith(' health'))
  38. if (roleExisting) await roleExisting.delete()
  39. // Reuse/create a health role and grant it
  40. const roleName = `${this.health}/${this.maxHealth} health`
  41. const role = member.roles.find(role => role.name === roleName)
  42. || await guild.createRole({
  43. name: roleName,
  44. color: this.health === 0
  45. ? colorDead
  46. : tinycolor(healthGradient.rgbAt(this.health / this.maxHealth)).toHexString()
  47. })
  48. await member.addRole(role)
  49. }
  50. get healthState() {
  51. if (this.health === this.maxHealth) return 'healthy'
  52. else if (this.health === 1) return 'peril'
  53. else if (this.health === 0) return 'dead'
  54. else return 'injured'
  55. }
  56. getName(guild) {
  57. // FIXME: names for characters without accociated discord users (eg. ai enemies)
  58. return guild.members.get(this.discordID).displayName
  59. }
  60. }
  61. module.exports = Character