用户点击额外的笑脸后,如何在随机位置生成新的笑脸?

时间:2016-09-27 15:12:56

标签: javascript

我一直试图通过将函数delete_all_children()放在适当的位置来让笑脸在新的随机位置生成,但每次都不会正常运行。相反,如果我在找到额外图片后忽略了随机位置,游戏就会正常运行,但它是从现有的笑脸中积聚起来的,这使得游戏更容易。

我想让新面孔在随机位置生成。

请帮忙!

<DOCTYPE! html>
<html>
<head>
    <title>Matching Game - Smiling :)</title>

    <style>
        div, img {position: absolute;}
        div {width: 500px; height: 500px;}
        #rightSide {left: 500px; border-left: 1px solid black}
    </style>
    <script type="text/javascript">

            var numberOfFace = 5;
            var count = 0;
            var theBody = document.getElementsByTagName("body")[0];

        function generateFaces() {

            var theLeftSide = document.getElementById('leftSide');
            var theRightSide = document.getElementById('rightSide');

            while (count < numberOfFace) {
            var top_random = (Math.random() * 400);
            var left_random = (Math.random() * 400);

            var smiling_face = document.createElement("img");
            smiling_face.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
            smiling_face.style.top = Math.floor(top_random) + "px";
            smiling_face.style.left = Math.floor(left_random) + "px";
            theLeftSide.appendChild(smiling_face);
            count ++;
            };

            leftSideImages = theLeftSide.cloneNode(true);
            leftSideImages.removeChild(leftSideImages.lastChild);
            theRightSide.appendChild(leftSideImages);

            theLeftSide.lastChild.onclick = function nextLevel(event) {
            event.stopPropagation();
            numberOfFace += 5;
            generateFaces();
            };

            theBody.onclick = function gameOver() {
            alert("Game Over!");
            theBody.onclick = null;
            theLeftSide.lastChild.onclick = null;
            };

            function delete_all_children() {
                var theNode = document.getElementById("theBody");
                while (theNode.firstChild) {
                    theNode.removeChild(theNode.firstChild);
                };
            };

            };


    </script>
</head>

<body onload="generateFaces()">
    <h1>Matching Game</h1>
    <p>Click on the extra smiling face on the left!</p>
    <div id="leftSide"></div>
    <div id="rightSide"></div>
</body>
</html>

0 个答案:

没有答案