/
index.vr.js
114 lines (95 loc) · 2.59 KB
/
index.vr.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
import React from 'react'
import { AppRegistry, View } from 'react-vr'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import Board from './components/Board';
import Scores from './components/Scores';
import app from './reducers'
import { board, countValues } from './reducers/board'
import uuid from 'uuid'
const client = uuid()
// master is client with first sorted client id.
const isMasterClient = (clients) => {
if (! clients) {
return false;
}
let master = Object.keys(clients).sort()[0]
return master === client
}
const setState = (state) => (
{
type: 'SET_STATE',
state: state,
sender: client
}
)
const join = (client) => (
{
type: 'JOIN',
client: client
}
)
const score = (scores, client) => (
{
type: 'SCORE',
client: client,
score: scores[client] + 1
}
)
const ws = new window.WebSocket('ws://localhost:4000')
// generate scores if master client
const scoreMaster = store => next => action => {
let state = store.getState()
if (isMasterClient(state.scores) && (action.type === 'SHOW')) {
let value = state.board[action.square.row][action.square.column]
if (countValues(state.board, Math.abs(value)) === 1) {
// if one half of pair is visible now, both will be after
// action is reduced, so generate score action.
store.dispatch(score(state.scores, action.client))
}
}
return next(action)
}
// send actions to other clients if not received over network
const sendAction = store => next => action => {
if (! ('sender' in action)) {
action.sender = client
ws.send(JSON.stringify(action))
}
return next(action)
}
const store = createStore(
app,
applyMiddleware(scoreMaster, sendAction)
)
// read actions from network and dispatch locally
ws.onmessage = (evt) => {
let action = JSON.parse(evt.data)
console.log(action)
// existing master client sends state to other clients after processing join
let master = isMasterClient(store.getState().scores)
// dispatch action locally
store.dispatch(action)
// sync state if join
// TODO(jimp): only send state to new client...
if (master && action.type === 'JOIN') {
ws.send(JSON.stringify(setState(store.getState())))
}
}
// send initial join action when websocket is ready
ws.onopen = (evt) => {
store.dispatch(join(client))
}
class App extends React.Component {
render() {
return (
<Provider store={store}>
<View>
<Board client={client}/>
<Scores client={client}/>
</View>
</Provider>
)
}
}
AppRegistry.registerComponent('pairs', () => App)