0

I have create two dices that are 1 until 11 slots.I want to display the results.If red wins (for example I want to show me a message R wins or if B ends first the B wins).Also, I want to display the results in a new table.I am trying to do that but I can't. Javascript code is this.

 // basic game settings
    const gameSettings = {
      length: 12,
      die: {
        min: 1,
        max: 8,
      }
    }
    
    // define "actors"
    let gameItems = [{
        name: "R",
        bgColor: "red",
        color: "white",
        position: 1,
      },
      {
        name: "B",
        bgColor: "black",
        color: "white",
        position: 1,
      },
    ]
    
    // the random function
    // source: https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript
    function randomIntFromInterval(min, max) { // min and max included 
      return Math.floor(Math.random() * (max - min + 1) + min);
    }
    
    // -----------------
    
    // creating a row & cells
    const rowHtml = (gameItem, cols) => {
      let html = `<div class="row" style="grid-template-columns: repeat(${ cols }, 1fr)">`
      for (let i = 0; i < cols; i++) {
        let marker = "-"
        let background = "white"
        let color = "black"
    
        if (gameItem.position - 1 === i) {
          marker = gameItem.name
          background = gameItem.bgColor
          color = gameItem.color
        }
    
        html += `<div class="cell" style="background: ${ background }; color: ${ color }">${ marker }</div>`
      }
      html += `</div>`
      return html
    }
    
    // updating rows
    const updateRows = (container, gameItems, cols) => {
      let html = ''
      for (let i = 0; i < gameItems.length; i++) {
        html += rowHtml(gameItems[i], cols)
      }
      container.innerHTML = html
    }
    
    // setting container
    const container = document.getElementById('container')
    
    // set up board for first time
    updateRows(container, gameItems, gameSettings.length)
    
    // -----------------
    // action buttons
    const btnRoll = document.getElementById("rollTheDice")
    const btnResetBoard = document.getElementById("resetBoard")
    
    // roll action
    btnRoll.addEventListener('click', function() {
      const {
        length,
        die: {
          min
        },
        die: {
          max
        }
      } = gameSettings
    
      gameItems = gameItems.map(item => ({
        ...item,
        position: item.position + randomIntFromInterval(min, max),
      }))
      updateRows(container, gameItems, length)
    })
    
    // reset action
    btnResetBoard.addEventListener('click', function() {
      const {
        length
      } = gameSettings
      gameItems = gameItems.map(item => ({
        ...item,
        position: 1,
      }))
      updateRows(container, gameItems, length)
    })

and the code of html,css is this

.row {
  display: grid;
  grid-template-rows: 1fr;
}

.cell {
  box-sizing: border-box;
  border: 1px solid black;
  display: flex;
  justify-content: center;
}
<div id="container"></div>
<hr />
<button id="rollTheDice">ROLL THE DICE</button><br />
<button id="resetBoard">RESET BOARD</button>

1 Answers1

0

Its really simple solution but you can work on it and extend to really have what you want.

I would done it like so apply some check of each player score on each click on roll the dice button, of course after all randomizing happens to prevent need clicking another time to get results.

      let winnerScore = 0;
      let winner = '';
      
      gameItems.forEach(item => {
        if (item.position >= 11) {
          winner = item.name;
          winnerScore = item.position;
        }
      });
      
      if (winnerScore >= 11) {
        console.log('[winner_result]', winner, ' wins game!');
      }

Of course instead of using this console.log on detect that someone won you can easily exapnd it to display scores or really what you want on screen. I think the best way to do that is to really get all properties from "actor" object in loop check. This solution will really decreas number of loops you need to do.

To really show results you'll have to add function or outputing it into html div element like so

      if (winnerScore >= 11) {
        console.log('[winner_result]', winner, ' wins game!');
        document.getElementById('results').innerHTML = `${winner} wins game!`;
      }

to get it working really you also need to add somewhere in you html strucure div with id "results" or anything else really but you have to remeber to swap ip too on js script

Hope It answers you're needs.

Below link to codepen which I was working on this solution: https://codepen.io/snoh666/pen/jOMamMy

snoh666
  • 129
  • 1
  • 6
  • Have you checked console? – snoh666 Dec 25 '20 at 15:59
  • yes I have check it ,,it doesn't show me anything –  Dec 25 '20 at 16:00
  • This part really checks for winner ```if (winnerScore >= 11) { console.log('[winner_result]', winner, ' wins game!'); } ``` – snoh666 Dec 25 '20 at 16:00
  • but it doestn't pass the "data" on another new table.I want to have a new table and to show the message from console to be shown in my table .In console it doesn't seem in my website –  Dec 25 '20 at 16:01
  • I wanted to give you an explanation how to really achieve what you want not do it for you. I've edited answer to give you maybe more clarity – snoh666 Dec 25 '20 at 16:10
  • I know man what you were trying to do,but my problem is on pass it on a table that result.To make it shown up.If I could do it I wouldn't be asking here.It works on console what we have done.I see it too.That part it was great,but I want those result to pass it in a table .Even if you can answer I have a lot of similar to do based on that –  Dec 25 '20 at 16:13
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/226418/discussion-between-snoh666-and-main-klain). – snoh666 Dec 25 '20 at 16:13