Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 30.88 KB | None | 0 0
  1. import io from "socket.io-client";
  2. import axios from 'axios';
  3.  
  4. class Guesser extends React.Component {
  5.  
  6. constructor() {
  7. super()
  8.  
  9.  
  10. // PLAYERS INICIALS FROM GAME
  11. var players = [];
  12. for (var i = 0; i < window.drupalSettings.players.length; i++) {
  13. var player = {};
  14. player['username'] = window.drupalSettings.players[i];
  15. player['online'] = false;
  16. player['guessed'] = false;
  17. player['points'] = 0;
  18. player['painter'] = false;
  19. players.push(player);
  20. }
  21.  
  22. this.state = {
  23. wordPos: window.drupalSettings.words.length,
  24. currentUser: window.drupalSettings.username,
  25. currentUserPosition: window.drupalSettings.currentUserPos,
  26. currentUserRound: 0,
  27. time: window.drupalSettings.time,
  28. manager: window.drupalSettings.manager,
  29. showStart: true,
  30. hits: 0,
  31. fails: 0,
  32. points: 0,
  33. guessed: 'nostarted',
  34. messages: [],
  35. submitChat: true,
  36. chivato: '',
  37. players: players,
  38. playersOnlinArr: players,
  39. playersOnline: 0,
  40. gameState: true,
  41. wordForPainter: false,
  42. diferencia: 0,
  43. rondaNum: 1,
  44. rondaMax: window.drupalSettings.words.length,
  45. title: window.drupalSettings.title,
  46. }
  47. this.timer = 0;
  48. this.startGame = this.startGame.bind(this);
  49. this.currentIsPainter = this.currentIsPainter.bind(this);
  50. this.replaceAt = this.replaceAt.bind(this);
  51. this.multipleOf = this.multipleOf.bind(this);
  52. this.generateRandom = this.generateRandom.bind(this);
  53. this.initGame = this.initGame.bind(this);
  54. this.tick = this.tick.bind(this);
  55.  
  56. this.socket = io('dibujantes.local:8099');
  57.  
  58.  
  59. /// CHAT
  60. this.socket.on('RECEIVE_MESSAGE', function (data) {
  61. addMessage(data);
  62. });
  63.  
  64. let addMessage = data => {
  65. this.setState({messages: [...this.state.messages, data]});
  66. };
  67.  
  68.  
  69. /// SCOREBOARD
  70. this.socket.on('RECEIVE_SCOREBOARD', function (data) {
  71. addPlayerScore(data);
  72. });
  73.  
  74. let addPlayerScore = data => {
  75. let playersStats = JSON.parse(JSON.stringify(this.state.playersOnlinArr))
  76. playersStats[data['user']].points = data['points'];
  77.  
  78. this.setState({
  79. playersOnlinArr: playersStats,
  80. })
  81. };
  82.  
  83. /// Users online
  84. this.socket.on('ONLINE', function (data) {
  85. userConnected(data);
  86. });
  87.  
  88. let userConnected = data => {
  89. let playersStats = JSON.parse(JSON.stringify(this.state.players))
  90. playersStats[data['user']].online = data['online']
  91.  
  92. this.setState({
  93. players: playersStats,
  94. }, function () {
  95. })
  96. };
  97.  
  98. // Change round
  99. this.socket.on('ROUND', function (data) {
  100. changeRound(data);
  101. });
  102.  
  103. let changeRound = data => {
  104. let playersOnline = this.state.players.filter(player => player.online === true);
  105. let playersStats = JSON.parse(JSON.stringify(playersOnline))
  106. playersStats[data['user']].painter = true
  107.  
  108. this.setState({
  109. playersOnlinArr: playersStats,
  110. playersOnline: playersOnline.length,
  111. currentUserRound: playersOnline.length,
  112. }, function () {
  113. })
  114. };
  115.  
  116. // Guessed round
  117. this.socket.on('GUESSED', function (data) {
  118. guessedRound(data);
  119. });
  120.  
  121. let guessedRound = data => {
  122. let playersStats = JSON.parse(JSON.stringify(this.state.playersOnlinArr))
  123. playersStats[data['user']].guessed = true
  124. this.setState({
  125. playersOnlinArr: playersStats,
  126. }, function () {
  127. })
  128. };
  129.  
  130.  
  131. /// STARTGAME
  132. this.socket.on("START_ON", function (data) {
  133. start(data);
  134. });
  135.  
  136. let start = data => {
  137.  
  138.  
  139. this.setState({
  140. showStart: false,
  141. })
  142. };
  143.  
  144. }
  145.  
  146. // Es crida al carregarse la pagina
  147. componentDidMount = (e) => {
  148.  
  149. this.setupBeforeUnloadListener();
  150.  
  151. if (this.state.showStart) {
  152. setInterval(() => {
  153. this.socket.emit('SEND_ONLINE', {
  154. user: this.state.currentUserPosition,
  155. online: true,
  156. })
  157. }, 2800)
  158. }
  159. }
  160.  
  161. doSomethingBeforeUnload = () => {
  162. this.socket.emit('SEND_ONLINE', {
  163. user: this.state.currentUserPosition,
  164. online: false,
  165. })
  166. }
  167.  
  168. // Setup the `beforeunload` event listener
  169. setupBeforeUnloadListener = () => {
  170. window.addEventListener("beforeunload", () => {
  171. return this.doSomethingBeforeUnload();
  172. });
  173. };
  174.  
  175. startGame() {
  176. // Mirem quans users online hi ha
  177. let playersOnline = this.state.players.filter(player => player.online === true);
  178.  
  179.  
  180. this.setState({
  181. showStart: false,
  182. playersOnline: playersOnline.length,
  183. chivato: '_'.repeat(window.drupalSettings.words[this.state.wordPos - 1].length)
  184. }, function () {
  185. this.socket.emit('START', {
  186. showStart: false,
  187. }),
  188. this.socket.emit('SEND_ROUND', {
  189. user: this.state.playersOnline - 1,
  190. currentUserRound: playersOnline.length,
  191. })
  192. },
  193. )
  194.  
  195.  
  196. var postData = {
  197. game: window.drupalSettings.id,
  198. };
  199.  
  200. let axiosConfig = {
  201. headers: {
  202. 'Content-Type': 'application/json;charset=UTF-8',
  203. "Access-Control-Allow-Origin": "*",
  204. }
  205. };
  206.  
  207. // axios.post('/live-game', postData, axiosConfig)
  208.  
  209. }
  210.  
  211.  
  212. initGame() {
  213. let playersOnline = this.state.players.filter(player => player.online === true);
  214. if (this.state.showStart === false) {
  215. if (this.timer == 0 && this.state.time > 0) {
  216. this.timer = setInterval(
  217. () => this.tick(),
  218. 1000,
  219. );
  220. }
  221. }
  222. }
  223.  
  224. // Genera un input random entre 0 i el length de la paraula
  225. generateRandom() {
  226. return Math.floor(Math.random() * (window.drupalSettings.words[this.state.wordPos - 1].length - 0 + 1) + 0);
  227. }
  228.  
  229. // Multiple de 5 per executarho cada 5 segons
  230. multipleOf(value, multiple) {
  231. let calc = value % multiple;
  232. if (calc == 0) {
  233. return true;
  234. }
  235. }
  236.  
  237. // Donat un string fes replace en un index pel caracter passat per parametre
  238. replaceAt(str, index, chr) {
  239. if (index > str.length - 1) {
  240. return str;
  241. }
  242. return str.substr(0, index) + chr + str.substr(index + 1);
  243. }
  244.  
  245. // Comprova q l'usuari es el pintador o no
  246. currentIsPainter() {
  247. let wordForPainter = true
  248. let userPainting = this.state.playersOnlinArr.filter(player => player.painter === true);
  249. if (userPainting.length > 0) {
  250. if (window.drupalSettings.username == userPainting[0].username) {
  251. return true
  252. }
  253. }
  254.  
  255. return false
  256. }
  257.  
  258. tick() {
  259. let guessed = this.state.guessed;
  260. let seconds = this.state.time - 1;
  261. let random = this.generateRandom();
  262. let painter = this.currentIsPainter();
  263. let roundNum = 0;
  264.  
  265.  
  266. if (this.multipleOf(seconds, 5)) {
  267. let newWord = this.replaceAt(this.state.chivato, random, window.drupalSettings.words[this.state.wordPos - 1][random])
  268. this.setState({chivato: newWord});
  269. }
  270.  
  271. // aixo es el contador q va restan cada segon
  272. this.setState({
  273. time: seconds,
  274. wordForPainter: painter,
  275. });
  276.  
  277. let playersGuessed = this.state.playersOnlinArr.filter(player => player.guessed === true);
  278. let playersOnline = this.state.playersOnlinArr.filter(player => player.online === true);
  279.  
  280.  
  281. if (playersOnline.length - playersGuessed.length == 1) {
  282. let playersStats = JSON.parse(JSON.stringify(this.state.playersOnlinArr))
  283. for (var i = 0; i < this.state.playersOnlinArr.length; i++) {
  284. playersStats[i].guessed = false
  285. }
  286. let painter = this.currentIsPainter();
  287.  
  288. if (this.state.currentUserRound >= 2) {
  289. playersStats[this.state.currentUserRound - 2].painter = true
  290. playersStats[this.state.currentUserRound - 1].painter = false
  291. }
  292.  
  293. if (this.state.currentUserRound == 1) {
  294. playersStats[this.state.playersOnlinArr.length - 1].painter = true
  295. playersStats[0].painter = false
  296.  
  297. }
  298.  
  299. if (window.drupalSettings.words[this.state.wordPos - 2]) {
  300. chivato = window.drupalSettings.words[this.state.wordPos - 2].length
  301. }
  302.  
  303. if (this.state.rondaNum < window.drupalSettings.words.length) {
  304. roundNum = this.state.rondaNum + 1
  305. }
  306. if (this.state.rondaNum == window.drupalSettings.words.length) {
  307. roundNum = window.drupalSettings.words.length
  308. }
  309.  
  310. this.setState({
  311. wordPos: this.state.wordPos - 1,
  312. time: window.drupalSettings.time,
  313. currentUserRound: this.state.currentUserRound - 1,
  314. submitChat: true,
  315. chivato: '_'.repeat(chivato),
  316. playersOnlinArr: playersStats,
  317. wordForPainter: painter,
  318. rondaNum: roundNum,
  319. }, function () {
  320. if (this.state.wordPos == 0) {
  321. for (var i = 0; i < this.state.playersOnlinArr.length; i++) {
  322. playersStats[i].painter = false
  323. playersStats[i].guessed = false
  324. }
  325. }
  326. })
  327.  
  328. if (this.state.wordPos == 0) {
  329. this.setState({chivato: 'The end'})
  330. var postData = {
  331. game: window.drupalSettings.id,
  332. };
  333.  
  334. let axiosConfig = {
  335. headers: {
  336. 'Content-Type': 'application/json;charset=UTF-8',
  337. "Access-Control-Allow-Origin": "*",
  338. }
  339. };
  340.  
  341. // axios.post('/finish-game', postData, axiosConfig)
  342. clearInterval(this.timer);
  343. }
  344. }
  345.  
  346. if (seconds == 0) {
  347. let chivato = 0
  348. let playersStats = JSON.parse(JSON.stringify(this.state.playersOnlinArr))
  349. for (var i = 0; i < this.state.playersOnlinArr.length; i++) {
  350. playersStats[i].guessed = false
  351. }
  352. let painter = this.currentIsPainter();
  353. let restart = this.state.currentUserRound - 1
  354.  
  355. if (this.state.currentUserRound >= 2) {
  356. playersStats[this.state.currentUserRound - 2].painter = true
  357. playersStats[this.state.currentUserRound - 1].painter = false
  358. }
  359.  
  360.  
  361. if (this.state.currentUserRound == 1) {
  362. playersStats[this.state.playersOnlinArr.length - 1].painter = true
  363. playersStats[0].painter = false
  364. restart = this.state.playersOnlinArr.length
  365. }
  366. if (window.drupalSettings.words[this.state.wordPos - 2]) {
  367. chivato = window.drupalSettings.words[this.state.wordPos - 2].length
  368. }
  369.  
  370. if (this.state.rondaNum < window.drupalSettings.words.length) {
  371. roundNum = this.state.rondaNum + 1
  372. }
  373. if (this.state.rondaNum == window.drupalSettings.words.length) {
  374. roundNum = window.drupalSettings.words.length
  375. }
  376.  
  377. this.setState({
  378. wordPos: this.state.wordPos - 1,
  379. time: window.drupalSettings.time,
  380. currentUserRound: restart,
  381. submitChat: true,
  382. chivato: '_'.repeat(chivato),
  383. wordForPainter: false,
  384. playersOnlinArr: playersStats,
  385. rondaNum: roundNum,
  386. }, function () {
  387. if (this.state.wordPos == 0) {
  388. for (var i = 0; i < this.state.playersOnlinArr.length; i++) {
  389. playersStats[i].painter = false
  390. playersStats[i].guessed = false
  391. }
  392. }
  393. }
  394. )
  395. if (this.state.wordPos == 0) {
  396. this.setState({chivato: 'The end'})
  397. var postData = {
  398. game: window.drupalSettings.id,
  399. };
  400.  
  401. let axiosConfig = {
  402. headers: {
  403. 'Content-Type': 'application/json;charset=UTF-8',
  404. "Access-Control-Allow-Origin": "*",
  405. }
  406. };
  407.  
  408. // axios.post('/finish-game', postData, axiosConfig)
  409.  
  410. clearInterval(this.timer);
  411. }
  412. }
  413.  
  414. // Hotfix to avoid to display the word for all the painters.
  415. if (seconds == window.drupalSettings.time) {
  416. this.setState({
  417. wordForPainter: painter,
  418. })
  419. }
  420.  
  421.  
  422. }
  423.  
  424. checkWord = (e) => {
  425. e.preventDefault()
  426. let word = this.inputWord.value
  427.  
  428.  
  429. // Agafa l'index del current user en l'array d'online. S'hauria de passar a function per reuse.
  430. let indexOfCurrentOnOnlinyPlayers = this.state.playersOnlinArr.findIndex(function (e) {
  431. return e.username == window.drupalSettings.username;
  432. })
  433.  
  434. if (word == window.drupalSettings.words[this.state.wordPos - 1]) {
  435. let playersStats = JSON.parse(JSON.stringify(this.state.playersOnlinArr))
  436. playersStats[this.state.currentUserPosition].points = this.state.points + 30;
  437. this.setState({
  438. points: this.state.points + 30,
  439. guessed: 'guessed',
  440. hits: this.state.hits + 1,
  441. players: playersStats,
  442. submitChat: false,
  443. }, function () {
  444. this.socket.emit('SEND_MESSAGE', {
  445. author: this.state.currentUser,
  446. word: 'Guessed the word',
  447. points: this.state.points,
  448. encertada: 'green',
  449. }),
  450.  
  451. this.socket.emit('SEND_SCOREBOARD', {
  452. user: indexOfCurrentOnOnlinyPlayers,
  453. points: this.state.points,
  454. }),
  455.  
  456. this.socket.emit('GUESSED_ROUND', {
  457. user: indexOfCurrentOnOnlinyPlayers,
  458. guessed: 'guessed',
  459. })
  460.  
  461. var postData = {
  462. author: this.state.currentUser,
  463. points: this.state.points,
  464. game: window.drupalSettings.id,
  465. word: word,
  466. guessed: 'guessed',
  467. };
  468.  
  469.  
  470. let axiosConfig = {
  471. headers: {
  472. 'Content-Type': 'application/json;charset=UTF-8',
  473. "Access-Control-Allow-Origin": "*",
  474. }
  475. };
  476. if (this.inputWord !== null) {
  477. this.inputWord.value = ''
  478. }
  479. // axios.post('/save-user', postData, axiosConfig)
  480. }
  481. )
  482.  
  483. }
  484. else {
  485. this.setState({
  486. guessed: 'failed',
  487. fails: this.state.fails + 1,
  488. }, function () {
  489. this.socket.emit('SEND_MESSAGE', {
  490. author: this.state.currentUser,
  491. word: this.inputWord.value,
  492. points: this.state.points,
  493. })
  494. var postData = {
  495. author: this.state.currentUser,
  496. points: this.state.points,
  497. game: window.drupalSettings.id,
  498. word: this.inputWord.value,
  499. guessed: 'failed',
  500. };
  501.  
  502. let axiosConfig = {
  503. headers: {
  504. 'Content-Type': 'application/json;charset=UTF-8',
  505. "Access-Control-Allow-Origin": "*",
  506. }
  507. };
  508. if (this.inputWord.value) {
  509. this.inputWord.value = ''
  510. }
  511. // axios.post('/save-user', postData, axiosConfig)
  512. }
  513. )
  514.  
  515. }
  516. }
  517.  
  518.  
  519. render() {
  520. let isManager = this.state.manager;
  521. let started = this.state.showStart;
  522. let wordForPainter = this.currentIsPainter();
  523.  
  524. if (started) {
  525.  
  526. if (isManager) {
  527. return (
  528. <div className="row">
  529. <div className="col-4 h-100 left"></div>
  530. <div className="col-4 h-100 mid">
  531. <button className="start-game"
  532. onClick={this.startGame}>Start game
  533. </button>
  534. </div>
  535.  
  536. <div className="col-4 h-100 right">
  537. <div className="logo h-20"><img
  538. src="/themes/custom/dibujantes/image/logo.png"/>
  539. </div>
  540. <div className="row lobby h-25">
  541. {/*Users online*/}
  542. <div className="lobby-wrapper">
  543. <div
  544. className="scoreboard">{this.state.title}</div>
  545. </div>
  546. {Object.keys(this.state.players)
  547. .filter(key => this.state.players[key].online === true)
  548. .map((key, index) => {
  549. return <div key={key}>
  550. <div className="online-wrapper">
  551. <div
  552. className="usersonline">{this.state.players[key].username}</div>
  553. </div>
  554. </div>
  555. })}
  556. </div>
  557. <div className="row chat h-60">
  558. <div className="chat-zone">
  559. {this.state.messages.map((message, i) => {
  560. return (
  561. <div key={i}>
  562. <span>{message.author}</span> : <span
  563. className={message.encertada}> {message.word} </span>
  564. </div>
  565. )
  566. })}
  567. </div>
  568. <div className="container-submit">
  569. <form className="submit"
  570. onSubmit={this.checkWord}>
  571. <div>
  572. <div className="input">
  573. <input className="careful"
  574. id='word'
  575. name='word'
  576. ref={inputElement => this.inputWord = inputElement}
  577. />
  578. < button
  579. className='btn btn-secondary enter'>ENTER
  580. </button>
  581. </div>
  582. </div>
  583. </form>
  584. </div>
  585. </div>
  586. </div>
  587. </div>
  588.  
  589.  
  590. );
  591. }
  592. else {
  593. return (
  594. <div className="row">
  595. <div className="col-4 h-100 left"></div>
  596. <div className="col-4 h-100 tete">
  597. <span>Waiting for owner to start the game...</span>
  598. </div>
  599.  
  600. <div className="col-4 h-100 right">
  601. <div className="logo h-20"><img
  602. src="/themes/custom/dibujantes/image/logo.png"/>
  603. </div>
  604. <div className="row lobby h-25">
  605. {/*Users online*/}
  606. <div className="lobby-wrapper">
  607. <div
  608. className="scoreboard">{this.state.title}</div>
  609. </div>
  610. {Object.keys(this.state.players)
  611. .filter(key => this.state.players[key].online === true)
  612. .map((key, index) => {
  613. return <div key={key}>
  614. <div className="online-wrapper">
  615. <div
  616. className="usersonline">{this.state.players[key].username}</div>
  617. </div>
  618. </div>
  619. })}
  620. </div>
  621. <div className="row chat h-60">
  622. <div className="chat-zone">
  623. {this.state.messages.map((message, i) => {
  624. return (
  625. <div key={i}>
  626. <span>{message.author}</span> : <span
  627. className={message.encertada}> {message.word} </span>
  628. </div>
  629. )
  630. })}
  631. </div>
  632. <div className="container-submit">
  633. <form className="submit"
  634. onSubmit={this.checkWord}>
  635. <div>
  636. <div className="input">
  637. <input className="careful"
  638. id='word'
  639. name='word'
  640. ref={inputElement => this.inputWord = inputElement}
  641. />
  642. < button
  643. className='btn btn-secondary enter'>ENTER
  644. </button>
  645. </div>
  646. </div>
  647. </form>
  648. </div>
  649. </div>
  650. </div>
  651. </div>
  652. );
  653. }
  654. }
  655. else {
  656.  
  657. return (
  658. <div className="row">
  659. <div className="col-1 h-100 left">
  660. </div>
  661. <div className="col-8 h-100 mid">
  662. <div className="row h-20">
  663. <div className="col-3 roundtime">
  664. <h4>Round {this.state.rondaNum}/{this.state.rondaMax}</h4>
  665. <h5><p>{this.state.time}</p></h5>
  666. </div>
  667. <div className="col-3 whopaints">
  668. {Object.keys(this.state.playersOnlinArr)
  669. .filter(key => this.state.playersOnlinArr[key].painter === true)
  670. .filter(key => this.state.playersOnlinArr[key].online === true)
  671. .map((key, index) => {
  672. return <div key={key}>
  673. <h4>Currently Drawing</h4>
  674. <p>{this.state.playersOnlinArr[key].username}</p>
  675. </div>
  676. })}
  677. </div>
  678. <div className="col-3 parauleta">
  679. <h4>{this.state.wordForPainter ? window.drupalSettings.words[this.state.wordPos - 1] : ''}</h4>
  680. </div>
  681. <div className="col-3 hint">
  682. <div>{this.state.chivato}</div>
  683. </div>
  684. </div>
  685. <div className="canvas row h-85">
  686. </div>
  687.  
  688.  
  689. </div>
  690. <div className="col-3 h-100 right">
  691. <div className="logo h-20"><img
  692. src="/themes/custom/dibujantes/image/logo.png"/>
  693. </div>
  694. <div className="row lobby h-25">
  695. {/*Users online*/}
  696. <div className="lobby-wrapper">
  697.  
  698. <div
  699. className="scoreboard">{this.state.title}</div>
  700. <div className="points">POINTS</div>
  701. </div>
  702. {Object.keys(this.state.playersOnlinArr)
  703. .filter(key => this.state.playersOnlinArr[key].online === true)
  704. .map((key, index) => {
  705. return <div key={key}>
  706. <div className="online-wrapper">
  707. <div
  708. className="usersonline">{this.state.playersOnlinArr[key].username}</div>
  709. <div
  710. className="pointsonline">{this.state.playersOnlinArr[key].points}</div>
  711. </div>
  712. </div>
  713. })}
  714. </div>
  715. <div className="row chat h-60">
  716. <div className="chat-zone">
  717. {this.state.messages.map((message, i) => {
  718. return (
  719. <div key={i}>
  720. <span>{message.author}</span> : <span
  721. className={message.encertada}> {message.word} </span>
  722. </div>
  723. )
  724. })}
  725. </div>
  726. <div className="container-submit">
  727. <form className="submit"
  728. onSubmit={this.checkWord}>
  729. {this.state.submitChat ?
  730. <div>
  731. {this.state.wordForPainter
  732. ?
  733. <div className="guessed-word">
  734. <p>Your painting turn</p>
  735. </div>
  736. :
  737. <div className="input">
  738. <input className="careful"
  739. id='word'
  740. name='word'
  741. ref={inputElement => this.inputWord = inputElement}
  742. />
  743. < button
  744. className='btn btn-secondary enter'>ENTER
  745. </button>
  746. </div>
  747. }
  748. </div>
  749. :
  750. <div className="guessed-word">
  751. <p> You already guessed word.</p>
  752. </div>
  753. }
  754. </form>
  755. </div>
  756. </div>
  757. </div>
  758.  
  759.  
  760. <div>
  761. </div>
  762. {this.state.showStart
  763. ? <button onClick={this.startGame}>Start game</button>
  764. : <div>
  765. {this.initGame()}
  766. </div>
  767. }
  768. </div>
  769. )
  770. }
  771. }
  772. }
  773.  
  774. ReactDOM.render(<Guesser/>,
  775. document.getElementById("guessermultiple"));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement