@@ -3,34 +3,76 @@ import Games from '../api/collections/games.js';
33
44export default class GameList extends Component {
55 handleNewGame ( ) {
6- let gameDoc = {
7- board : [ [ null , null , null ] , [ null , null , null ] , [ null , null , null ] ]
8- } ;
9- Games . insert ( gameDoc ) ; // insert a new game document into the collection
6+ Games . newGame ( this . props . user ) ;
7+ }
8+
9+ handleLeaveGame ( gameId ) {
10+ Games . leaveGame ( gameId , this . props . user ) ;
11+ }
12+
13+ handleJoinGame ( gameId ) {
14+ Games . joinGame ( gameId , this . props . user ) ;
1015 }
1116
1217handleEnterGame ( gameId ) {
1318 this . props . enterGameHandler ( gameId ) ;
1419 }
1520
21+ myCurrentGameId ( ) {
22+ // find game where the user is currently in
23+ let game = _ . find ( this . props . games , ( game ) => {
24+ return _ . find ( game . players , ( player ) => {
25+ return player . userId === this . props . user . _id ;
26+ } ) !== undefined ;
27+ } ) ;
28+ if ( game === undefined ) return null ;
29+ return game . _id ;
30+ }
31+
32+ renderPlayers ( game ) {
33+ let player1 = game . players . length > 0 ? game . players [ 0 ] . username : '' ;
34+ let player2 = game . players . length > 1 ? game . players [ 1 ] . username : '' ;
35+ return (
36+ < span > [{ player1 } ] vs [{ player2 } ]</ span >
37+ )
38+ }
39+
1640render ( ) {
1741 return (
1842 < div >
1943 < div >
20- < button onClick = { this . handleNewGame . bind ( this ) } > New Game</ button >
21- </ div >
22-
23- < div >
2444 < h1 > List of games</ h1 >
2545 { this . props . games . map ( ( game , index ) => {
2646 return (
2747 < div key = { game . _id } >
2848 < span > Game { index + 1 } </ span >
29- < button onClick = { this . handleEnterGame . bind ( this , game . _id ) } > Enter</ button >
49+ { this . renderPlayers ( game ) }
50+
51+ { /* can leave only if user is in the game, and the game is not started */ }
52+ { this . myCurrentGameId ( ) === game . _id && game . players . length < 2 ? (
53+ < button onClick = { this . handleLeaveGame . bind ( this , game . _id ) } > Leave</ button >
54+ ) : null }
55+
56+ { /* can join only if user is not in any game, and the game is not started */ }
57+ { this . myCurrentGameId ( ) === null && game . players . length < 2 ? (
58+ < button onClick = { this . handleJoinGame . bind ( this , game . _id ) } > Join</ button >
59+ ) : null }
60+
61+ { /* can enter only if the game is started */ }
62+ { game . players . length === 2 ? (
63+ < button onClick = { this . handleEnterGame . bind ( this , game . _id ) } > Enter</ button >
64+ ) : null }
3065 </ div >
3166 )
3267 } ) }
3368 </ div >
69+
70+ { /* Only show new game button if player is not in any room */ }
71+ { this . myCurrentGameId ( ) === null ? (
72+ < div >
73+ < button onClick = { this . handleNewGame . bind ( this ) } > New Game</ button >
74+ </ div >
75+ ) : null }
3476 </ div >
3577 )
3678 }
0 commit comments