Express服务器跳过if语句并发送对POST请求的响应



我正在制作一款带有客户端-服务器通信接口的JS战舰游戏。

在我的客户端中,我将用户在CPU游戏板上点击的互动程序发送到服务器,以检查它是HIT还是MISS,并根据服务器的响应,游戏板会更新以显示船只是否被击中。

这是我的服务器响应命中/未命中的部分:

// generate cpu attack
var tileToAttack = cpuAttack(dataIn['cpuhitship']);
// cpu tile being attacked by player
var tileXY = dataIn['tileattacked'];        
// check if a CPU ship placed on the selected tile
if(allCoords.includes(tileXY)){
// remove tile from array
var index = allCoords.indexOf(tileXY);
if(index != -1){
allCoords.splice(index, 1);
} 
// check if ship is destroyed
cpuShipDestroyed(tileXY);            
// send back hit response and cpu attack
var jsontext = JSON.stringify({
task:'cpuHit',                      
tilehit:tileXY,
message:'HIT! BOOOOM!',
carrierlength:carrier.length,
battleshiplength:battleship.length,
submarinelength:submarine.length,
cruiserlength:cruiser.length,
patrolboatlength:patrolboat.length,
cpucoords:allCoords.length,
cpuattack:tileToAttack                            
});
res.send(jsontext);            
}    
else{
// send back miss response and cpu attack
var jsontext = JSON.stringify({
task: 'cpuMiss',
tilemiss:tileXY,
cpuattack:tileToAttack,                               
message:'MISS! All you hear is the missile hitting water!'
});
res.send(jsontext);
console.log(jsontext);          
} 

这是我发送的JSON对象

// get coordinates of the tile being attacked
var attackXY = parseInt(cpuTile.substring(8, 10));
var data = 
{
task:'playerAttack',                
tileattacked:attackXY      
};             
$.ajax({
url: url,
method: 'POST',
data: data,
dataType: 'json' 
}).done(function(response) {

tileXY是与游戏板上的瓦片相对应的整数。示例12将是1个瓦片X和2个瓦片Y。

allCoords存储17个整数,这些整数对应于CPU的发货位置。

然而,即使我击中了正确的瓦片,我也只会收到未命中的响应;它跳过if语句,每次都转到else{}部分。有关于可能发生的事情的线索吗?

修复了它。我不得不使用parseInt((。

最新更新