Advertisement
Guest User

david

a guest
Feb 24th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Observable() {
  2.   this.observers = [];
  3.  
  4.   this.add = function (observer) {
  5.     this.observers.push(observer);
  6.   };
  7.  
  8.   this.notify = function (obj) {
  9.     this.observers.forEach(function (observer) {
  10.       observer.call(null, obj);  
  11.     });
  12.   };
  13. }
  14.  
  15. function PokemonCombate(pokemon1, pokemon2){
  16.   this.observable = new Observable();
  17.  
  18.   this.pokemon1 = pokemon1;
  19.   this.pokemon2 = pokemon2;
  20.   this.ronda = 1;
  21. }
  22.  
  23. PokemonCombate.prototype.combatir = function () {
  24.     var ganador,
  25.         perdedor;
  26.  
  27.   if(Math.floor((Math.random() * 2) + 1) === 1) {
  28.       ganador = this.pokemon1;
  29.       perdedor = this.pokemon2;
  30.   } else {
  31.       ganador = this.pokemon2;
  32.       perdedor = this.pokemon1;
  33.   }
  34.  
  35.   this.observable.notify({
  36.     ganador: ganador,
  37.     perdedor: perdedor,
  38.     ronda: this.ronda
  39.   });
  40.  
  41.   this.ronda++;
  42. };
  43.  
  44. window.onload = function(){
  45.   var combate = new PokemonCombate('Pikachu', 'Meowth');
  46.  
  47.   combate.observable.add(function(obj){
  48.     document.getElementById("ganador").innerHTML = ('El ganador de la ronda ' + obj.ronda + ' es: ' + obj.ganador);
  49.   });
  50.  
  51.   combate.observable.add(function(obj){
  52.     document.getElementById("perdedor").innerHTML = ('El perdedor de la ronda ' + obj.ronda + ' es: ' + obj.perdedor);
  53.   });
  54.  
  55.   document.querySelector('#combate').addEventListener('click', function(){
  56.     combate.combatir();
  57.   })
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement