2015-05-13 4 views
-2

Я создаю комбинационную игру в JavaScript (соответствие правильных животных имен принтов животных), и я застрял на одном последний бит ..JavaScript игра - счет на отдельной странице

Я хочу, чтобы счет, который вы можете см. добавление, когда вы идете вперед, чтобы появиться на другой веб-странице. Как бы я это сделал, поскольку, когда я удаляю div 'score' из html-страницы, он все развращает.

Любая помощь была бы принята с благодарностью.

Heres код ..

<html> 



<head> 
<Script> 

function randSort (a,b) {return Math.random() - 0.5} 

var questions = [ 
{text: " What animal is this?", img: "AnimalPrints/1.jpg", answers: ["Cheetah", "Tiger", "Ladybird"], ans: "0"}, 

{text: " What animal is this one?", img: "AnimalPrints/2.jpg", answers: ["Elephant", "Giraffe", "Snake"], ans: "1"}, 

{text: "What animal is this one please?", img: "AnimalPrints/3.jpg", answers: ["Bumblebee", "Tiger", "Lady bird"], ans: "2"}, 


{text: "What animal is this one please?", img: "AnimalPrints/4.jpg", answers: ["Tiger", "Parrot", "Snake"], ans: "1"}, 

{text: "What animal is this one please?", img: "AnimalPrints/5.jpg", answers: ["Bumblebee", "Tiger", "Lady bird"], ans: "2"}, 

{text: "What animal is this one please?", img: "AnimalPrints/6.jpg", answers: ["Peacock", "Cow", "Zebra"], ans: "2"}, 

{text: "What animal is this one please?", img: "AnimalPrints/7.jpg", answers: ["Snake", "Ladybird", "Pig"], ans: "0"}, 

{text: "What animal is this one please?", img: "AnimalPrints/8.jpg", answers: ["Cat", "Bat", "Peacock"], ans: "2"}, 

{text: "What animal is this one please?", img: "AnimalPrints/9.jpg", answers: ["Cow", "Horse", "Parrot"], ans: "2"}, 

{text: "What animal is this one please?", img: "AnimalPrints/10.jpg", answers: ["Bumblebee", "Tiger", "Lady bird"], ans: "0"} 

]; 

var correctCount = 0; 
var currentQ = 0; 


function select(nr) { 


if (nr == questions[currentQ].ans) 
{ 
correctCount++; 
document.getElementById('display').innerHTML= "You win" 
} 
else 
{ 
    document.getElementById('display').innerHTML= "You lose" 
} 





document.getElementById('display').innerHTML += "<p>Score: "+ correctCount; 

// if its the last one 



nextQ(); 

} 

function showQ() { 


document.getElementById('questionText').innerHTML = questions[currentQ].text; 

document.getElementById('animalPrint').src = questions[currentQ].img; 


newhtml = ""; 
for (var i = 0; i< questions[currentQ].answers.length; i++) 
{ 
newhtml+= "<button onclick = 'select(" + i + ")'>"+ questions[currentQ].answers[i] + "</button>"; 

} 

document.getElementById('alloptions').innerHTML = newhtml; 

} 


function nextQ(){ 

if (currentQ < questions.length-1) 
{ 
currentQ++; 

showQ(); 
} 

} 


window.onload =init; 


function init() 
{ 
correctCount = 0; 
questions.sort(randSort); 
currentQ = 0; 
showQ(); 

} 



</script> 
<title> Game_page</title> 


<link rel="stylesheet" type="text/css" href ="gamepage_css.css"> 


       <script type = "text/javascript"> 
/* 
       document.write("<img src = \ "" + Math.floor 1 + Math.random() * 10) + 
       ".jpg\" />"); 



       document.write("<img src = \"" + Math.floor 1 + Math.random() *) 
*/    

       </script> 


</head> 



<body> 

<div id = "main"> 




<div id = "questionText"> Testing</div> 

<div id ="animal"> 

<img id = "animalPrint" src = "AnimalPrints/1.jpg"> 

</div> 

<div id = "alloptions"> 





        </div> 


<button id = "nextbutton" onclick = "nextQ();"> 



      </button></a> 


     </div> 



<div id = "display"> Score: </div> 

</body> 









</html> 

CSS

body { 



    background-position: center; 
    background-color:lime; 


} 

#questionText { 
    width: 300px; 
    background: white; 
    font-family:verdana; 
    border-radius: 5px; 
    margin-left:150px; 
} 


#nextbutton { 
    background-image: url(Buttons/nextbutton.jpg); 
    background-size:contain; 
    background-repeat:repeat-y; 
    background-position: center; 
    width:100px; 
    height:44px; 
    margin-left: 250px; 
    border-radius:10px; 


} 


#main { 
margin-top:200px; 
margin-left:250px; 
border:1px solid red; 
width:600px; 

} 

#animalPrint{ 

    margin-left:230px; 
    margin-top: 40px; 
} 

#display { 
    width:150px; 
    height:50px; 
    background-color:blue; 
    color:white; 
    border-radius:5px; 
    font-family:aqua; 
} 

#alloptions { 
    margin-left:180px; 
    padding:30px; 
} 
+0

Возможно, вы можете использовать localStorage. Он должен хранить информацию, доступную любой веб-странице в одном домене. – Houshalter

ответ

0

Если вы хотите передать переменную на другую веб-страницу, вам нужен сервер.

Этот сервер может быть в любой технологии (узел, PHP, ...) и передать переменную, вы можете использовать запрос POST, AJAX, WebSocket ...

+0

Я только хочу использовать JavaScript для этого задания, я думал, что могу просто связать его с другой веб-страницей или что-то в этом роде? (извините, я так новичок в этом) – MysteryX

0

Ваш игровой код и CSS не относящийся к вопросу, в будущем, пожалуйста, попробуйте вставить соответствующий фрагмент в ваш вопрос.

Самое простое решение для вас - сохранить счет в локальном хранилище, что позволит его читать, когда страница обновляется или когда вы перенаправляетесь на другую страницу, предполагая, что новая страница имеет тот же домен, т.е. часть URL-адреса между «http: //» и первым «/».

когда новая игра начинается сделать

localStorage["score"] = 0 

, когда вы увеличиваете счет разобрать его в целое (так как она держит только строки) и добавить к нему:

localStorage["score"] = parseInt(localStorage["score"],10) + 50 

при перенаправлять оценка страницы:

document.getElementById('scoreDiv').innerHTML = "Your score is "+localStorage["score"] + " points!"; 
Смежные вопросы