javaScript - 猜瓦片游戏

时间:2014-09-08 11:27:11

标签: javascript html css

我正在制作一个javaScript游戏 - 最终将是一个带有网格GUI的战舰游戏等等。

已经开始用瓷砖制作水平网格(用户可以为自己定义(最少4个瓷砖))

当点击时,一块瓷砖从蓝色变为红色,表明它是否被击中 - 但它没有注册,如果它被击中3次,那么应弹出统计数据和准确度:

等。在3之后它将弹出统计数据:“你需要3-4次猜测才能沉没我的战舰,你的准确率是30%”

相反,它给了我0猜测,我的准确度是无限的:)

我在下面发布了我的代码:

<html>
<head>
    <title></title>
    <style type="text/css">
    td 
    {
        width: 94px;
        height: 94px;
        background-color: blue;
    }


    .clicked
{
    color: red;
}



    </style>
</head>
<body>

<div id="board">
<div id="messageArea"></div>
<table>
<tr id="tblRow">
</tr>
</table>
</div>

<script type="text/javascript">

var boardLength;

do {

boardLength = prompt('Enter length of board length (min 4)')
}

while(boardLength <4);

var boardLengthCal = parseInt(boardLength)-2;
var randomLoc = Math.floor(Math.random() * boardLengthCal);
var location1 = randomLoc;
var location2 = location1 + 1;
var location3 = location1 + 2;
console.log(location1);
console.log(location2);
console.log(location3);



for (var i = 0; i < boardLength; i++){
document.getElementById('tblRow').innerHTML +="<td id='"+i+"'></td>"
};

var fields = document.getElementsByTagName('td');
for (var i =0; i < fields.length; i++){
fields[i].addEventListener('click', pickLocation)
};

function pickLocation(){

guess = this.id;
    if (guess < 0 || guess > boardLength) {
        alert("Please enter a valid cell number!");
    } else {
        guesses = guesses + 1;
        if (guess == location1 || guess == location2 || guess == location3) {
            changeColor(this, "red");
            alert("HIT!");
            hits = hits + 1;
            if (hits == 3) {
                isSunk = true;
                alert("You sank my battleship!");
            }
        } else {
            alert("MISS");
        }



        }

}

var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;

var stats = "You took " + guesses + " guesses to sink the battleship, " +
            "which means your shooting accuracy was " + (3*100/guesses)+"%";
alert(stats);


function changeColor(element, color)
{
    element.style.backgroundColor = color;
};

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

显示代码的统计信息在游戏开始之前就已执行。那时你的猜测值是0,所以除以0会给你无限。你需要将你的统计代码放在一个函数中并在游戏结束时调用它(3次点击)

function stats(){
    var stats = "You took " + guesses + " guesses to sink the battleship, " +
            "which means your shooting accuracy was " + (3*100/guesses)+"%";
    alert(stats);
}

if (hits == 3) {
   isSunk = true;
   alert("You sank my battleship!");
   stats();
}

现在,当用户点击三次时,只会弹出具有正确值的统计数据。

<强> See the DMEO here

编辑: 我在你的游戏中做了一些改进,现在通过引入随机数而不是三行并删除其他小错误来实现可玩性。你可以检查该版本 HERE.