2015-02-17 114 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],模擬的座標平面。