/
02_rock_paper_scissors_object_literals.js
76 lines (66 loc) · 2.45 KB
/
02_rock_paper_scissors_object_literals.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// a module defined using object literal notation
// https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript
var myGame = {
// In object literal notation, an object is described as a set of comma-separated name/value pairs enclosed in curly braces.
// Names inside the object may be either strings or identifiers that are followed by a colon.
// object literals can contain properties and methods:
playerChoiceDisplay: document.getElementById("player_choice"),
computerChoiceDisplay: document.getElementById("computer_choice"),
resultDisplay: document.getElementById("result"),
computerChoice: '',
userChoice: '',
// a method
functionkey: function () {
'use strict';
},
computerInput: function () {
switch (Math.floor(Math.random() * 3)) {
case 0:
this.computerChoice = "Rock";
break;
case 1:
this.computerChoice = "Paper";
break;
case 2:
this.computerChoice = "Scissors";
}
},
compare: function () {
// game is a draw
if (this.userChoice === this.computerChoice) {
this.resultDisplay.innerHTML = 'Game is a draw!';
// all other possibilities
} else if (this.userChoice === 'Paper' && this.computerChoice === 'Rock') {
this.resultDisplay.innerHTML = 'You win!';
} else if (this.userChoice === 'Paper' && this.computerChoice === 'Scissors') {
this.resultDisplay.innerHTML = 'You loose!';
} else if (this.userChoice === 'Scissors' && this.computerChoice === 'Rock') {
this.resultDisplay.innerHTML = 'You loose!';
} else if (this.userChoice === 'Scissors' && this.computerChoice === 'Paper') {
this.resultDisplay.innerHTML = 'You win!';
} else if (this.userChoice === 'Rock' && this.computerChoice === 'Paper') {
this.resultDisplay.innerHTML = 'You loose!';
} else if (this.userChoice === 'Rock' && this.computerChoice === 'Scissors') {
this.resultDisplay.innerHTML = 'You win!';
}
},
display : function (){
// to make user and computer choice visible
this.playerChoiceDisplay.innerHTML = this.userChoice;
this.computerChoiceDisplay.innerHTML = this.computerChoice;
}
///// object end /////
};
// The buttons
var buttons = document.getElementsByClassName("button"); // returning an array
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', play);
}
// main logic
function play() {
//myGame.functionkey();
myGame.userChoice = this.id; // registering the buttons id!
myGame.computerInput();
myGame.compare();
myGame.display();
}