mercredi 4 décembre 2019

Syncing a random variable

I am currently making simple UI for my rock paper scissors game. I am using a random number for my getComputerChoice function which then is used to display an image and decide the outcome of the game. I tried setting the outcome of getComputerChoice to a variable but then I ran into the issue that the computer's choice would remain the same each time I ran a new game.

const model = {
  wins: 0,
  losses: 0,
  draws: 0,

  getCompChoice: function() {
    var num = Math.floor(Math.random() * 3);
    var choices = ["rock", "paper", "scissors"];

    var choice = choices[num];
    return choice;
  },

  gameLogic: function(player, computer) {
    if (player === false) {
      return alert("Please enter a valid guess");
    } else if (player === computer) {
      this.draws++;
      return "draw";
    } else if (
      (player === "rock" && computer === "paper") ||
      (player === "paper" && computer === "scissors") ||
      (player === "scissors" && computer === "rock")
    ) {
      this.losses++;
      return "lose";
    } else {
      this.wins++;
      return "win";
    }
  }
};
const view = {
  updateScore: function() {
    document.getElementById("wins").textContent = "Wins:" + " " + model.wins;
    document.getElementById("losses").textContent =
      "Losses:" + " " + model.losses;
    document.getElementById("draws").textContent = "Draws:" + " " + model.draws;
    return;
  },
  displayRollComputer: function() {
    var computer = document.getElementById("computer");
    computer.classList.remove("rock", "paper", "scissors");
    computer.classList.add(controller.compChoice);
    console.log(controller.compChoice);
  },
  displayRollUser: function() {
    var user = document.getElementById("user");
    user.classList.remove("rock", "paper", "scissors");
    user.classList.add(processPlayer());
  }
};
const controller = {
  compChoice: model.getCompChoice(),

  play: function() {
    model.gameLogic(processPlayer(), this.compChoice);
    view.updateScore();
    view.displayRollComputer();
    view.displayRollUser();
  }
};

// Helper Functions
function processPlayer() {
  const player = document.getElementById("guess").value;

  if (player === "rock" || player === "paper" || player === "scissors") {
    return player;
  } else {
    return false;
  }
}



Aucun commentaire:

Enregistrer un commentaire