【问题标题】:Express server skipping if statement and sending response to POST requestExpress 服务器跳过 if 语句并发送对 POST 请求的响应
【发布时间】:2020-06-15 09:54:32
【问题描述】:

我正在使用带有客户端-服务器通信接口的 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{} 部分。关于可能发生什么的任何线索?

【问题讨论】:

  • 如果你说的代码总是跳过if(allCoords.includes(tileXY)){,那么显然那个语句总是false,所以你必须做一些调试来弄清楚为什么会这样。
  • @jfriend00 好的,由于某种原因,包含与图块对应的整数的 JSON 数据似乎不适用于数组的 include() 甚至 index() 函数?

标签: json express post server client


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 2019-12-30
    • 2018-02-10
    相关资源
    最近更新 更多