0

I'm trying to make a simple game where

  • you start with 9 circles

  • when you click on a circle with a thicker border it's going to increment a score and cause new circles to be drawn randomly.

I've already worked on counting stuff but I have a problem, because wherever you click (I mean whatever div) it sums up points. I don't have an idea about how to deactivate div's which do not have a thicker border.

Please tell if this is a good programming approach.

photo of game

HTML

<body>
    <div class="container-fluid">
        <div class="row">
          <div class="col-md-2">
            <h1> Wyniki </h1> 
            <p> Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. </p>
          </div>

          <div class="col-md-8">
            <h1> Gra </h1>

            <div class="wynik">
                <h2> Rezultat </h2>
                <p id="zliczenie"> </p>
            </div>

            <div class="points"> </div>

          </div>

          <div class="col-md-2">
            <h1> Profil </h1> 
            <p> Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. </p>
          </div>
        </div>
    </div>
</body>

CSS

body {
background-color: #ecf0f1;
margin          : 2% 2%;
}

.wynik{
border          : solid 1px blue;
}

.point {
width           : 100px;
height          : 100px;
border          : solid 1px #000;
border-radius   : 100%;
text-align      : center;
cursor          : pointer;
float           : left;
margin          : 20px;
}
.point:hover {
color           : red;
border-radius   : 0%;
}

.points{
width           : calc(140px * 3);
margin          : 5px auto;
}

JS

window.onload = start;
function start()
{
        var div_value = "";

        for (i = 0; i < 9; i++) 
            {
                var element = "div_number" + i;
                div_value = div_value + '<div class="point" id="'+element+'" onclick="c('+i+')"> Klik </div>';

                if((i+1)%3 == 0) 
                {
                    div_value = div_value + '<div style="clear:both;"> </div>';
                } 

            }

        document.getElementsByClassName("points")[0].innerHTML = div_value; 

esthetic();
random_show();
}
// IT SHOWS 1 RANDOM DIV TO START THE GAME
function random_show() {
    var a = Math.floor((Math.random() * 8));
    var x = document.getElementById("div_number" + a).style.border="10px       dotted";
}

var liczby = [];
// IT DROWN LOTS AND COUNT THE SCORE
function c(i) 
{
    var a = Math.floor((Math.random() * 8));
    this.i = a;
    var z = document.getElementById("div_number" + i);
    var y = document.getElementById("div_number" + a);


    if(y.style.border = "10px dotted") {
        z.style.border ="5px dotted";
        liczby.push(i); 
    } else {
        y.style.border="8px solid";
    } 

    var x = document.getElementById("zliczenie").innerHTML = liczby.length;

}


// IT GIVES EVERY DIV INITIAL style.border 
function esthetic()
{
    var x = document.getElementsByClassName("point");
    for (i = 0; i < 9; i++) 
    {
        x[i].style.border = "5px dotted";

    }
}     

Thanks a lot for any hints one more time!

bren
  • 4,176
  • 3
  • 28
  • 43
Ernesto
  • 950
  • 1
  • 14
  • 31

4 Answers4

1

You can store the current bordered div number in a variable, and each time the click function is called, you can check if the same div number triggered this function call.

Here is your modified code that does this:

window.onload = start;

function start() {
  var div_value = "";

  for (i = 0; i < 9; i++) {
    var element = "div_number" + i;
    div_value = div_value + '<div class="point" id="' + element + '" onclick="c(' + i + ')"> Klik </div>';

    if ((i + 1) % 3 == 0) {
      div_value = div_value + '<div style="clear:both;"> </div>';
    }

  }

  document.getElementsByClassName("points")[0].innerHTML = div_value;

  esthetic();
  random_show();
}

currDiv = 0;
// IT SHOWS 1 RANDOM DIV TO START THE GAME
function random_show() {
  var a = Math.floor((Math.random() * 8));
  currDiv = a; // assign current bordered div
  var x = document.getElementById("div_number" + a).style.border = "10px       dotted";
}

var liczby = [];
// IT DROWN LOTS AND COUNT THE SCORE
function c(i) {

  if (parseInt(i) == currDiv) { // check if the current div clicked is the bordered div

    var a = Math.floor((Math.random() * 8));
    this.i = a;
    var z = document.getElementById("div_number" + i);
    var y = document.getElementById("div_number" + a);

    currDiv = a; // change it to the current bordered div


    if (y.style.border = "10px dotted") {
      z.style.border = "5px dotted";
      liczby.push(i);
    } else {
      y.style.border = "8px solid";
    }

    var x = document.getElementById("zliczenie").innerHTML = liczby.length;

  }


}


// IT GIVES EVERY DIV INITIAL style.border 
function esthetic() {
  var x = document.getElementsByClassName("point");
  for (i = 0; i < 9; i++) {
    x[i].style.border = "5px dotted";

  }
}
body {
  background-color: #ecf0f1;
  margin: 2% 2%;
}
.wynik {
  border: solid 1px blue;
}
.point {
  width: 100px;
  height: 100px;
  border: solid 1px #000;
  border-radius: 100%;
  text-align: center;
  cursor: pointer;
  float: left;
  margin: 20px;
}
.point:hover {
  color: red;
  border-radius: 0%;
}
.points {
  width: calc(140px * 3);
  margin: 5px auto;
}
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-2">
        <h1> Wyniki </h1> 
        <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.</p>
      </div>

      <div class="col-md-8">
        <h1> Gra </h1>

        <div class="wynik">
          <h2> Rezultat </h2>
          <p id="zliczenie"></p>
        </div>

        <div class="points"></div>

      </div>

      <div class="col-md-2">
        <h1> Profil </h1> 
        <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.</p>
      </div>
    </div>
  </div>
</body>

Hope it helps!

1

It is always good practice to keep the styling in .css file and html tags in .html file and the code in .js file.

Also for checking if a particular style is there on an element, you should just check if the element has a particular class in its classlist. Refer: https://developer.mozilla.org/en/docs/Web/API/Element/classList

Create new classes in your .css as:

.boldCircle {
    border: 10px dotted;
}

And in your code just do:

if(y.classlist.contains("boldCircle")) {
    // Do what you want
}

Another thing that I would like to point out is the equality in if condition. You should use '==' instead of '='. '=' is assignment operator and evaluates to true always.

if (y.style.border == "10px dotted") {
    // Do what you want
}
kumardeepakr3
  • 395
  • 6
  • 16
1

Building on @DeepakKumar recommendation, I would also think about using a class to flag an element as the active target. Your click event handler can then check for it and increment points/manage your array as needed.

I also simplified the code a bit to better format it for this sandbox.

// =====================
// Initialize the game
// =====================
function start() {
  var divTemplate = '<div id="%1%" class="point" data-index="%2%" onclick="c(event)"> Klik </div>';
  var clearTemplate = '<div style="clear:both;"> </div>';
  var elPoints = document.getElementsByClassName("points")[0];

  var div_value = "";

  for (i = 0; i < 9; i++) {
    div_value += divTemplate
                    .replace("%1%", "div_number" + i)
                    .replace("%2%", i);

    if ((i + 1) % 3 == 0) { div_value += clearTemplate; }
  }

  elPoints.innerHTML = div_value;

  liczby = [];
  random_show();
}
// =====================

// =====================
// Set one div as the target
// =====================
function random_show() {
  var a = Math.floor((Math.random() * 8));
  var elCurrentTarget = document.querySelector(".point.target");
  var elNewTarget = document.getElementById("div_number" + a);

  if (elCurrentTarget) { elCurrentTarget.classList.remove("target"); }
  elNewTarget.classList.add("target");
}
// =====================

// =====================
// If the target div was clicked increment the score
// reset the board.
// =====================
function c(event) {
  var elTarget = event.target;
  var elScore = document.getElementById("zliczenie");

  if (elTarget.classList.contains("target")) {
    liczby.push(elTarget.getAttribute("data-index"));
    elScore.innerHTML = liczby.length;
  }

  random_show();
}
// =====================

var liczby = [];
window.onload = start;
.wynik {
  border: solid 1px blue;
}

.points {
  width: calc(140px * 3);
  margin: 5px auto;
}

.point {
  width: 60px;
  height: 60px;
  border: solid 1px #000;
  border-radius: 100%;
  text-align: center;
  cursor: pointer;
  float: left;
  margin: 10px;

  border: 5px dotted;
}

.point.target {
  border: 10px dotted;
}

.point:hover {
  color: red;
  border-radius: 0%;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha256-916EbMg70RQy9LHiGkXzG8hSg9EdNy97GazNG/aiY1w=" crossorigin="anonymous" />

<div class="container-fluid">
  <div class="row">
    <div class="wynik">
      <span>Rezultat: </span><span id="zliczenie"></span>
    </div>
    <div class="points"></div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha256-U5ZEeKfGNOja007MMD3YBI0A3OSZOQbeG6z2f2Y0hu8=" crossorigin="anonymous"></script>
JonSG
  • 10,542
  • 2
  • 25
  • 36
  • @Pineda Your suggested edits were good, but I made an edit that would not allow me to accept your suggestions. I hope I have now also incorporated what you suggested. – JonSG Nov 12 '16 at 18:54
1

The following code means "score + 1 if you clicked the thick circle, score - 1 otherwise" :

score += i == winning ? +1 : -1;

See conditional operator for details.

A post about randomness : https://stackoverflow.com/a/32395535/1636522.

var boardEl = document.getElementById("board"), 
    scoreEl = document.getElementById("score"), 
    indexOf = Array.prototype.indexOf, 
    winning = 0, 
    score = 0;

scoreEl.textContent = "( " + score + " )";
boardEl.innerHTML = new Array(10).join("<a href=\"#\"></a>");
boardEl.childNodes[winning].setAttribute("class", "winning");

boardEl.onclick = function (ev) {
  var i, rdm, winningEl;
  ev.preventDefault();
  if (ev.target.parentNode == boardEl) {
    i = indexOf.call(boardEl.childNodes, ev.target);
    score += i == winning ? +1 : -1;
    winningEl = boardEl.childNodes[winning];
    winningEl.setAttribute("class", "");
    rdm = Math.floor(Math.random() * 8);
    winning = rdm >= winning ? rdm + 1 : rdm;
    winningEl = boardEl.childNodes[winning];
    winningEl.setAttribute("class", "winning");
    scoreEl.textContent = "( " + score + " )";
  }
};
#board, #score {
  display: inline-block;
  vertical-align: middle;
}

#board {
  width: 150px;
}

#score {
  font: bold 32px Arial;
  color: #666;
}

#board a {
  vertical-align: top;
  display: inline-block;
  border: 5px dashed #666;
  border-radius: 50%;
  height: 30px;
  width: 30px;
  margin: 5px;
}

#board a.winning {
  border-width: 10px;
  height: 20px;
  width: 20px;
}

#board a:hover {
  border-color: black;
}
<div id="board"></div>
<div id="score"></div>