Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const template = document.createElement('template')
- template.innerHTML = `
- <style>
- #questionDiv {
- visibility: hidden;
- }
- </style>
- <div id="highScoreDiv">
- <p>Enter your username</p>
- <input id="nicknameField" type="text">
- <button id="submitButton">Submit</button>
- </div>
- <div id="questionDiv">
- <button id="info">Info</button>
- <br><br><br>
- <button id="startButton">Start</button>
- <br>
- <input id="answerField" type="text">
- <button id="answerButton">Answer</button>
- <div id="altButtons">
- </div>
- <p id="questionTextPTag"></p>
- <p id="answerResultPTag"></p>
- <p id="currentScore"></p>
- <p id="currentTime"></p>
- </div>
- `
- class QuestionGame extends window.HTMLElement {
- constructor() {
- super()
- this.attachShadow({ mode: 'open' })
- this.shadowRoot.appendChild(template.content.cloneNode(true))
- this.questionDiv = this.shadowRoot.querySelector('#questionDiv')
- this.highScoreDiv = this.shadowRoot.querySelector('#highScoreDiv')
- this.nicknameField = this.shadowRoot.querySelector('#nicknameField')
- this.startButton = this.shadowRoot.querySelector('#startButton')
- this.answerButton = this.shadowRoot.querySelector('#answerButton')
- this.answerField = this.shadowRoot.querySelector('#answerField')
- this.submitButton = this.shadowRoot.querySelector('#submitButton')
- this.altButtons = this.shadowRoot.querySelector('#altButtons')
- this.infoButton = this.shadowRoot.querySelector('#info')
- this.questionTextPTag = this.shadowRoot.querySelector('#questionTextPTag')
- this.answerTextPTag = this.shadowRoot.querySelector('#answerResultPTag')
- this.currentTimePTag = this.shadowRoot.querySelector('#currentTime')
- this.startURL = 'http://vhost3.lnu.se:20080/question/1'
- this.nextURL = ''
- this.highScoreArray = []
- this.allPlayers = []
- this.name = ''
- this.gameState = true
- this.score = 0
- this.currentTime = 0
- this.parsedResponse = ''
- this.jsonAnswer = ''
- this.p = setTimeout(args => { }, 0)
- }
- static get observedAttributes() {
- return []
- }
- attributesChangedCallback(name, oldValue, newValue) {
- }
- connectedCallback() {
- // Hides the username div and shows the question div
- this.submitButton.addEventListener('click', event => {
- this.name = this.nicknameField.value
- this.highScoreDiv.style.visibility = 'hidden'
- this.questionDiv.style.visibility = 'visible'
- console.log(this.name)
- // this.saveToLocalStorage()
- })
- this.infoButton.addEventListener('click', async event => {
- // console.log(this.nextURL)
- // console.log(this.parsedResponse)
- // debugger
- // this.startTimer()
- // this.saveToLocalStorage()
- this.saveToLocalStorage()
- // this.getFromlocalStorage()
- })
- this.startButton.addEventListener('click', async event => {
- this.resetGame()
- this.startTimer()
- await this.loadQuestion()
- this.p = setTimeout(arg => {
- this.onTimeout()
- }, 7001)
- this.renderQuestion()
- })
- this.answerButton.addEventListener('click', async event => {
- console.log(event.target.id)
- this.answerToJson()
- try {
- await this.sendAnswer(this.nextURL, this.jsonAnswer)
- this.score++
- } catch (error) {
- this.onWrongAnswer()
- return
- }
- this.renderScore()
- await this.loadQuestion(this.nextURL)
- clearTimeout(this.p)
- this.p = setTimeout(arg => {
- this.onTimeout()
- }, 7000)
- this.renderQuestion()
- if (this.parsedResponse.alternatives) {
- this.renderAnswerButtons()
- this.hideAnswerField()
- this.showButtons()
- } else {
- this.showAnswerField()
- this.hideButtons()
- }
- this.answerField.value = ''
- })
- this.altButtons.addEventListener('click', async event => {
- console.log(event.target.id)
- if (event.target.id === 'alt1' || event.target.id === 'alt2' || event.target.id === 'alt3' || event.target.id === 'alt4') {
- this.answerToJson(event.target.id)
- try {
- await this.sendAnswer(this.nextURL, this.jsonAnswer)
- this.score++
- } catch (error) {
- this.onWrongAnswer()
- return
- }
- this.renderScore()
- await this.loadQuestion(this.nextURL)
- clearTimeout(this.p)
- this.p = setTimeout(arg => {
- this.onTimeout()
- }, 7000)
- this.renderQuestion()
- if (this.parsedResponse.alternatives) {
- this.renderAnswerButtons()
- this.hideAnswerField()
- } else {
- this.showAnswerField()
- this.hideButtons()
- }
- this.answerField.value = ''
- }
- })
- }
- async loadQuestion(str = this.startURL) {
- const response = await window.fetch(str)
- const parsedResponse = await response.json()
- this.parsedResponse = parsedResponse
- this.saveNextURL()
- }
- async sendAnswer(url = this.nextURL, answer) {
- this.oldParsedResponse = this.parsedResponse
- const response = await window.fetch(url, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- redirect: 'follow',
- body: answer
- })
- if (!response.ok) {
- console.log('Throwing error message')
- this.parsedResponse = await response.json()
- throw Error
- } else {
- this.parsedResponse = await response.json()
- this.saveNextURL()
- }
- }
- renderAnswerButtons() {
- if (this.parsedResponse.alternatives) {
- this.altButtons.innerText = ''
- let i = 1
- for (let alt in this.parsedResponse.alternatives) {
- let newButton = document.createElement('button')
- newButton.innerText = this.parsedResponse.alternatives[alt]
- newButton.setAttribute('id', 'alt' + i)
- this.altButtons.appendChild(newButton)
- i++
- }
- }
- }
- startTimer() {
- setTimeout(arg => {
- if (this.gameState === true) {
- this.currentTime += 1
- console.log(this.currentTime)
- this.startTimer()
- this.renderCurrentTime()
- }
- }, 1000)
- }
- // countDown () {
- // this.currentTime += 1
- // }
- hideButtons() {
- this.altButtons.style.visibility = 'hidden'
- }
- showButtons() {
- this.altButtons.style.visibility = 'visible'
- }
- hideAnswerField() {
- this.answerField.style.visibility = 'hidden'
- this.answerButton.style.visibility = 'hidden'
- }
- showAnswerField() {
- this.answerField.style.visibility = 'visible'
- this.answerButton.style.visibility = 'visible'
- }
- renderQuestion() {
- this.questionTextPTag.innerText = this.parsedResponse.question
- }
- renderScore() {
- this.answerTextPTag.innerText = 'Current score: ' + this.score
- }
- renderCurrentTime() {
- this.currentTimePTag.innerText = 'Current time: ' + this.currentTime
- }
- saveNextURL() {
- this.nextURL = this.parsedResponse.nextURL
- }
- answerToJson(alt) {
- if (alt) {
- const answerObject = { answer: alt }
- const jsonAnswer = JSON.stringify(answerObject)
- this.jsonAnswer = jsonAnswer
- } else {
- const answerObject = { answer: this.answerField.value }
- const jsonAnswer = JSON.stringify(answerObject)
- this.jsonAnswer = jsonAnswer
- }
- }
- onTimeout() {
- this.gameState = false
- this.answerButton.disabled = true
- this.questionTextPTag.innerText = 'Gamer Over, timeout'
- }
- onWrongAnswer() {
- clearTimeout(this.p)
- if (this.oldParsedResponse.alternatives) {
- let objLength = Object.keys(this.oldParsedResponse.alternatives).length
- for (let i = 1; i <= objLength; i++) {
- let p = this.shadowRoot.querySelector('#alt' + i)
- console.log(p)
- p.disabled = true
- }
- }
- // p.disabled = true
- this.answerButton.disabled = true
- this.questionTextPTag.innerText = 'Gamer Over, wrong answer'
- }
- resetGame() {
- clearTimeout(this.p)
- this.gameState = true
- this.currentTime = 0
- this.showAnswerField()
- this.answerButton.disabled = false
- this.questionTextPTag.innerText = ''
- this.answerTextPTag.innerText = ''
- this.altButtons.innerText = ''
- this.nextURL = this.startURL
- this.score = 0
- }
- // getHightScores () {
- // return JSON.parse('highscores')
- // }
- async saveToLocalStorage() {
- // this.getHightScores()
- // Gör om det till JSON för att spara i local storage
- // window.localStorage.setItem('highscores', JSON.stringify(this.allPlayers))
- // Nuvarande längden av highscore arrayen
- console.log('TEST')
- console.log([...this.allPlayers])
- console.log(this.allPlayers)
- let i = this.allPlayers.length
- console.log(i)
- this.allPlayers[i] = { name: this.name, score: this.currentTime }
- window.localStorage.setItem('highscores', JSON.stringify(this.allPlayers))
- console.log([...this.allPlayers])
- // if (currentHighScoreList.length >= 5) {
- // let oldHighScoreList = window.localStorage.getItem('highscores')
- // oldHighScoreList = JSON.parse(oldHighScoreList)
- // let scoreObject = { name: this.name, score: this.currentTime }
- // let scoreArr = [scoreObject]
- // let newScoreArr = oldHighScoreList + scoreArr
- // newScoreArr = JSON.parse(newScoreArr)
- // console.log(newScoreArr)
- // window.localStorage.setItem('highscores', JSON.stringify(newScoreArr))
- // }
- }
- getFromlocalStorage() {
- let highScoreList = window.localStorage.getItem('highscores')
- highScoreList = JSON.parse(highScoreList)
- console.log(highScoreList)
- }
- }
- window.customElements.define('question-game', QuestionGame)
- export { QuestionGame }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement