task-tsgame.js 2.5 KB

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