task-tsgame.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. // 玩家
  2. class Player {
  3. name: string;
  4. hp: number;
  5. power: number;
  6. defense: number;
  7. chargeCount: number;
  8. reboundUsed: boolean;
  9. constructor(name: string) {
  10. this.name = name;
  11. this.hp = 5;
  12. this.power = 1;
  13. this.defense = 0;
  14. this.chargeCount = 0;
  15. this.reboundUsed = false;
  16. }
  17. attack(target: Player) {
  18. target.receiveDamage(this.power);
  19. console.log(`${this.name}发动了攻击!`);
  20. }
  21. charge() {
  22. this.chargeCount++;
  23. console.log(`${this.name}开始蓄力!`);
  24. }
  25. defenseMove() {
  26. this.defense++;
  27. console.log(`${this.name}采取了防御姿态!`);
  28. }
  29. ultimateStrike(target: Player) {
  30. if (this.chargeCount === 2) {
  31. target.receiveDamage(999); // 直接秒杀
  32. this.chargeCount = 0;
  33. console.log(`${this.name}使用了终极大招!${target.name}被击败了!`);
  34. } else if (this.chargeCount === 1) {
  35. target.receiveDamage(this.power * 2); // 大招伤害为攻击的双倍
  36. this.chargeCount = 0;
  37. console.log(`${this.name}释放了大招!${target.name}受到了${this.power * 2}点伤害!`);
  38. } else {
  39. console.log(`${this.name}尚未蓄力足够,无法释放大招!`);
  40. }
  41. }
  42. reboundMove() {
  43. if (this.reboundUsed) {
  44. console.log(`${this.name}本局已经使用过反弹了!`);
  45. } else {
  46. this.reboundUsed = true;
  47. console.log(`${this.name}释放了反弹技能!`);
  48. }
  49. }
  50. receiveDamage(damage: number) {
  51. const actualDamage = Math.max(damage - this.defense, 0); // 考虑防御
  52. this.hp -= actualDamage;
  53. console.log(`${this.name}受到了${actualDamage}点伤害!`);
  54. if (this.hp <= 0) {
  55. console.log(`${this.name}被击败了!`);
  56. }
  57. }
  58. }
  59. // 游戏主逻辑
  60. function playGame() {
  61. const player1 = new Player('玩家1');
  62. const player2 = new Player('玩家2');
  63. while (player1.hp > 0 && player2.hp > 0) {
  64. // 玩家1的回合
  65. console.log('\n===== 玩家1的回合 =====');
  66. player1.attack(player2);
  67. // 玩家2的回合
  68. console.log('\n===== 玩家2的回合 =====');
  69. player2.charge();
  70. // 玩家1的回合
  71. console.log('\n===== 玩家1的回合 =====');
  72. player1.defenseMove();
  73. // 玩家2的回合
  74. console.log('\n===== 玩家2的回合 =====');
  75. player2.ultimateStrike(player1);
  76. // 重置防御
  77. player1.defense = 0;
  78. player2.defense = 0;
  79. // 判断玩家1是否被击败
  80. if (player1.hp <= 0) {
  81. break;
  82. }
  83. // 玩家1的回合
  84. console.log('\n===== 玩家1的回合 =====');
  85. player1.charge();
  86. // 玩家2的回合
  87. console.log('\n===== 玩家2的回合 =====');
  88. player2.attack(player1);
  89. // 玩家1的回合
  90. console.log('\n===== 玩家1的回合 =====');
  91. player1.reboundMove();
  92. // 判断玩家2是否被击败
  93. if (player2.hp <= 0) {
  94. break;
  95. }
  96. }
  97. }
  98. // 运行游戏
  99. playGame();