-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
329 lines (287 loc) · 8.79 KB
/
game.js
File metadata and controls
329 lines (287 loc) · 8.79 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
const HAND_SIZE = 10
const INITIAL_TOKENS = 14
const BOARD_ROWS = 10
const TIMER_INITIAL = 60
const COLORS = ['red', 'blue', 'green', 'yellow']
const NUM_PLAYERS = 4
async function connect () {
const client = deepstream.deepstream('localhost:6020')
await client.login()
return client
}
/*
* create a new game
*/
async function start (client, name) {
const gameStateRecord = client.record.getRecord('gameState')
const boardStateRecord = client.record.getRecord('boardState')
await gameStateRecord.whenReady()
await boardStateRecord.whenReady()
gameStateRecord.set(getInitialGameState())
boardStateRecord.set(getInitialBoardState())
const id = addPlayer(gameStateRecord, name, true)
const playerStateRecord = client.record.getRecord(`playerState/${id}`)
await playerStateRecord.whenReady()
playerStateRecord.set(getInitialPlayerState(id, name, true))
const records = { gameStateRecord, boardStateRecord, playerStateRecord }
client.rpc.provide('add-player', addPlayerRPC.bind(null, client, records))
genericGameInit(records)
}
/*
* join a game in progress
*/
async function join (client, name) {
const id = await client.rpc.make('add-player', { name })
if (id === null) {
throw 'team already full'
}
const gameStateRecord = client.record.getRecord('gameState')
const boardStateRecord = client.record.getRecord('boardState')
const playerStateRecord = client.record.getRecord(`playerState/${id}`)
await gameStateRecord.whenReady()
await boardStateRecord.whenReady()
await playerStateRecord.whenReady()
genericGameInit({ gameStateRecord, boardStateRecord, playerStateRecord })
}
function genericGameInit (records) {
Object.values(records).forEach(record => {
record.subscribe(onStateChanged.bind(null, records))
})
view.registerUpdateHooks({
moveTokenOnBoard: moveTokenOnBoard.bind(null, records),
moveTokenFromHand: moveTokenFromHand.bind(null, records),
takeTokenFromPile: takeTokenFromPile.bind(null, records),
endTurn: endTurn.bind(null, records),
startGame: startGame.bind(null, records)
})
onStateChanged(records)
}
function onStateChanged (records) {
const state = records.gameStateRecord.get('state')
switch (state) {
case STATE.WAITING_FOR_PLAYERS:
waitingForPlayers(records)
break
case STATE.PLAYING:
showBoard(records)
break
default:
throw new Error(`unknown state ${state}`)
}
}
function waitingForPlayers ({ playerStateRecord }) {
view.renderWaitingForPlayers(playerStateRecord.get())
}
function showBoard ({ gameStateRecord, boardStateRecord, playerStateRecord }) {
const changingPlayer = records.gameStateRecord.get('changingPlayer')
if (changingPlayer) {
const currentPlayer = records.gameStateRecord.get('currentPlayer')
const myId = records.playerStateRecord.get('id')
if (currentPlayer === myId) {
records.gameStateRecord.set('changingPlayer', false)
playerStateRecord.set('canTakeFromPile', true)
}
}
view.renderGameView({
playing: false,
gameState: gameStateRecord.get(),
boardState: boardStateRecord.get(),
playerState: playerStateRecord.get()
})
}
function addPlayerRPC (client, { gameStateRecord }, { name }, response) {
const id = addPlayer(gameStateRecord, name, false)
client.record.setData(`playerState/${id}`, getInitialPlayerState(id, name, false))
.then(() => response.send(id))
}
function addPlayer (gameStateRecord, name, isMaster) {
const players = gameStateRecord.get('players')
let id = null
for (let i = 0; i < NUM_PLAYERS; i++) {
if (players.indexOf(i) < 0) {
id = i
}
}
if (id !== null) {
players.push(id)
gameStateRecord.set('players', players)
gameStateRecord.set('playerInfo[id]', { name })
if (isMaster) {
gameStateRecord.set('master', id)
}
}
return id
}
function getInitialPlayerState (id, name, isMaster) {
return {
id,
name,
isMaster,
hand: [],
timeRemaining: 0,
canTakeFromPile: null
}
}
function getInitialGameState () {
return {
master: null,
players: [],
playerInfo: {},
currentPlayer: null,
state: STATE.WAITING_FOR_PLAYERS,
changingPlayer: null
}
}
function getInitialBoardState () {
return {
groups: [],
pile: [],
isValid: true
}
}
function createPile () {
const pile = []
for (const color of COLORS) {
for (const num = 1; num <= 13; num++) {
pile.push({ color, num })
pile.push({ color, num })
}
}
return pile
}
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
* @see: https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
/*
* Shuffle the pile and deal 14 tokens to each player
*/
function dealBoard ({ gameStateRecord, boardStateRecord }) {
const pile = createPile()
shuffle(pile)
const players = gameStateRecord.get('players')
const pile = boardStateRecord.get('pile')
for (const playerId of players) {
for (let i = 0; i < INITIAL_TOKENS; i++) {
player.hand[i] = pile.pop()
}
}
boardStateRecord.set('pile', pile)
}
function moveTokenOnBoard (records, { token, fromGroupId, toGroupId }) {
const { boardStateRecord } = records
const fromGroup = boardStateRecord.get(`groups[${fromGroupId}]`) || []
const toGroup = boardStateRecord.get(`groups[${toGroupId}]`) || []
const fromGroupIndex = fromGroup
.findIndex(tok => tok.color === token.color && tok.num === token.num)
if (fromGroupIndex < 0) {
console.log('warning: tried to move token not in group', token, fromGroupId, toGroupId)
return
}
fromGroup.splice(fromGroupIndex, 1)
sortedInsert(groups[toGroupId], token)
boardStateRecord.set(`groups[${fromGroupId}]`, fromGroup)
boardStateRecord.set(`groups[${toGroupId}]`, toGroup)
if (groupState.every(groupIsValid)) {
// enable DONE button
} else {
// disable DONE button
}
}
function sortedInsert (group, token) {
const idx = group.findIndex(
tok => tok.color === token.color && tok.num > token.num || tok.color > token.color
)
if (idx < 0) {
group.push(token)
} else {
group.splice(idx, 0, token)
}
return group
}
function moveTokenFromHand ({ boardStateRecord, playerStateRecord }, { token, toGroupId }) {
const toGroup = boardStateRecord.get(`groups[${toGroupId}]`) || []
const hand = playerStateRecord.get('hand')
const handIndex = hand
.findIndex(tok => tok.color === token.color && tok.num === token.num)
if (fromGroupIndex < 0) {
console.log('warning: tried to move token not in hand', token, hand, toGroupId)
return
}
hand.splice(fromGroupIndex, 1)
sortedInsert(groups[toGroupId], token)
playerStateRecord.set('hand', hand)
boardStateRecord.set(`groups[${toGroupId}]`, toGroup)
playerStateRecord.set('canTakeFromPile', false)
}
function takeTokenFromPile ({ boardStateRecord, playerStateRecord }) {
const pile = boardStateRecord.get('pile')
const token = pile.pop()
boardStateRecord.set('pile', pile)
const hand = playerStateRecord.get('hand')
hand.push(token)
playerStateRecord.set('hand', hand)
playerStateRecord.set('canTakeFromPile', false)
view.addTokenToHand(token)
}
function groupIsValid (group) {
return group.length >= 3 && (isRun(group) || isSet(group))
}
/*
* check if a group is a run e.g.
* [{color: 'red', num: 4}, {color: 'red', num: 5}, {color: 'red', num: 6}]
*/
function isRun (group) {
let { num, color } = group[0]
for (let i = 1; i < group.length; i++) {
if (group[i].color !== color || group[i].num !== ++num) {
return false
}
}
return true
}
/*
* check if a group is a set e.g.
* [{color: 'red', num: 4}, {color: 'green', num: 4}, {color: 'blue', num: 4}]
*/
function isSet (group) {
let { num, color } = group[0]
for (let i = 1; i < group.length; i++) {
if (group[i].num !== num || group.slice(i).some(({ color: c }) => c === color)) {
return false
}
}
return true
}
function getNextPlayer (players, currentPlayer) {
return players[(players.indexOf(currentPlayer) + 1) % players.length]
}
function endTurn ({ gameStateRecord, playerStateRecord }) {
const players = gameStateRecord.get('players')
const currentPlayer = gameStateRecord.get('currentPlayer')
const nextPlayer = getNextPlayer(players, currentPlayer)
gameStateRecord.set('currentPlayer', nextPlayer)
gameStateRecord.set('changingPlayer', true)
}
function timerExpire (boardStateRecord) {
}
function startGame (records) {
dealBoard(records)
const { gameStateRecord, playerStateRecord, boardStateRecord } = records
const me = playerStateRecord.get('id')
gameStateRecord.set('currentPlayer', getNextPlayer(me))
gameStateRecord.set('changingPlayer', true)
}
game = {
connect,
start,
join
}