-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcard-played.js
104 lines (74 loc) · 2.6 KB
/
card-played.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
const { getGameById, validateRequest, sleep } = require('./utilities')
const {
isGameConflicted,
setGameInConflict,
conflictResolution,
startRound,
dealOutRewards,
setGameInTransition,
resolveConflict,
concludeGame
} = require('./game-engine')
const rejected = validateRequest({
tableName: 'plays',
operation: 'INSERT',
dataKeys: ['new'],
excludeAdminEvents: true
})
module.exports = async (req, res) => {
if (rejected(req)) {
return res.status(204).json({ message: 'irrelevant trigger' })
}
const freshPlay = req.body.event.data.new
let game = await getGameById(freshPlay.game_id)
if (!game) return res.status(204).json({ message: 'Error finding game' })
if (game.ready && !game.in_conflict && !game.round.is_blind && isGameConflicted(game)) {
game = await setGameInConflict(game)
if (!game) {
return res.status(500).json({ message: 'error setting game to conflicted' })
}
await sleep(1000)
game = await resolveConflict(game)
if (!game) {
return res.status(500).json({ message: 'error resolving conflict' })
}
await sleep(3000)
if (!game.lives || game.lives < 1) {
const gameConcluded = await concludeGame(game)
if (!gameConcluded) {
return res.status(500).json({ message: 'Failed to Conclude Game' })
}
return res.status(200).json({ message: `Game ${game.id} Concluded` })
}
}
if (!game.finished && !game.in_conflict && !game.transitioning_round && game.players.every(player => !player.cards.length)) {
if (game.round.is_blind && isGameConflicted(game)) {
game = await setGameInConflict(game)
if (!game) {
return res.status(500).json({ message: 'error setting game to conflicted' })
}
await sleep(1000)
game = await resolveConflict(game)
if (!game) {
return res.status(500).json({ message: 'error resolving conflict' })
}
await sleep(3000)
if (!game.lives || game.lives < 1) {
const gameConcluded = await concludeGame(game)
if (!gameConcluded) {
return res.status(500).json({ message: 'Failed to Conclude Game' })
}
return res.status(200).json({ message: `Game ${game.id} Concluded` })
}
}
const [transitioningGame, nextRound] = await setGameInTransition(game)
if (!transitioningGame) {
return res.status(500).json({ message: 'Error transitioning game' })
}
await sleep(3000)
await dealOutRewards(transitioningGame)
await sleep(1000)
await startRound(transitioningGame, nextRound)
}
res.status(200).json({ success: true })
}