-
Notifications
You must be signed in to change notification settings - Fork 1
/
game-event-handlers.js
119 lines (91 loc) · 3.63 KB
/
game-event-handlers.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
app.factory('GameEventHandlers', function ($timeout, Utils) {
return function ($scope) {
var flipOpponentsCard = function (show) {
show = show || false;
angular.element(document.body).toggleClass('property-chosen', show);
},
nextTurn = function (wonLastRound) {
flipOpponentsCard();
$scope.win = null;
//wonLastRound == 1 if won, 0 if draw, -1 if lost
if (wonLastRound !== 0) {
$scope.myGo = wonLastRound === 1 ? true : false;
}
$scope.myCard = Utils.makeCard();
},
handleResult = function (whoWon) {
var winner;
// draw logic
if (whoWon === 'draw') {
$scope.status = 'Draw!';
winner = 0;
$scope.drawScore += 1;
$timeout(function () {
nextTurn(winner); //needs to be the same person
}, 2500);
// win lose logic
} else {
winner = whoWon === 'me' ? 1 : -1;
$scope.scores[whoWon] += 1;
$scope.scores[whoWon] += $scope.drawScore;
$scope.drawScore = 0;
$scope.state = winner === 1 ? 'You win' : 'You lost';
$scope.status = $scope.state;
// Do we need to celebrate for too long?
$timeout(function () {
nextTurn(winner);
}, 2500);
}
},
sendCard = function () {
$scope.status = 'Sending a card';
$scope.sendCard($scope.myCard);
},
init = function () {
// Create your first card.
$scope.myCard = Utils.makeCard();
$scope.win = null;
$scope.state = null;
$scope.drawScore = 0;
// $scope.myGo is initialised in the main controller
$scope.scores = {
'me' : 0,
'opponent' : 0
};
};
init();
return {
scope: $scope,
onReadyToPlay: function (event) {
$scope.status = 'Opponent is ready to play';
},
onPropertyChosen: function (event, propertyName) {
if ($scope.myGo) {
$scope.status = 'You chose to play with ' + propertyName;
$scope.myCard.chosenProperty = propertyName;
sendCard();
}
},
onCardReceived: function (event, cardData) {
var chosenProperty;
// Setting the opponent card is important for the opponent's card
// to display correctly in it's card directive.
$scope.opponentCard = cardData;
flipOpponentsCard(true);
// Avoid an infinite loop yes :)
if (!$scope.myGo) {
sendCard();
}
// What property did you/opponent choose?
chosenProperty = $scope.myGo ?
$scope.myCard.chosenProperty :
cardData.chosenProperty;
Utils.calculateWinner(
chosenProperty,
cardData.cardDetails,
$scope.myCard.cardDetails
).then(handleResult);
}
};
};
});