aboutsummaryrefslogtreecommitdiffstats
path: root/public/projects/js-small-apps/rock-paper-scissors/lib/rps-instance.js
diff options
context:
space:
mode:
authorArmand Philippot <git@armandphilippot.com>2022-02-20 16:11:50 +0100
committerArmand Philippot <git@armandphilippot.com>2022-02-20 16:15:08 +0100
commit73a5c7fae9ffbe9ada721148c8c454a643aceebe (patch)
treec8fad013ed9b5dd589add87f8d45cf02bbfc6e91 /public/projects/js-small-apps/rock-paper-scissors/lib/rps-instance.js
parentb01239fbdcc5bbc5921f73ec0e8fee7bedd5c8e8 (diff)
chore!: restructure repo
I separated public files from the config/dev files. It improves repo readability. I also moved dotenv helper to public/inc directory and extract the Matomo tracker in the same directory.
Diffstat (limited to 'public/projects/js-small-apps/rock-paper-scissors/lib/rps-instance.js')
-rw-r--r--public/projects/js-small-apps/rock-paper-scissors/lib/rps-instance.js70
1 files changed, 70 insertions, 0 deletions
diff --git a/public/projects/js-small-apps/rock-paper-scissors/lib/rps-instance.js b/public/projects/js-small-apps/rock-paper-scissors/lib/rps-instance.js
new file mode 100644
index 0000000..73c5888
--- /dev/null
+++ b/public/projects/js-small-apps/rock-paper-scissors/lib/rps-instance.js
@@ -0,0 +1,70 @@
+import RPS_Game from "./rps-game.js";
+
+export default class RPS_Instance extends RPS_Game {
+ #buttons = {};
+ #scoring = { player1: '', player2: '' };
+ #resultBox = '';
+ #resultMsg = '';
+
+ constructor(player1, player2, buttons, scoring, result) {
+ super(player1, player2);
+ this.#buttons = buttons;
+ this.#scoring = scoring;
+ this.#resultBox = result;
+ this.#resultMsg = result.innerHTML;
+ }
+
+ updateScoring() {
+ for (const [name, element] of Object.entries(this.#scoring)) {
+ if ( 'player1' === name ) {
+ element.innerHTML = this.player1Score;
+ }
+
+ if ( 'player2' === name ) {
+ element.innerHTML = this.player2Score;
+ }
+ }
+ }
+
+ updateResult(result = '') {
+ let txt;
+ if ( result === 'player1' ) {
+ txt = this.player1Choice + ' beats ' + this.player2Choice + ".<br>You win!"
+ this.#resultBox.style.color = 'green';
+ } else if ( result === 'player2' ) {
+ txt = this.player1Choice + ' loses to ' + this.player2Choice + ".<br>You lose..."
+ this.#resultBox.style.color = 'red';
+ } else if ( result === 'even' ) {
+ txt = this.player1Choice + ' equals to ' + this.player2Choice + ".<br>No winner.";
+ this.#resultBox.style.color = 'black';
+ } else {
+ txt = this.#resultMsg;
+ this.#resultBox.style.color = '';
+ }
+
+ this.#resultBox.innerHTML = txt;
+ }
+
+ listen() {
+ for (const [name, element] of Object.entries(this.#buttons)) {
+ element.addEventListener('click', () => {
+ if ( 'reset' === name ) {
+ this.reset();
+ this.updateResult();
+ this.updateScoring();
+ } else {
+ this.player1Choice = name;
+ const result = this.calculateScore();
+ this.setScore(result);
+ this.updateResult(result);
+ this.updateScoring();
+ }
+ })
+ }
+ }
+
+ init() {
+ this.reset();
+ this.listen();
+ }
+}