task-tsgame.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. class Player {
  2. life: number;
  3. choices: string[];
  4. constructor() {
  5. this.life = 3;
  6. this.choices = ['石头', '剪刀', '布'];
  7. }
  8. makeChoice(): number {
  9. return Math.floor(Math.random() * 3) + 1;
  10. }
  11. }
  12. class Game {
  13. players: Player[];
  14. constructor() {
  15. this.players = [new Player(), new Player()];
  16. }
  17. playGame(): void {
  18. console.log('游戏开始!');
  19. while (this.players[0].life > 0 && this.players[1].life > 0) {
  20. this.playRound();
  21. }
  22. this.endGame();
  23. }
  24. playRound(): void {
  25. const player1Choice = this.players[0].makeChoice();
  26. const player2Choice = this.players[1].makeChoice();
  27. const result = this.getResult(player1Choice, player2Choice);
  28. this.printRoundResult(player1Choice, player2Choice, result);
  29. if (result === 1) {
  30. this.players[1].life--;
  31. } else if (result === -1) {
  32. this.players[0].life--;
  33. }
  34. this.printLifeStatus();
  35. }
  36. getResult(choice1: number, choice2: number): number {
  37. if (choice1 === choice2) {
  38. return 0;
  39. } else if (
  40. (choice1 === 1 && choice2 === 2) ||
  41. (choice1 === 2 && choice2 === 3) ||
  42. (choice1 === 3 && choice2 === 1)
  43. ) {
  44. return 1;
  45. } else {
  46. return -1;
  47. }
  48. }
  49. printRoundResult(choice1: number, choice2: number, result: number): void {
  50. console.log('对局开始:');
  51. console.log(`玩家1选择了${this.players[0].choices[choice1 - 1]}`);
  52. console.log(`玩家2选择了${this.players[1].choices[choice2 - 1]}`);
  53. if (result === 0) {
  54. console.log('平局!');
  55. } else if (result === 1) {
  56. console.log('玩家1赢了!');
  57. } else {
  58. console.log('玩家2赢了!');
  59. }
  60. }
  61. printLifeStatus(): void {
  62. console.log(`玩家1生命值:${this.players[0].life}`);
  63. console.log(`玩家2生命值:${this.players[1].life}`);
  64. console.log('----------------------');
  65. }
  66. endGame(): void {
  67. console.log('游戏结束!');
  68. }
  69. }
  70. // 创建游戏实例并开始对战
  71. const game = new Game();
  72. game.playGame();