我试图编写代码来检测船是否被击中。我在船上有3艘船,每艘需要3个单元。使用js我将3艘船放在了板上。当我运行火力法时,只有最后两艘船显示它们已被击中,但位于00,01,02的第一艘船并未表示它被击中,甚至一次。我哪里做错了?
这是html:
<div id='board'>
<div id='message'></div>
<table>
<tr>
<td id='00'></td>
<td id='01'></td>
<td id='02'></td>
<td id='03'></td>
<td id='04'></td>
<td id='05'></td>
<td id='06'></td>
</tr>
<tr>
<td id='10'></td>
<td id='11'></td>
<td id='12'></td>
<td id='13'></td>
<td id='14'></td>
<td id='15'></td>
<td id='16'></td>
</tr>
<tr>
<td id='20'></td>
<td id='21'></td>
<td id='22'></td>
<td id='23'></td>
<td id='24'></td>
<td id='25'></td>
<td id='26'></td>
</tr>
<tr>
<td id='30'></td>
<td id='31'></td>
<td id='32'></td>
<td id='33'></td>
<td id='34'></td>
<td id='35'></td>
<td id='36'></td>
</tr>
<tr>
<td id='40'></td>
<td id='41'></td>
<td id='42'></td>
<td id='43'></td>
<td id='44'></td>
<td id='45'></td>
<td id='46'></td>
</tr>
<tr>
<td id='50'></td>
<td id='51'></td>
<td id='52'></td>
<td id='53'></td>
<td id='54'></td>
<td id='55'></td>
<td id='56'></td>
</tr>
<tr>
<td id='60'></td>
<td id='61'></td>
<td id='62'></td>
<td id='63'></td>
<td id='64'></td>
<td id='65'></td>
<td id='66'></td>
</tr>
</table>
<form action='#' method='get'>
<input type='text' id='guessInput' placeholder='enter location: A0'/>
<input type='button' name='submit' value='Fire!' name='fire'/>
</form>
</div>
CSS:
*{
margin:0px;
padding:0px;
}
body{
background-color:black;
}
#message{
color:green;
font-size:2em;
text-transform:uppercase;
font-family:sans-serif;
}
#board{
background:url('board.jpg') no-repeat;
width:863px;
height:1024px;
margin:auto;
position:relative;
}
table{
position:absolute;
left:173px;
top:98px;
}
td{
height:94px;
width:94px;
}
form input{
position:absolute;
right:0px;
bottom:0px;
background-color:green;
}
.hit{
background:url('ship.png') no-repeat center center;
}
.miss{
background:url('miss.png') no-repeat center center;
}
JS:
var view={
showMessage:function(msg){
var message=document.getElementById('message');
message.innerHTML = msg;
},
showHit:function(location){
var cell=document.getElementById(location);
cell.setAttribute('class','hit');
},
showMiss:function(location){
var cell=document.getElementById(location);
cell.setAttribute('class','miss');
}
}
var model = {
boardSize:7,
numShips:3,
shipsSunk:3,
ships:[{location:[00,01,02], hits:['','','']},
{location:[10,11,12], hits:['','','']},
{location:[20,21,22], hits:['','','']}],
fire:function(guess){
for(var i=0; i<this.numShips; i++){
var ship = this.ships[i];
var index=ship.location.indexOf(guess);
if(index>=0){
ship.hits[index]='hit';
view.showHit(guess);
}
}
}
};
model.fire(10);
model.fire(11);
model.fire(12);
model.fire(20);
model.fire(21);
model.fire(22);
model.fire(00);
model.fire(01);
model.fire(02);
答案 0 :(得分:2)
您的坐标00,01和02被解释为int
s,因此被解析为0,1和2,因为假设int
不需要前导零值。您可以通过使用字符串来表示和比较坐标来解决此问题。而不是model.fire(00)
,您需要model.fire("00")
。然后,要比较输入坐标,您需要比较guess.charAt(0)
和guess.charAt(1)
以确定该坐标是否为点击。