Skip to content

Commit

Permalink
make computer moves, Close #6
Browse files Browse the repository at this point in the history
  • Loading branch information
an4s911 committed Jul 26, 2023
1 parent 6a43d1a commit 87534d8
Showing 1 changed file with 32 additions and 14 deletions.
46 changes: 32 additions & 14 deletions script.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,38 +54,52 @@ const currentTurn = {
},
switchPlayer: function () {
if (this.currentPlayer === user) {
rollBtn.setAttribute("disabled", false);
turnOverBtn.setAttribute("disabled", false);
this.player = computer;
} else {
rollBtn.setAttribute("disabled", true);
turnOverBtn.setAttribute("disabled", true);
this.player = computer;
emulateComputerTurn();
} else {
rollBtn.removeAttribute("disabled");
turnOverBtn.removeAttribute("disabled");
this.player = user;
}
turnPronounElement.textContent = this.currentPlayer.pronoun;
},
};

rollBtn.addEventListener("click", () => {
rollBtn.addEventListener("click", rollAndValidate);

turnOverBtn.addEventListener("click", turnOver);

function turnOver() {
currentTurn.player.score += currentTurn.score;
setTimeout(() => {
currentTurn.score = 0;
}, 800);

currentTurn.switchPlayer();
}

function rollAndValidate() {
const rollDetails = rollDice();
const validationResult = rollDetails.validateRoll();
if (validationResult === 1) {
currentTurn.score += rollDetails.rollValue;
if (currentTurn.player === computer) {
if (currentTurn.score >= 20) {
turnOver();
} else {
emulateComputerTurn();
}
}
} else {
currentTurn.score = 0;
if (validationResult === -1) {
currentTurn.player.score = 0;
}
currentTurn.switchPlayer();
turnOver();
}
});

turnOverBtn.addEventListener("click", () => {
currentTurn.player.score += currentTurn.score;
currentTurn.score = 0;

currentTurn.switchPlayer();
});
}

function rollDice() {
return {
Expand Down Expand Up @@ -114,3 +128,7 @@ function rollDie(die) {

return randomNumber + 1;
}

function emulateComputerTurn() {
setTimeout(rollAndValidate, 2000);
}

0 comments on commit 87534d8

Please sign in to comment.