【问题标题】:I am tring to create "Sinking ships" using jQuery我正在尝试使用 jQuery 创建“沉船”
【发布时间】:2014-12-08 14:52:11
【问题描述】:

到目前为止,我正在尝试制作用于将船舶放置在船上的功能,但我在检查某些字段是否可用时遇到了一些问题。我的基本想法是有一种方法可以在单击按钮时调用:

$("#dodaj1x1").click(function(){
        var raspolozivo=parseInt($("#raspolozivo1x1").text());
        if(raspolozivo>0){

            generisi1x1();//call for function that generate random field

            var novoRaspolozivo= raspolozivo-1;
            $("#raspolozivo1x1").html(novoRaspolozivo);
        }
        else{
            alert("Rasporedjeni svi raspolozivi brodovi ovog tipa!");
        }
    });

它会调用函数来生成随机场:

function generisi1x1(){
            var minR = 0;
            var maxR = 9;
            var minK = 0;
            var maxK = 9;
            randRed=Math.floor(Math.random() * (maxR - minR + 1)) + minR;
            randKol=Math.floor(Math.random() * (maxK - minK + 1)) + minK;
            proveri1x1(randRed,randKol);//call to function to check is field available
    }

比函数generisi1x1() 调用检查该字段是否可用的函数:

function proveri1x1(randRed,randKol){
        for(i=randRed-1;i<randRed+2;i++){
            for(j=randKol-1;j<randKol+2;j++){
                if($(".red"+i+".kolona"+j+"").hasClass('deoBroda')){
                    alert("red:"+" "+i+" kolona:"+j);
                    generisi1x1();
                }
                else { postavi1x1(randRed,randKol);}
            }
        }
    }

而我的问题是,有时这项工作很棒(至少看起来效果很好,也许纯粹是运气),有时它只生成 3 艘 1x1 船(应该有 4 艘),有时它向我显示有关问题的消息并生成5 艘船(4 艘在正确的位置,1 艘在错误的位置)等等。

坏案例的打印屏幕:Added ship 1x1 on position 5,3 right next to ship 4x1

这里是整个代码的现场演示:Live demo

到目前为止,我可以插入 4x1 和 1x1 的船只,并且只检查 1x1,计划对所有船只都做同样的事情,任何帮助都会很棒。

【问题讨论】:

    标签: javascript jquery html css 2d-games


    【解决方案1】:

    如果proveri1x1() 执行检查并返回truefalse,而generisi1x1() 执行postavi1x1() 操作,您会发现更容易理解;

    function generisi1x1() {
        var minR = 0, maxR = 9, minK = 0, maxK = 9;
        randRed = Math.floor(Math.random() * (maxR - minR + 1)) + minR;
        randKol = Math.floor(Math.random() * (maxK - minK + 1)) + minK;
        if(proveri1x1(randRed, randKol)) { //call to function to check is field available
            postavi1x1(randRed,randKol);//set
        } else {
            generisi1x1();//try again
        }
    }
    
    function proveri1x1(randRed, randKol) {
        for(var i=randRed-1; i<randRed+2; i++) {
            for(var j=randKol-1; j<randKol+2; j++) {
                if($(".red" + i + ".kolona" + j).hasClass('deoBroda')) {
                    return false;
                }
            }
        }
        return true;//<<<< note the position of this return statement
    }
    

    【讨论】:

    • @user3294091,根据我的回答,您可以减少代码量并更容易定义新的船舶类型,例如THIS。注意 - 更改 HTML 和 javascript,但不更改 CSS。
    猜你喜欢
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多