save-throw-field.component.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { Component, Input } from '@angular/core';
  2. import { DataService } from 'src/services/data/data.service';
  3. import { Observable } from 'rxjs';
  4. import { Attribute } from 'src/interfaces/attribute';
  5. import { DetailsService } from 'src/services/details/details.service';
  6. import { SaveThrowDetailsComponent } from '../save-throw-details/save-throw-details.component';
  7. @Component({
  8. selector: 'save-throw-field',
  9. templateUrl: './save-throw-field.component.html',
  10. styleUrls: ['./save-throw-field.component.scss'],
  11. })
  12. export class SaveThrowFieldComponent {
  13. constructor(
  14. public dataAccessor: DataService,
  15. public detailsAccessor: DetailsService
  16. ) {}
  17. @Input() attributeName: string = '';
  18. public attribute: Attribute = { name: '', value: 0, proficiency: false };
  19. private proficiencyBonus: number = 0;
  20. private attributeModifier: number = 0;
  21. public saveModifier: string = '0';
  22. public nameTranslator: any = {
  23. strength: 'Stärke',
  24. dexterity: 'Geschicklichkeit',
  25. constitution: 'Konstitution',
  26. intelligence: 'Intelligenz',
  27. wisdom: 'Weisheit',
  28. charisma: 'Charisma',
  29. };
  30. public ngOnInit(): void {
  31. this.initAttributeSubscription();
  32. this.initProficiencySubscription();
  33. }
  34. private initAttributeSubscription(): void {
  35. const observable: Observable<Attribute> = eval(
  36. `this.dataAccessor.${this.attributeName}$`
  37. );
  38. observable.subscribe((newValue: Attribute) => {
  39. this.attribute = newValue;
  40. this.attributeModifier = this.calculateAttributeModifier();
  41. this.saveModifier = this.calculateSaveModifier();
  42. });
  43. }
  44. private initProficiencySubscription(): void {
  45. this.dataAccessor.proficiency$.subscribe((newValue: any) => {
  46. this.proficiencyBonus = newValue;
  47. this.attributeModifier = this.calculateAttributeModifier();
  48. this.saveModifier = this.calculateSaveModifier();
  49. });
  50. }
  51. private calculateAttributeModifier(): number {
  52. return Math.floor((this.attribute.value - 10) / 2);
  53. }
  54. public calculateSaveModifier(): string {
  55. let mod = this.attributeModifier;
  56. if (this.attribute.proficiency) {
  57. mod += this.proficiencyBonus;
  58. }
  59. if (mod > 0) {
  60. return '+' + mod;
  61. } else {
  62. return mod.toString();
  63. }
  64. }
  65. public openDetails(): void {
  66. this.detailsAccessor.openPanel(SaveThrowDetailsComponent, {
  67. attributeName: this.nameTranslator[this.attributeName],
  68. saveModifier: this.saveModifier,
  69. });
  70. }
  71. public updateAttribute(): void {
  72. setTimeout(() => {
  73. this.dataAccessor.updateAttribute(this.attribute);
  74. });
  75. }
  76. }