JavaScript文本游戏积分系统

JavaScript text game points system

本文关键字:分系统 游戏 文本 JavaScript      更新时间:2024-01-11

我是JavaScript的初学者,通过做我在网上找到的简单项目来练习/提高我的JavaScript技能。

这基本上是一个有四个按钮的文本定位游戏。北、南、东和西。每次玩家去一个新的地方,我都会加5分。

我怎么能做到,一旦点击按钮,它就不会加分?

<script type="text/javascript">
var score = 0;
function north(){
    var message = 'You are now in the kitchen';
    alert(message);
    document.getElementById("score").innerHTML = score + 5;
}
function west(){
    var message='You are now the bathroom';
    alert(message);
    document.getElementById("score").innerHTML = score + 10;
}
function east(){
    var message='You are now your bedroom ';
    alert(message);
}
function south(){
    var message='You are now in the living room';
    alert(message);
}

if(document.getElementById('north').clicked == true)
{
    document.getElementById('score') = score + 5;
}
else if(document.getElementById('west').clicked == true){
    document.getElementById('score') = score + 5;
}
</script>
</head>
<body>
<div id='wrap' />
    <header>
        <h1> Exploring New Apartment </h1>
    </header>
    <section>
        <article id='textarea'>
            <textarea  cols='30' rows='5' placeholder='You are currently the living room'></textarea>
            <br />
            <strong> Score: </strong> <p id='score' style="display:inline">0</p>
        </article>
        <article>
            <div>
            <input type='button' value="north" onclick='north()' id='north'/>
            <br />
            <input type='button' value='west' onclick='west()' />
            <input type="button" value='east' onclick='east()'/>
            <br />
            <input type='button' value='south' onclick='south()'/>
        </article>
    </section>
    <footer>
        <p> <a href="mailto:tenkdarko@gmail.com"> Contact Us Via Email </a>
    </footer>

</div>
</body>
</html>

我认为这可能是因为您没有在函数之外声明分数变量,所以它们可能存储在本地,但我不确定

为了好玩,我开始了一个更深入的项目,所以我知道这里发生了什么。

首先,你打错了比分。它是一个javascript变量,因此与其像HTML元素那样调用它,不如将其作为javascript变量来调用。

更改此项:

document.getElementById("score").innerHTML = score + 5;

对此:

score = score + 5;

简单多了。但是,您需要添加一个函数来更改#score,以便随着score变量的更改而更改。对不起,我的知识太有限,无法帮助你完成这项工作。

现在,为了只在一个地方没有去过的情况下增加分数,你需要添加一个变量来说明一个地方是否去过,并添加一个if语句来计算分数。像这样(对于北方):

var score = 0;
var beenNorth = false;
function north(){
    var message = 'You are now in the kitchen';
    alert(message);
    if (beenNorth == false) {    //If you have not been north, do this:
        score = score + 5;
        }
    beenNorth = true;    //Yes, I have been north
}

显然,您必须为每个房间(N、S、E和W)添加一个变量。

但是像这样只有四个房间的游戏有点无聊。我建议使用基于坐标的系统,变量起始为:

location = [0,0]

使用if语句对位置[0]或位置[1]进行加法或减法运算,模拟坐标平面。