Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import io from "socket.io-client";
- import axios from 'axios';
- class Guesser extends React.Component {
- constructor() {
- super()
- // PLAYERS INICIALS FROM GAME
- var players = [];
- for (var i = 0; i < window.drupalSettings.players.length; i++) {
- var player = {};
- player['username'] = window.drupalSettings.players[i];
- player['online'] = false;
- player['guessed'] = false;
- player['points'] = 0;
- player['painter'] = false;
- players.push(player);
- }
- this.state = {
- wordPos: window.drupalSettings.words.length,
- currentUser: window.drupalSettings.username,
- currentUserPosition: window.drupalSettings.currentUserPos,
- currentUserRound: 0,
- time: window.drupalSettings.time,
- manager: window.drupalSettings.manager,
- showStart: true,
- hits: 0,
- fails: 0,
- points: 0,
- guessed: 'nostarted',
- messages: [],
- submitChat: true,
- chivato: '',
- players: players,
- playersOnlinArr: players,
- playersOnline: 0,
- gameState: true,
- wordForPainter: false,
- diferencia: 0,
- rondaNum: 1,
- rondaMax: window.drupalSettings.words.length,
- title: window.drupalSettings.title,
- }
- this.timer = 0;
- this.startGame = this.startGame.bind(this);
- this.currentIsPainter = this.currentIsPainter.bind(this);
- this.replaceAt = this.replaceAt.bind(this);
- this.multipleOf = this.multipleOf.bind(this);
- this.generateRandom = this.generateRandom.bind(this);
- this.initGame = this.initGame.bind(this);
- this.tick = this.tick.bind(this);
- this.socket = io('dibujantes.local:8099');
- /// CHAT
- this.socket.on('RECEIVE_MESSAGE', function (data) {
- addMessage(data);
- });
- let addMessage = data => {
- this.setState({messages: [...this.state.messages, data]});
- };
- /// SCOREBOARD
- this.socket.on('RECEIVE_SCOREBOARD', function (data) {
- addPlayerScore(data);
- });
- let addPlayerScore = data => {
- let playersStats = JSON.parse(JSON.stringify(this.state.playersOnlinArr))
- playersStats[data['user']].points = data['points'];
- this.setState({
- playersOnlinArr: playersStats,
- })
- };
- /// Users online
- this.socket.on('ONLINE', function (data) {
- userConnected(data);
- });
- let userConnected = data => {
- let playersStats = JSON.parse(JSON.stringify(this.state.players))
- playersStats[data['user']].online = data['online']
- this.setState({
- players: playersStats,
- }, function () {
- })
- };
- // Change round
- this.socket.on('ROUND', function (data) {
- changeRound(data);
- });
- let changeRound = data => {
- let playersOnline = this.state.players.filter(player => player.online === true);
- let playersStats = JSON.parse(JSON.stringify(playersOnline))
- playersStats[data['user']].painter = true
- this.setState({
- playersOnlinArr: playersStats,
- playersOnline: playersOnline.length,
- currentUserRound: playersOnline.length,
- }, function () {
- })
- };
- // Guessed round
- this.socket.on('GUESSED', function (data) {
- guessedRound(data);
- });
- let guessedRound = data => {
- let playersStats = JSON.parse(JSON.stringify(this.state.playersOnlinArr))
- playersStats[data['user']].guessed = true
- this.setState({
- playersOnlinArr: playersStats,
- }, function () {
- })
- };
- /// STARTGAME
- this.socket.on("START_ON", function (data) {
- start(data);
- });
- let start = data => {
- this.setState({
- showStart: false,
- })
- };
- }
- // Es crida al carregarse la pagina
- componentDidMount = (e) => {
- this.setupBeforeUnloadListener();
- if (this.state.showStart) {
- setInterval(() => {
- this.socket.emit('SEND_ONLINE', {
- user: this.state.currentUserPosition,
- online: true,
- })
- }, 2800)
- }
- }
- doSomethingBeforeUnload = () => {
- this.socket.emit('SEND_ONLINE', {
- user: this.state.currentUserPosition,
- online: false,
- })
- }
- // Setup the `beforeunload` event listener
- setupBeforeUnloadListener = () => {
- window.addEventListener("beforeunload", () => {
- return this.doSomethingBeforeUnload();
- });
- };
- startGame() {
- // Mirem quans users online hi ha
- let playersOnline = this.state.players.filter(player => player.online === true);
- this.setState({
- showStart: false,
- playersOnline: playersOnline.length,
- chivato: '_'.repeat(window.drupalSettings.words[this.state.wordPos - 1].length)
- }, function () {
- this.socket.emit('START', {
- showStart: false,
- }),
- this.socket.emit('SEND_ROUND', {
- user: this.state.playersOnline - 1,
- currentUserRound: playersOnline.length,
- })
- },
- )
- var postData = {
- game: window.drupalSettings.id,
- };
- let axiosConfig = {
- headers: {
- 'Content-Type': 'application/json;charset=UTF-8',
- "Access-Control-Allow-Origin": "*",
- }
- };
- // axios.post('/live-game', postData, axiosConfig)
- }
- initGame() {
- let playersOnline = this.state.players.filter(player => player.online === true);
- if (this.state.showStart === false) {
- if (this.timer == 0 && this.state.time > 0) {
- this.timer = setInterval(
- () => this.tick(),
- 1000,
- );
- }
- }
- }
- // Genera un input random entre 0 i el length de la paraula
- generateRandom() {
- return Math.floor(Math.random() * (window.drupalSettings.words[this.state.wordPos - 1].length - 0 + 1) + 0);
- }
- // Multiple de 5 per executarho cada 5 segons
- multipleOf(value, multiple) {
- let calc = value % multiple;
- if (calc == 0) {
- return true;
- }
- }
- // Donat un string fes replace en un index pel caracter passat per parametre
- replaceAt(str, index, chr) {
- if (index > str.length - 1) {
- return str;
- }
- return str.substr(0, index) + chr + str.substr(index + 1);
- }
- // Comprova q l'usuari es el pintador o no
- currentIsPainter() {
- let wordForPainter = true
- let userPainting = this.state.playersOnlinArr.filter(player => player.painter === true);
- if (userPainting.length > 0) {
- if (window.drupalSettings.username == userPainting[0].username) {
- return true
- }
- }
- return false
- }
- tick() {
- let guessed = this.state.guessed;
- let seconds = this.state.time - 1;
- let random = this.generateRandom();
- let painter = this.currentIsPainter();
- let roundNum = 0;
- if (this.multipleOf(seconds, 5)) {
- let newWord = this.replaceAt(this.state.chivato, random, window.drupalSettings.words[this.state.wordPos - 1][random])
- this.setState({chivato: newWord});
- }
- // aixo es el contador q va restan cada segon
- this.setState({
- time: seconds,
- wordForPainter: painter,
- });
- let playersGuessed = this.state.playersOnlinArr.filter(player => player.guessed === true);
- let playersOnline = this.state.playersOnlinArr.filter(player => player.online === true);
- if (playersOnline.length - playersGuessed.length == 1) {
- let playersStats = JSON.parse(JSON.stringify(this.state.playersOnlinArr))
- for (var i = 0; i < this.state.playersOnlinArr.length; i++) {
- playersStats[i].guessed = false
- }
- let painter = this.currentIsPainter();
- if (this.state.currentUserRound >= 2) {
- playersStats[this.state.currentUserRound - 2].painter = true
- playersStats[this.state.currentUserRound - 1].painter = false
- }
- if (this.state.currentUserRound == 1) {
- playersStats[this.state.playersOnlinArr.length - 1].painter = true
- playersStats[0].painter = false
- }
- if (window.drupalSettings.words[this.state.wordPos - 2]) {
- chivato = window.drupalSettings.words[this.state.wordPos - 2].length
- }
- if (this.state.rondaNum < window.drupalSettings.words.length) {
- roundNum = this.state.rondaNum + 1
- }
- if (this.state.rondaNum == window.drupalSettings.words.length) {
- roundNum = window.drupalSettings.words.length
- }
- this.setState({
- wordPos: this.state.wordPos - 1,
- time: window.drupalSettings.time,
- currentUserRound: this.state.currentUserRound - 1,
- submitChat: true,
- chivato: '_'.repeat(chivato),
- playersOnlinArr: playersStats,
- wordForPainter: painter,
- rondaNum: roundNum,
- }, function () {
- if (this.state.wordPos == 0) {
- for (var i = 0; i < this.state.playersOnlinArr.length; i++) {
- playersStats[i].painter = false
- playersStats[i].guessed = false
- }
- }
- })
- if (this.state.wordPos == 0) {
- this.setState({chivato: 'The end'})
- var postData = {
- game: window.drupalSettings.id,
- };
- let axiosConfig = {
- headers: {
- 'Content-Type': 'application/json;charset=UTF-8',
- "Access-Control-Allow-Origin": "*",
- }
- };
- // axios.post('/finish-game', postData, axiosConfig)
- clearInterval(this.timer);
- }
- }
- if (seconds == 0) {
- let chivato = 0
- let playersStats = JSON.parse(JSON.stringify(this.state.playersOnlinArr))
- for (var i = 0; i < this.state.playersOnlinArr.length; i++) {
- playersStats[i].guessed = false
- }
- let painter = this.currentIsPainter();
- let restart = this.state.currentUserRound - 1
- if (this.state.currentUserRound >= 2) {
- playersStats[this.state.currentUserRound - 2].painter = true
- playersStats[this.state.currentUserRound - 1].painter = false
- }
- if (this.state.currentUserRound == 1) {
- playersStats[this.state.playersOnlinArr.length - 1].painter = true
- playersStats[0].painter = false
- restart = this.state.playersOnlinArr.length
- }
- if (window.drupalSettings.words[this.state.wordPos - 2]) {
- chivato = window.drupalSettings.words[this.state.wordPos - 2].length
- }
- if (this.state.rondaNum < window.drupalSettings.words.length) {
- roundNum = this.state.rondaNum + 1
- }
- if (this.state.rondaNum == window.drupalSettings.words.length) {
- roundNum = window.drupalSettings.words.length
- }
- this.setState({
- wordPos: this.state.wordPos - 1,
- time: window.drupalSettings.time,
- currentUserRound: restart,
- submitChat: true,
- chivato: '_'.repeat(chivato),
- wordForPainter: false,
- playersOnlinArr: playersStats,
- rondaNum: roundNum,
- }, function () {
- if (this.state.wordPos == 0) {
- for (var i = 0; i < this.state.playersOnlinArr.length; i++) {
- playersStats[i].painter = false
- playersStats[i].guessed = false
- }
- }
- }
- )
- if (this.state.wordPos == 0) {
- this.setState({chivato: 'The end'})
- var postData = {
- game: window.drupalSettings.id,
- };
- let axiosConfig = {
- headers: {
- 'Content-Type': 'application/json;charset=UTF-8',
- "Access-Control-Allow-Origin": "*",
- }
- };
- // axios.post('/finish-game', postData, axiosConfig)
- clearInterval(this.timer);
- }
- }
- // Hotfix to avoid to display the word for all the painters.
- if (seconds == window.drupalSettings.time) {
- this.setState({
- wordForPainter: painter,
- })
- }
- }
- checkWord = (e) => {
- e.preventDefault()
- let word = this.inputWord.value
- // Agafa l'index del current user en l'array d'online. S'hauria de passar a function per reuse.
- let indexOfCurrentOnOnlinyPlayers = this.state.playersOnlinArr.findIndex(function (e) {
- return e.username == window.drupalSettings.username;
- })
- if (word == window.drupalSettings.words[this.state.wordPos - 1]) {
- let playersStats = JSON.parse(JSON.stringify(this.state.playersOnlinArr))
- playersStats[this.state.currentUserPosition].points = this.state.points + 30;
- this.setState({
- points: this.state.points + 30,
- guessed: 'guessed',
- hits: this.state.hits + 1,
- players: playersStats,
- submitChat: false,
- }, function () {
- this.socket.emit('SEND_MESSAGE', {
- author: this.state.currentUser,
- word: 'Guessed the word',
- points: this.state.points,
- encertada: 'green',
- }),
- this.socket.emit('SEND_SCOREBOARD', {
- user: indexOfCurrentOnOnlinyPlayers,
- points: this.state.points,
- }),
- this.socket.emit('GUESSED_ROUND', {
- user: indexOfCurrentOnOnlinyPlayers,
- guessed: 'guessed',
- })
- var postData = {
- author: this.state.currentUser,
- points: this.state.points,
- game: window.drupalSettings.id,
- word: word,
- guessed: 'guessed',
- };
- let axiosConfig = {
- headers: {
- 'Content-Type': 'application/json;charset=UTF-8',
- "Access-Control-Allow-Origin": "*",
- }
- };
- if (this.inputWord !== null) {
- this.inputWord.value = ''
- }
- // axios.post('/save-user', postData, axiosConfig)
- }
- )
- }
- else {
- this.setState({
- guessed: 'failed',
- fails: this.state.fails + 1,
- }, function () {
- this.socket.emit('SEND_MESSAGE', {
- author: this.state.currentUser,
- word: this.inputWord.value,
- points: this.state.points,
- })
- var postData = {
- author: this.state.currentUser,
- points: this.state.points,
- game: window.drupalSettings.id,
- word: this.inputWord.value,
- guessed: 'failed',
- };
- let axiosConfig = {
- headers: {
- 'Content-Type': 'application/json;charset=UTF-8',
- "Access-Control-Allow-Origin": "*",
- }
- };
- if (this.inputWord.value) {
- this.inputWord.value = ''
- }
- // axios.post('/save-user', postData, axiosConfig)
- }
- )
- }
- }
- render() {
- let isManager = this.state.manager;
- let started = this.state.showStart;
- let wordForPainter = this.currentIsPainter();
- if (started) {
- if (isManager) {
- return (
- <div className="row">
- <div className="col-4 h-100 left"></div>
- <div className="col-4 h-100 mid">
- <button className="start-game"
- onClick={this.startGame}>Start game
- </button>
- </div>
- <div className="col-4 h-100 right">
- <div className="logo h-20"><img
- src="/themes/custom/dibujantes/image/logo.png"/>
- </div>
- <div className="row lobby h-25">
- {/*Users online*/}
- <div className="lobby-wrapper">
- <div
- className="scoreboard">{this.state.title}</div>
- </div>
- {Object.keys(this.state.players)
- .filter(key => this.state.players[key].online === true)
- .map((key, index) => {
- return <div key={key}>
- <div className="online-wrapper">
- <div
- className="usersonline">{this.state.players[key].username}</div>
- </div>
- </div>
- })}
- </div>
- <div className="row chat h-60">
- <div className="chat-zone">
- {this.state.messages.map((message, i) => {
- return (
- <div key={i}>
- <span>{message.author}</span> : <span
- className={message.encertada}> {message.word} </span>
- </div>
- )
- })}
- </div>
- <div className="container-submit">
- <form className="submit"
- onSubmit={this.checkWord}>
- <div>
- <div className="input">
- <input className="careful"
- id='word'
- name='word'
- ref={inputElement => this.inputWord = inputElement}
- />
- < button
- className='btn btn-secondary enter'>ENTER
- </button>
- </div>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- );
- }
- else {
- return (
- <div className="row">
- <div className="col-4 h-100 left"></div>
- <div className="col-4 h-100 tete">
- <span>Waiting for owner to start the game...</span>
- </div>
- <div className="col-4 h-100 right">
- <div className="logo h-20"><img
- src="/themes/custom/dibujantes/image/logo.png"/>
- </div>
- <div className="row lobby h-25">
- {/*Users online*/}
- <div className="lobby-wrapper">
- <div
- className="scoreboard">{this.state.title}</div>
- </div>
- {Object.keys(this.state.players)
- .filter(key => this.state.players[key].online === true)
- .map((key, index) => {
- return <div key={key}>
- <div className="online-wrapper">
- <div
- className="usersonline">{this.state.players[key].username}</div>
- </div>
- </div>
- })}
- </div>
- <div className="row chat h-60">
- <div className="chat-zone">
- {this.state.messages.map((message, i) => {
- return (
- <div key={i}>
- <span>{message.author}</span> : <span
- className={message.encertada}> {message.word} </span>
- </div>
- )
- })}
- </div>
- <div className="container-submit">
- <form className="submit"
- onSubmit={this.checkWord}>
- <div>
- <div className="input">
- <input className="careful"
- id='word'
- name='word'
- ref={inputElement => this.inputWord = inputElement}
- />
- < button
- className='btn btn-secondary enter'>ENTER
- </button>
- </div>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- );
- }
- }
- else {
- return (
- <div className="row">
- <div className="col-1 h-100 left">
- </div>
- <div className="col-8 h-100 mid">
- <div className="row h-20">
- <div className="col-3 roundtime">
- <h4>Round {this.state.rondaNum}/{this.state.rondaMax}</h4>
- <h5><p>{this.state.time}</p></h5>
- </div>
- <div className="col-3 whopaints">
- {Object.keys(this.state.playersOnlinArr)
- .filter(key => this.state.playersOnlinArr[key].painter === true)
- .filter(key => this.state.playersOnlinArr[key].online === true)
- .map((key, index) => {
- return <div key={key}>
- <h4>Currently Drawing</h4>
- <p>{this.state.playersOnlinArr[key].username}</p>
- </div>
- })}
- </div>
- <div className="col-3 parauleta">
- <h4>{this.state.wordForPainter ? window.drupalSettings.words[this.state.wordPos - 1] : ''}</h4>
- </div>
- <div className="col-3 hint">
- <div>{this.state.chivato}</div>
- </div>
- </div>
- <div className="canvas row h-85">
- </div>
- </div>
- <div className="col-3 h-100 right">
- <div className="logo h-20"><img
- src="/themes/custom/dibujantes/image/logo.png"/>
- </div>
- <div className="row lobby h-25">
- {/*Users online*/}
- <div className="lobby-wrapper">
- <div
- className="scoreboard">{this.state.title}</div>
- <div className="points">POINTS</div>
- </div>
- {Object.keys(this.state.playersOnlinArr)
- .filter(key => this.state.playersOnlinArr[key].online === true)
- .map((key, index) => {
- return <div key={key}>
- <div className="online-wrapper">
- <div
- className="usersonline">{this.state.playersOnlinArr[key].username}</div>
- <div
- className="pointsonline">{this.state.playersOnlinArr[key].points}</div>
- </div>
- </div>
- })}
- </div>
- <div className="row chat h-60">
- <div className="chat-zone">
- {this.state.messages.map((message, i) => {
- return (
- <div key={i}>
- <span>{message.author}</span> : <span
- className={message.encertada}> {message.word} </span>
- </div>
- )
- })}
- </div>
- <div className="container-submit">
- <form className="submit"
- onSubmit={this.checkWord}>
- {this.state.submitChat ?
- <div>
- {this.state.wordForPainter
- ?
- <div className="guessed-word">
- <p>Your painting turn</p>
- </div>
- :
- <div className="input">
- <input className="careful"
- id='word'
- name='word'
- ref={inputElement => this.inputWord = inputElement}
- />
- < button
- className='btn btn-secondary enter'>ENTER
- </button>
- </div>
- }
- </div>
- :
- <div className="guessed-word">
- <p> You already guessed word.</p>
- </div>
- }
- </form>
- </div>
- </div>
- </div>
- <div>
- </div>
- {this.state.showStart
- ? <button onClick={this.startGame}>Start game</button>
- : <div>
- {this.initGame()}
- </div>
- }
- </div>
- )
- }
- }
- }
- ReactDOM.render(<Guesser/>,
- document.getElementById("guessermultiple"));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement