Lobby joining

master
Wilco Kruijer 5 years ago
parent ddeaca06c2
commit 3f7987f482
  1. 35
      backend/src/index.js
  2. 33
      backend/src/service.js
  3. 10
      frontend/src/App.tsx
  4. 72
      frontend/src/components/Lobby.tsx
  5. 16
      frontend/src/css/lobby.css
  6. 13
      frontend/src/util/socket.ts

@ -17,10 +17,10 @@ io.on('connection', socket => {
console.log('a user connected', socketId); console.log('a user connected', socketId);
const lobby = service.joinLobby(socketId); const lobby = state.createRandomLobby();
service.joinLobby(socketId, lobby.name);
socket.join(lobby.name); socket.join(lobby.name);
socket.emit('welcome', {lobby: lobby.name}); socket.emit('welcome', {lobby: lobby});
socket.on('disconnect', (reason) => { socket.on('disconnect', (reason) => {
console.log('Disconnected:', socketId); console.log('Disconnected:', socketId);
@ -28,6 +28,19 @@ io.on('connection', socket => {
}); });
socket.on('join_lobby', (lobbyId, callback) => { socket.on('join_lobby', (lobbyId, callback) => {
if (!callback || typeof callback !== 'function') {
console.error("Callback not a function.");
return
}
if (!lobbyId) {
return callback('no_lobby_id_given');
}
if (!Number.isSafeInteger(+lobbyId)) {
return callback('lobby_id_not_integer');
}
console.log(`${socketId} wants to join '${lobbyId}'.`); console.log(`${socketId} wants to join '${lobbyId}'.`);
// Leave current lobby first // Leave current lobby first
@ -38,7 +51,21 @@ io.on('connection', socket => {
callback(null, { callback(null, {
status: 'ok', status: 'ok',
lobby: lobby.name lobby: lobby
}); });
}); });
socket.on('lobby_info', callback => {
if (!callback || typeof callback !== 'function') {
console.error("Callback not a function.");
return
}
const lobby = service.getUserLobby(socketId);
callback(null, {
status: 'ok',
lobby: lobby
});
})
}); });

@ -4,13 +4,13 @@ const state = require("./state.js");
/** /**
* *
* @param {string} socketId * @param {string} socketId
* @param {number|undefined} lobbyId * @param {number} lobbyId
* @returns {Lobby} * @returns {Lobby}
*/ */
function joinLobby(socketId, lobbyId=undefined) { function joinLobby(socketId, lobbyId) {
let lobby = state.getLobby(lobbyId); let lobby = state.getLobby(lobbyId);
if (!lobby) { if (!lobby) {
lobby = state.createRandomLobby(); lobby = state.createLobby(lobbyId);
} }
lobby.addUser(new User(socketId)); lobby.addUser(new User(socketId));
@ -27,6 +27,10 @@ function leaveLobby(socketId) {
Object.keys(state.lobbies).forEach(lobbyId => { Object.keys(state.lobbies).forEach(lobbyId => {
const lobby = state.getLobby(lobbyId); const lobby = state.getLobby(lobbyId);
if (!lobby) {
return;
}
lobby.removeUser(socketId); lobby.removeUser(socketId);
if (!lobby.hasUsers()) { if (!lobby.hasUsers()) {
@ -40,4 +44,25 @@ function leaveLobby(socketId) {
}); });
} }
module.exports = {joinLobby, leaveLobby}; /**
*
* @param socketId
* @returns {Lobby|undefined}
*/
function getUserLobby(socketId) {
for (let lobbyId of Object.keys(state.lobbies)) {
const lobby = state.getLobby(lobbyId);
if (!lobby) {
continue;
}
if (lobby.getUser(socketId)) {
return lobby;
}
}
return undefined;
}
module.exports = {joinLobby, leaveLobby, getUserLobby};

@ -15,11 +15,8 @@ const App = () => {
useEffect(() => { useEffect(() => {
socket.on('welcome', async (obj: any) => { socket.on('welcome', async (obj: any) => {
const {lobby} = obj; setLobbyId(obj.lobby.name);
setLobbyId(lobby);
setConnected(true); setConnected(true);
// const joined = await emit('join_lobby', 123);
}); });
return () => { return () => {
@ -37,9 +34,7 @@ const App = () => {
); );
const lobbyContent = ( const lobbyContent = (
<Row> <Lobby/>
<Lobby/>
</Row>
); );
const content = lobbyContent; const content = lobbyContent;
@ -51,7 +46,6 @@ const App = () => {
</section> </section>
<footer> <footer>
<img src={logo} className="via-logo" alt="logo"/> <img src={logo} className="via-logo" alt="logo"/>
<span>{connected ? 'Verbonden ' + lobbyId : ''}</span>
</footer> </footer>
</> </>
); );

@ -1,24 +1,74 @@
import React, {useEffect} from 'react'; import React, {useEffect, useState} from 'react';
import {Col, Progress} from "antd" import {Card, Col, InputNumber, Row} from "antd"
import socket from "../util/socket"; import socket, {emit} from "../util/socket";
import "../css/lobby.css";
import beer1 from "../img/beer1.png"
const Lobby = () => { const Lobby = () => {
useEffect(() => { const [lobbyId, setLobbyId] = useState<number | undefined>(undefined);
socket.on("SENDING_NEW_TIME", (data: string) => { const [isLeader, setIsLeader] = useState(false);
const [userCount, setUserCount] = useState(0);
}); async function onChangeLobbyInput(i: any) {
setLobbyId(i);
const result: any = await emit('join_lobby', i);
setIsLeader(socket.id === result.lobby.leaderId);
setUserCount(result.lobby.users?.length || 0);
}
useEffect(() => {
socket.on('welcome', async (obj: any) => {
setLobbyId(obj.lobby.name);
setIsLeader(socket.id === obj.lobby.leaderId);
setUserCount(obj.lobby.users?.length || 0);
});
return () => { return () => {
socket.off("SENDING_NEW_TIME"); socket.off("welcome");
} }
}); });
useEffect(() => {
async function wrapper() {
const result: any = await emit('lobby_info');
setIsLeader(socket.id === result.lobby.leaderId);
setUserCount(result.lobby.users?.length || 0);
}
wrapper();
}, []);
return ( return (
<Col className="sider" span={4} offset={10}> <div className="lobby">
<h1>Centurion!</h1> <Row>
</Col> <Col span={24}>
<h1>Centurion! <img src={beer1} className="beer" alt="beer"/></h1>
</Col>
</Row>
<Row>
<Col className="hints" span={24}>
<div>Honderd minuten...</div>
<div>Honderd shots...</div>
<div>Kun jij het aan?</div>
</Col>
</Row>
<Row>
<Col className="control" span={8} offset={8}>
<Card title={`Lobby setup (${lobbyId}):`} actions={ isLeader ? [
<span>Start</span>,
]: []}>
<span>
Huidige lobby <InputNumber size="small" min={100} max={100000} value={lobbyId}
onChange={onChangeLobbyInput}/>
</span>
<p>Er zijn {userCount} gebruiker(s) aanwezig.</p>
<p> {isLeader ? 'Jij bent de baas.' : 'Wachtend op de baas...'}</p>
</Card>
</Col>
</Row>
</div>
); );
}; };

@ -0,0 +1,16 @@
h1 {
font-size: 3.5rem;
text-align: center;
min-height: inherit;
}
.hints {
font-size: 2rem;
text-align: center;
}
.control {
font-size: 1.3rem;
margin-top: 10em;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

@ -10,14 +10,21 @@ export default socket;
* @param arg * @param arg
* @param callback * @param callback
*/ */
export function emit(event: string, arg: any) { export function emit(event: string, arg: any = null) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
socket.emit(event, arg, (err: any, res: any) => { const cb = (err: any, res: any) => {
if (err) { if (err) {
return reject(err); return reject(err);
} }
resolve(res); resolve(res);
}) };
if (arg) {
socket.emit(event, arg, cb);
} else {
socket.emit(event, cb);
}
}) })
} }
Loading…
Cancel
Save