JavaScript: implements a mouse-hitting game and javascript mouse-hitting

Source: Internet
Author: User

JavaScript: implements a mouse-hitting game and javascript mouse-hitting

First, you need to know what to do in each step.
Then, we will build a framework step by step and then improve the functions.

1. Create three rows and three columns of the table to store pitfalls (images)
2. Obtain all image tags
3. The mouse moves...
4. ②. The mouse is running
5. ③. The mouse was killed.
6. Improved Functions

1. First, implement the first step: Create a three-row and three-column pitfall with table

<Div id = "content"> 

The next step is to write js functions.

2. First, obtain a set of all pitfalls

Var image = document. getElementsByTagName ('img ');

3. mouse actions:①. Come out

The mouse has to get a random pitfall, and then replace the pitfall image with that of the hamster.
Then, bind each mouse to a click event. Then either the die () function is killed. Or call the paole () function at intervals.

function chulai(){ ranK = Math.floor(Math.random() * 9); image[ranK].src = "./images/dishu.gif"; image[ranK].style.marginTop = "0px"; image[ranK].setAttribute("onclick","die()"); setTimeout("paole()", Math.random()*400+800);}

4. mouse actions:②. The mouse ran very lucky.
If the mouse runs this function, make some changes. First, replace the image with the default pitfall image. Then, remove the click Event bound to it. Finally, continue to call the mouse's function, chulai ();

function paole(){ image[ranK].src = "./images/keng.gif"; image[ranK].style.marginTop = "31px"; image[ranK].removeAttribute("onclick"); setTimeout("chulai()", Math.random()*400+800);}

5. mouse actions:3. The mouse was unfortunately killed by us.
The mouse must perform the following changes to execute the event, and also remove the click event from the mouse to change its image to an injured image.

function die(){ image[ranK].src = "./images/shang.gif"; image[ranK].removeAttribute("onclick"); image[ranK].style.marginTop = "3px"; }

After writing the above Code, it seems that there is a complete function, but it cannot be executed. Because there is no entry function, that is, the mouse function should be called. Of course, this function should also be in Math. the random time of random () is called, that is, the integrated code is as follows.

<Script type = "text/javascript"> // 1 first, get all pitfalls (images) var image = document. getElementsByTagName ('img '); var ranK; // call the entry function setTimeout ("chulai ()", Math. random () * 400 + 800); // Let the mouse randomly appear in a pit function chulai () {ranK = Math. floor (Math. random () * 9); image [ranK]. src = ". /images/dishu.gif "; image [ranK]. style. marginTop = "0px"; image [ranK]. setAttribute ("onclick", "die ()"); setTimeout ("paole ()", Math. random () * 400 + 800);} // 2 the mouse went back to function paole () {image [ranK]. src = ". /images/keng.gif "; image [ranK]. style. marginTop = "31px"; image [ranK]. removeAttribute ("onclick"); setTimeout ("chulai ()", Math. random () * 400 + 800);} // 3 the mouse was killed by function die () {image [ranK]. src = ". /images/shang.gif "; image [ranK]. removeAttribute ("onclick"); image [ranK]. style. marginTop = "3px" ;}</script>

After setting the css style, you can execute it perfectly. As follows.

The above body code has been completed. Next, add the function.

Add function 1. record the number of rats killed currently

If you want to add the counting function, define a div block in the body to display the string of the number of rats killed currently. Here we set id to score. Define another variable count to record the number of rats killed currently. Run count ++ in the die () function.
Some code is as follows:

function die(){ image[ranK].src = "./images/shang.gif"; image[ranK].removeAttribute("onclick"); image[ranK].style.marginTop = "3px"; count++; score.innerHTML =count; }

As follows:

Add function 2. Save the best history

To save the best history, use the local storage object. Here we mainly use
LocalStorage. setItem ("key name", "value"), stores the value as a key-value pair to the local device. LocalStorage. getItem ("key name"); obtain the value through the key name.

Here we only need to use var preScore = localStorage. getItem ("key name") obtains the best history record and compares it with the current count. If preScore is greater than the current count, the best history record is not updated. If preScore is smaller than the current count, make preScore = count; then store the game after the current round ends.

Add function 3. Set the countdown timer to control the end of the game

So when can the current round of game end, it is necessary to set a timer. Here I wrote a one-minute countdown timer. When sencond is equal to 0, the game ends and
LocalStorage. setItem ("bestScore", preScore.
The code for adding Feature 2 and feature 3 is as follows:

Function die () {try {image [ranK]. src = ". /images/shang.gif "; image [ranK]. removeAttribute ("onclick"); image [ranK]. style. marginTop = "3px"; count ++; score. innerHTML = count; if (count> preScore) {score1.innerHTML = count; preScore = count;} localStorage. setItem ("bestScore", preScore);} catch (ex) {}}// set a timer var seconds = 59; var speed = 1000; function countDown (seconds, speed) {var txt = "remaining time:" + (se Conds <10 )? "0" + seconds: seconds) + "second"; div. innerHTML = txt; var timeId = setTimeout ("countDown (seconds --, speed)", speed); // if the time reaches if (seconds = 0) {// store the best record, whether or not the record localStorage is broken. setItem ("bestScore", preScore); clearTimeout (timeId); if (cover. style. display = "none") {cover. style. display = "block"; // if (count = undefined) text is displayed if no mouse is hit. innerHTML = "Current score:" + 0 + "+" <br/> "+" the game is over! "; // Exceeds the historical record. The current count value is used when localStorage. getItem (" bestScore ") is saved. Else if (count = localStorage. getItem ("bestScore") {text. innerHTML = "Current score:" + count + "score" + "<br/>" + "Congratulations!" + "<br/>" + "the game is over! ";} Else text. innerHTML =" Current score: "+ count +" + "<br/>" + "the game is over! ";}}} CountDown (seconds, speed );

As follows:

Complete source code is attached.

<! DOCTYPE html> 

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.