Question

How do I generate a content at random, within a cell in the table? I'm making a game where the user has at disposal 10 attempts. With these efforts should try to select the cell containing a key. With each failed attempt, these decrease. The problem is that I do not know how to insert the contents randomly generated by the script, within the cell.

<html>
<meta charset="utf-8">
<head><title>game of the key</title>
<style type="text/css"> 
table  
{ 
border-collapse:collapse;
}
td {border: 5px solid maroon;
padding:80px                        
}
</style>
</head>
<body><div align="center">
<table id="table" onclick="clic()">
<tr><td id="1"></td><td id="2"></td><td id="3"></td><td id="4"></td><td id="5"></td></tr>
<tr><td id="6"></td><td id="7"></td><td id="8"></td><td id="9"></td><td id="10"></td></tr>
<tr><td id="11"></td><td id="12"></td><td id="13"></td><td id="14"></td><td id="15"></td></tr>
<tr><td id="16"></td><td id="17"></td><td id="18"></td><td id="19"></td><td id="20"></td></tr> 
<tr><td id="21"></td><td id="22"></td><td id="23"></td><td id="24"></td><td id="25"></td></tr>
</table></div>
</body>
<script>

var attempts = 10;
var key = true;

function clic() 
{

console.log("check");


} 

</script>
</html>
Was it helpful?

Solution

Try with:

var cellId = Math.floor(Math.random() * 24 + 1);
document.getElementById(cellId).setAttribute("name", "key");

But the user can simply look at the source of the page to find the key

for check if the key is found

function clic(e) 
{
    if( attempts <= 0){
        console.log("no more attempts");
        return;
    }
    if( e.target.getAttribute('name') == 'key' ){
       console.log('key found');  
    }
    else{
       console.log('key NOT found'); 
      --attempts;    
    }
}

Here you find the working jsFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top