2015-02-17 116 views
0

我开始使用JavaScript,通过在网上找到简单的项目来练习/提高我的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:[email protected]"> Contact Us Via Email </a> 
    </footer> 


</div> 

</body> 
</html> 
+0

你似乎没有在任何地方定义'score'变量。 – 2015-02-17 20:28:35

回答

0

我想可能是因为你没有申报的功能外比分变量,所以他们可能会被存储在本地,但林不知道

+0

没有任何声明或分配给它 - 它不会被存储在任何地方,它是未定义的。 – 2015-02-17 21:27:01

0

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

首先,你打电话给分数错了。这是一个JavaScript变量,因此不要将其称为HTML元素,而应将其称为JavaScript变量。

更改此:

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

要这样:

score = score + 5; 

简单得多。但是,您需要添加一个函数来更改#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],模拟的坐标平面。