]> git.cworth.org Git - lmno.games/blob - tictactoe/tictactoe.jsx
Add a simple player-info div
[lmno.games] / tictactoe / tictactoe.jsx
1 const Team = {
2   X: 0,
3   O: 1,
4   properties: {
5     0: {name: "X"},
6     1: {name: "O"}
7   }
8 };
9
10 function undisplay(element) {
11   element.style.display="none";
12 }
13
14 function add_message(severity, message) {
15   message = `<div class="message ${severity}" onclick="undisplay(this)">
16 <span class="hide-button" onclick="undisplay(this.parentElement)">&times;</span>
17 ${message}
18 </div>`;
19   const message_area = document.getElementById('message-area');
20   message_area.insertAdjacentHTML('beforeend', message);
21 }
22
23 /*********************************************************
24  * Handling server-sent event stream                     *
25  *********************************************************/
26
27 const events = new EventSource("events");
28
29 events.onerror = function(event) {
30   if (event.target.readyState === EventSource.CLOSED) {
31       add_message("danger", "Connection to server lost.");
32   }
33 };
34
35 events.addEventListener("game-info", event => {
36   const info = JSON.parse(event.data);
37
38   window.game.set_game_info(info);
39 });
40
41 events.addEventListener("player-info", event => {
42   const info = JSON.parse(event.data);
43
44   window.game.set_player_info(info);
45 });
46
47 events.addEventListener("player-update", event => {
48   const info = JSON.parse(event.data);
49
50   if (info.id === window.game.state.player_info.id)
51     window.game.set_player_info(info);
52 });
53
54 events.addEventListener("move", event => {
55   const move = JSON.parse(event.data);
56
57   window.game.receive_move(move);
58 });
59
60 events.addEventListener("game-state", event => {
61   const state = JSON.parse(event.data);
62
63   window.game.reset_board();
64
65   for (let square of state.moves) {
66     window.game.receive_move(square);
67   }
68 });
69
70 /*********************************************************
71  * Game and supporting classes                           *
72  *********************************************************/
73
74 function GameInfo(props) {
75   return (
76     <div className="game-info">
77       <h2>{props.id}</h2>
78       Invite a friend to play by sending this URL: {props.url}
79     </div>
80   );
81 }
82
83 function PlayerInfo(props) {
84   return (
85     <div className="player-info">
86       <h2>Player</h2>
87       {props.name}, ID: {props.id}, on team: {props.team}
88     </div>
89   );
90 }
91
92 function Square(props) {
93   let className = "square";
94
95   if (props.value) {
96     className += " occupied";
97   } else if (props.active) {
98     className += " open";
99   }
100
101   const onClick = props.active ? props.onClick : null;
102
103   return (
104     <div className={className}
105          onClick={onClick}>
106       {props.value}
107     </div>
108   );
109 }
110
111 class Board extends React.Component {
112   render_square(i) {
113     const value = this.props.squares[i];
114     return (
115       <Square
116         value={value}
117         active={! this.props.game_over && ! value}
118         onClick={() => this.props.onClick(i)}
119       />
120     );
121   }
122
123   render() {
124     return (
125       <div>
126         <div className="board-row">
127           {this.render_square(0)}
128           {this.render_square(1)}
129           {this.render_square(2)}
130         </div>
131         <div className="board-row">
132           {this.render_square(3)}
133           {this.render_square(4)}
134           {this.render_square(5)}
135         </div>
136         <div className="board-row">
137           {this.render_square(6)}
138           {this.render_square(7)}
139           {this.render_square(8)}
140         </div>
141       </div>
142     );
143   }
144 }
145
146 function fetch_post_json(api = '', data = {}) {
147   const response = fetch(api, {
148     method: 'POST',
149     headers: {
150       'Content-Type': 'application/json'
151     },
152     body: JSON.stringify(data)
153   });
154   return response;
155 }
156
157 class Game extends React.Component {
158   constructor(props) {
159     super(props);
160     this.state = {
161       game_info: {},
162       player_info: {},
163       history: [
164         {
165           squares: Array(9).fill(null)
166         }
167       ],
168       step_number: 0,
169       next_to_play: Team.X
170     };
171   }
172
173   set_game_info(info) {
174     this.setState({
175       game_info: info
176     });
177   }
178
179   set_player_info(info) {
180     this.setState({
181       player_info: info
182     });
183   }
184
185   send_move(i) {
186     return fetch_post_json("move", { move: i });
187   }
188
189   reset_board() {
190     this.setState({
191       history: [
192         {
193           squares: Array(9).fill(null)
194         }
195       ],
196       step_number: 0,
197       next_to_play: Team.X
198     });
199   }
200
201   receive_move(i) {
202     const history = this.state.history.slice(0, this.state.step_number + 1);
203     const current = history[history.length - 1];
204     const squares = current.squares.slice();
205     if (calculate_winner(squares) || squares[i]) {
206       return;
207     }
208     squares[i] = Team.properties[this.state.next_to_play].name;
209     let next_to_play;
210     if (this.state.next_to_play === Team.X)
211       next_to_play = Team.O;
212     else
213       next_to_play = Team.X;
214     this.setState({
215       history: history.concat([
216         {
217           squares: squares
218         }
219       ]),
220       step_number: history.length,
221       next_to_play: next_to_play
222     });
223   }
224
225   async handle_click(i) {
226     const response = await this.send_move(i);
227     if (response.status == 200) {
228       const result = await response.json();
229       if (! result.legal)
230         add_message("danger", result.message);
231     } else {
232       add_message("danger", `Error occurred sending move`);
233     }
234   }
235
236   render() {
237     const history = this.state.history;
238     const current = history[this.state.step_number];
239     const winner = calculate_winner(current.squares);
240
241     let status;
242     if (winner) {
243       status = "Winner: " + winner;
244     } else {
245       status = "Next player: " + (Team.properties[this.state.next_to_play].name);
246     }
247
248     return [
249       <GameInfo
250         id={this.state.game_info.id}
251         url={this.state.game_info.url}
252       />,
253       <PlayerInfo
254         id={this.state.player_info.id}
255         name={this.state.player_info.name}
256         team={this.state.player_info.team}
257       />,
258       <div className="game">
259         <div>{status}</div>
260         <div className="game-board">
261           <Board
262             game_over={winner}
263             squares={current.squares}
264             onClick={i => this.handle_click(i)}
265           />
266         </div>
267       </div>
268     ];
269   }
270 }
271
272 ReactDOM.render(<Game
273                   ref={(me) => window.game = me}
274                 />, document.getElementById("tictactoe"));
275
276 function calculate_winner(squares) {
277   const lines = [
278     [0, 1, 2],
279     [3, 4, 5],
280     [6, 7, 8],
281     [0, 3, 6],
282     [1, 4, 7],
283     [2, 5, 8],
284     [0, 4, 8],
285     [2, 4, 6]
286   ];
287   for (let i = 0; i < lines.length; i++) {
288     const [a, b, c] = lines[i];
289     if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
290       return squares[a];
291     }
292   }
293   return null;
294 }