How to check Tic-Tac-Toe Winner
I want to know what is wrong with my code. I made a tic-tac-toe game using a table in the body of the website and javascript. Here are the relevant parts of my code:
INSIDE BODY:
<body>
</table>
<table id="matrix" border="1">
<tr>
<td class="cellCSS">
<img alt="Click Here" class="imageCSS" onclick="imageClicked(this,0,0)"/>
</td>
<td class="cellCSS">
<img alt="Click Here" class="imageCSS" onclick="imageClicked(this,0,1)"/>
</td>
<td class="cellCSS">
<img alt="Click Here" class="imageCSS" onclick="imageClicked(this,0,2)"/>
</td>
</tr>
...
</table>
</body>
And this is the relevant part of the function imageClicked:
...
same = false;
var r = 0;
tbl = document.getElementById("matrix");
//alert(tbl.rows.length);
for(r = 0; r < tbl.rows.length; r++) {
// alert('Bob');
var _tempmg = tbl.rows[r].cells[col].childNodes[0].src;
alert(开发者_开发知识库_tempmg);
if (!_tempmg) break;
if (_img.src != _tempmg) break;
same = true;
}
if (r == tbl.rows.length && same) {
alert(_img.src + "won");
return;
}
same = false;
...
Your problem is that r == tbl.rows.length is always false, because the for loop iterates while r < tbl.rows.length.
You should include a bit more of the imageClicked function. I'll guess that it starts:
function imageClicked(element, row, col) {
and in your posted code:
same = false;
Presumably you've declared same earlier to keep it local.
var r = 0;
There is no need to initialise r here (i.e. assign it a value) if you do so in the loop.
tbl = document.getElementById("matrix");
for(r = 0; r < tbl.rows.length; r++) {
var _tempmg = tbl.rows[r].cells[col].childNodes[0].src;
if (!_tempmg) break;
In your html, you have not assigned a value to the image src attribute, so I would have thought that at this point you'd assign a naught or cross depending on who had clicked on it. Having assigned an appropriate image, I would execute the next line.
if (_img.src != _tempmg) break;
same = true;
It might be clearer to add a condition to the for(...) expression like:
for(r = 0; r < tbl.rows.length && !same; r++) {
Now instead of break you can use:
if (_img.src == _tempmg) same = true;
.
}
if (r == tbl.rows.length && same) {
alert(_img.src + "won");
return;
}
same = false;
I need to see more of the imageClicked function to understand why it isn't working.
精彩评论