party.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. const { Document } = require('camo')
  2. const Character = require('./character')
  3. const tinycolor = require('tinycolor2')
  4. // Just an organised party (read: team, group) of Characters.
  5. class Party extends Document {
  6. constructor() {
  7. super()
  8. this.schema({
  9. members: [Character],
  10. //name: {type: String, default: 'Unnamed Party'},
  11. colorHue: {type: Number, min: 0, max: 1},
  12. //discordRoleID: {type: String, required: false},
  13. })
  14. }
  15. get colorHex() {
  16. return tinycolor.fromRatio({h: this.colorHue, s: 0.6, v: 1.0}).toHexString()
  17. }
  18. async addCharacter(character) {
  19. if (character.partyID) {
  20. // Remove the character from their old party
  21. const origParty = await character.getParty()
  22. await origParty.rmCharacter(character)
  23. }
  24. character.partyID = this._id
  25. this.members.push(character)
  26. await Promise.all([this.save(), character.save()])
  27. }
  28. async rmCharacter(character) {
  29. character.partyID = null
  30. await character.save()
  31. this.members = this.members.filter(mem => mem._id !== character._id)
  32. if (this.members.length === 0) {
  33. // We don't need to exist anymore.
  34. // #relatable
  35. await this.delete()
  36. } else {
  37. await this.save()
  38. }
  39. }
  40. /*
  41. async getRole(guild) {
  42. // Create the role, if it doesn't exist already.
  43. if (!this.discordRoleID) {
  44. const role = await guild.createRole()
  45. await this.updateRole(role)
  46. this.discordRoleID = role.id
  47. }
  48. return guild.roles.get(this.discordRoleID)
  49. }
  50. async updateRole(role) {
  51. // Update party role details.
  52. await role.edit({
  53. name: this.name,
  54. color: this.colorHex,
  55. })
  56. }
  57. async assignRoles(guild) {
  58. const partyRole = await this.getRole(guild)
  59. await this.updateRole(partyRole)
  60. for (const character of this.members) {
  61. if (!character.discordID) {
  62. continue
  63. }
  64. const member = guild.members.get(character.discordID)
  65. member.addRole(partyRole)
  66. }
  67. */
  68. static async of(characters) {
  69. const party = this.create({
  70. characters: [],
  71. colorHue: Math.random(),
  72. })
  73. for (const character of characters) {
  74. await party.addCharacter(character)
  75. }
  76. return party
  77. }
  78. }
  79. module.exports = Party