SHARE
TWEET

Untitled

a guest Dec 15th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const template = document.createElement('template')
  2. template.innerHTML = `
  3. <style>
  4.   #questionDiv {
  5.     visibility: hidden;
  6.   }
  7. </style>
  8. <div id="highScoreDiv">
  9. <p>Enter your username</p>
  10. <input id="nicknameField" type="text">
  11. <button id="submitButton">Submit</button>
  12. </div>
  13.  
  14. <div id="questionDiv">
  15.   <button id="info">Info</button>
  16.   <br><br><br>
  17.   <button id="startButton">Start</button>
  18.   <br>
  19.   <input id="answerField" type="text">
  20.   <button id="answerButton">Answer</button>
  21.   <div id="altButtons">
  22.   </div>
  23.   <p id="questionTextPTag"></p>
  24.  
  25.   <p id="answerResultPTag"></p>
  26.   <p id="currentScore"></p>
  27.   <p id="currentTime"></p>
  28. </div>
  29. `
  30.  
  31. class QuestionGame extends window.HTMLElement {
  32.   constructor() {
  33.     super()
  34.  
  35.     this.attachShadow({ mode: 'open' })
  36.     this.shadowRoot.appendChild(template.content.cloneNode(true))
  37.  
  38.     this.questionDiv = this.shadowRoot.querySelector('#questionDiv')
  39.     this.highScoreDiv = this.shadowRoot.querySelector('#highScoreDiv')
  40.  
  41.     this.nicknameField = this.shadowRoot.querySelector('#nicknameField')
  42.  
  43.     this.startButton = this.shadowRoot.querySelector('#startButton')
  44.     this.answerButton = this.shadowRoot.querySelector('#answerButton')
  45.     this.answerField = this.shadowRoot.querySelector('#answerField')
  46.     this.submitButton = this.shadowRoot.querySelector('#submitButton')
  47.     this.altButtons = this.shadowRoot.querySelector('#altButtons')
  48.  
  49.     this.infoButton = this.shadowRoot.querySelector('#info')
  50.     this.questionTextPTag = this.shadowRoot.querySelector('#questionTextPTag')
  51.     this.answerTextPTag = this.shadowRoot.querySelector('#answerResultPTag')
  52.  
  53.     this.currentTimePTag = this.shadowRoot.querySelector('#currentTime')
  54.  
  55.     this.startURL = 'http://vhost3.lnu.se:20080/question/1'
  56.     this.nextURL = ''
  57.  
  58.     this.highScoreArray = []
  59.     this.allPlayers = []
  60.  
  61.     this.name = ''
  62.     this.gameState = true
  63.  
  64.     this.score = 0
  65.     this.currentTime = 0
  66.  
  67.     this.parsedResponse = ''
  68.     this.jsonAnswer = ''
  69.  
  70.     this.p = setTimeout(args => { }, 0)
  71.   }
  72.  
  73.   static get observedAttributes() {
  74.     return []
  75.   }
  76.  
  77.   attributesChangedCallback(name, oldValue, newValue) {
  78.  
  79.   }
  80.  
  81.   connectedCallback() {
  82.     // Hides the username div and shows the question div
  83.     this.submitButton.addEventListener('click', event => {
  84.      
  85.       this.name = this.nicknameField.value
  86.       this.highScoreDiv.style.visibility = 'hidden'
  87.       this.questionDiv.style.visibility = 'visible'
  88.       console.log(this.name)
  89.       // this.saveToLocalStorage()
  90.     })
  91.  
  92.     this.infoButton.addEventListener('click', async event => {
  93.       // console.log(this.nextURL)
  94.       // console.log(this.parsedResponse)
  95.       // debugger
  96.       // this.startTimer()
  97.       // this.saveToLocalStorage()
  98.      
  99.       this.saveToLocalStorage()
  100.       // this.getFromlocalStorage()
  101.     })
  102.  
  103.     this.startButton.addEventListener('click', async event => {
  104.       this.resetGame()
  105.       this.startTimer()
  106.       await this.loadQuestion()
  107.       this.p = setTimeout(arg => {
  108.         this.onTimeout()
  109.       }, 7001)
  110.       this.renderQuestion()
  111.     })
  112.  
  113.     this.answerButton.addEventListener('click', async event => {
  114.       console.log(event.target.id)
  115.       this.answerToJson()
  116.       try {
  117.         await this.sendAnswer(this.nextURL, this.jsonAnswer)
  118.         this.score++
  119.       } catch (error) {
  120.         this.onWrongAnswer()
  121.         return
  122.       }
  123.       this.renderScore()
  124.       await this.loadQuestion(this.nextURL)
  125.       clearTimeout(this.p)
  126.       this.p = setTimeout(arg => {
  127.         this.onTimeout()
  128.       }, 7000)
  129.       this.renderQuestion()
  130.       if (this.parsedResponse.alternatives) {
  131.         this.renderAnswerButtons()
  132.         this.hideAnswerField()
  133.         this.showButtons()
  134.       } else {
  135.         this.showAnswerField()
  136.         this.hideButtons()
  137.       }
  138.       this.answerField.value = ''
  139.     })
  140.  
  141.     this.altButtons.addEventListener('click', async event => {
  142.       console.log(event.target.id)
  143.       if (event.target.id === 'alt1' || event.target.id === 'alt2' || event.target.id === 'alt3' || event.target.id === 'alt4') {
  144.         this.answerToJson(event.target.id)
  145.         try {
  146.           await this.sendAnswer(this.nextURL, this.jsonAnswer)
  147.           this.score++
  148.         } catch (error) {
  149.           this.onWrongAnswer()
  150.           return
  151.         }
  152.         this.renderScore()
  153.         await this.loadQuestion(this.nextURL)
  154.         clearTimeout(this.p)
  155.         this.p = setTimeout(arg => {
  156.           this.onTimeout()
  157.         }, 7000)
  158.         this.renderQuestion()
  159.         if (this.parsedResponse.alternatives) {
  160.           this.renderAnswerButtons()
  161.           this.hideAnswerField()
  162.         } else {
  163.           this.showAnswerField()
  164.           this.hideButtons()
  165.         }
  166.         this.answerField.value = ''
  167.       }
  168.     })
  169.   }
  170.  
  171.   async loadQuestion(str = this.startURL) {
  172.     const response = await window.fetch(str)
  173.     const parsedResponse = await response.json()
  174.     this.parsedResponse = parsedResponse
  175.     this.saveNextURL()
  176.   }
  177.  
  178.   async sendAnswer(url = this.nextURL, answer) {
  179.     this.oldParsedResponse = this.parsedResponse
  180.     const response = await window.fetch(url, {
  181.       method: 'POST',
  182.       headers: {
  183.         'Content-Type': 'application/json'
  184.       },
  185.       redirect: 'follow',
  186.       body: answer
  187.     })
  188.     if (!response.ok) {
  189.       console.log('Throwing error message')
  190.       this.parsedResponse = await response.json()
  191.       throw Error
  192.     } else {
  193.       this.parsedResponse = await response.json()
  194.       this.saveNextURL()
  195.     }
  196.   }
  197.  
  198.   renderAnswerButtons() {
  199.     if (this.parsedResponse.alternatives) {
  200.       this.altButtons.innerText = ''
  201.       let i = 1
  202.       for (let alt in this.parsedResponse.alternatives) {
  203.         let newButton = document.createElement('button')
  204.         newButton.innerText = this.parsedResponse.alternatives[alt]
  205.         newButton.setAttribute('id', 'alt' + i)
  206.         this.altButtons.appendChild(newButton)
  207.         i++
  208.       }
  209.     }
  210.   }
  211.  
  212.   startTimer() {
  213.     setTimeout(arg => {
  214.       if (this.gameState === true) {
  215.         this.currentTime += 1
  216.         console.log(this.currentTime)
  217.         this.startTimer()
  218.         this.renderCurrentTime()
  219.       }
  220.     }, 1000)
  221.   }
  222.  
  223.   // countDown () {
  224.   //   this.currentTime += 1
  225.   // }
  226.  
  227.   hideButtons() {
  228.     this.altButtons.style.visibility = 'hidden'
  229.   }
  230.  
  231.   showButtons() {
  232.     this.altButtons.style.visibility = 'visible'
  233.   }
  234.  
  235.   hideAnswerField() {
  236.     this.answerField.style.visibility = 'hidden'
  237.     this.answerButton.style.visibility = 'hidden'
  238.   }
  239.  
  240.   showAnswerField() {
  241.     this.answerField.style.visibility = 'visible'
  242.     this.answerButton.style.visibility = 'visible'
  243.   }
  244.  
  245.   renderQuestion() {
  246.     this.questionTextPTag.innerText = this.parsedResponse.question
  247.   }
  248.  
  249.   renderScore() {
  250.     this.answerTextPTag.innerText = 'Current score: ' + this.score
  251.   }
  252.  
  253.   renderCurrentTime() {
  254.     this.currentTimePTag.innerText = 'Current time: ' + this.currentTime
  255.   }
  256.  
  257.   saveNextURL() {
  258.     this.nextURL = this.parsedResponse.nextURL
  259.   }
  260.  
  261.   answerToJson(alt) {
  262.     if (alt) {
  263.       const answerObject = { answer: alt }
  264.       const jsonAnswer = JSON.stringify(answerObject)
  265.       this.jsonAnswer = jsonAnswer
  266.     } else {
  267.       const answerObject = { answer: this.answerField.value }
  268.       const jsonAnswer = JSON.stringify(answerObject)
  269.       this.jsonAnswer = jsonAnswer
  270.     }
  271.   }
  272.  
  273.   onTimeout() {
  274.     this.gameState = false
  275.     this.answerButton.disabled = true
  276.     this.questionTextPTag.innerText = 'Gamer Over, timeout'
  277.   }
  278.  
  279.   onWrongAnswer() {
  280.     clearTimeout(this.p)
  281.     if (this.oldParsedResponse.alternatives) {
  282.       let objLength = Object.keys(this.oldParsedResponse.alternatives).length
  283.       for (let i = 1; i <= objLength; i++) {
  284.         let p = this.shadowRoot.querySelector('#alt' + i)
  285.         console.log(p)
  286.         p.disabled = true
  287.       }
  288.     }
  289.     // p.disabled = true
  290.     this.answerButton.disabled = true
  291.     this.questionTextPTag.innerText = 'Gamer Over, wrong answer'
  292.   }
  293.  
  294.   resetGame() {
  295.     clearTimeout(this.p)
  296.     this.gameState = true
  297.     this.currentTime = 0
  298.     this.showAnswerField()
  299.     this.answerButton.disabled = false
  300.     this.questionTextPTag.innerText = ''
  301.     this.answerTextPTag.innerText = ''
  302.     this.altButtons.innerText = ''
  303.     this.nextURL = this.startURL
  304.     this.score = 0
  305.   }
  306.  
  307.   // getHightScores () {
  308.     // return JSON.parse('highscores')
  309.   // }
  310.  
  311.   async saveToLocalStorage() {
  312.     // this.getHightScores()
  313.  
  314.     // Gör om det till JSON för att spara i local storage
  315.     // window.localStorage.setItem('highscores', JSON.stringify(this.allPlayers))
  316.  
  317.     // Nuvarande längden av highscore arrayen
  318.     console.log('TEST')
  319.     console.log([...this.allPlayers])
  320.     console.log(this.allPlayers)
  321.     let i = this.allPlayers.length
  322.     console.log(i)
  323.  
  324.     this.allPlayers[i] = { name: this.name, score: this.currentTime }
  325.  
  326.     window.localStorage.setItem('highscores', JSON.stringify(this.allPlayers))
  327.    
  328.     console.log([...this.allPlayers])
  329.     // if (currentHighScoreList.length >= 5) {
  330.     //   let oldHighScoreList = window.localStorage.getItem('highscores')
  331.     //   oldHighScoreList = JSON.parse(oldHighScoreList)
  332.  
  333.     //   let scoreObject = { name: this.name, score: this.currentTime }
  334.     //   let scoreArr = [scoreObject]
  335.  
  336.     //   let newScoreArr = oldHighScoreList + scoreArr
  337.     //   newScoreArr = JSON.parse(newScoreArr)
  338.     //   console.log(newScoreArr)
  339.  
  340.     //   window.localStorage.setItem('highscores', JSON.stringify(newScoreArr))
  341.     // }
  342.   }
  343.  
  344.   getFromlocalStorage() {
  345.     let highScoreList = window.localStorage.getItem('highscores')
  346.     highScoreList = JSON.parse(highScoreList)
  347.     console.log(highScoreList)
  348.   }
  349. }
  350.  
  351. window.customElements.define('question-game', QuestionGame)
  352.  
  353. export { QuestionGame }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top