JavaScript--(snake game)

Source: Internet
Author: User
Tags button type event listener

Interface settings

/***body**/

<body>

/***score Record scores **/

<p id= "Score" >0</p>

/*** Map **/

<div id= "Snake_map" >

/*** map is drawn through JS to achieve **/

</div>

/*** three buttons **/

<div class = "box" >

<button type= "button" name= "button" id= "reset" > Restart </button>

<button type= "button" name= "button" id= "Createspeed" > Speed </button>

<button type= "button" name= "button" id= "Stop" > Pause </button>

</div>

</body>

/***body Partial End **/

/***style**/

<style>

* {

margin:0;

padding:0;

}

H1 {

Text-align:center;

}

#score {

Text-align:center;

Font-size:2em;

}

#snake_map {

/*** width and height through JS implementation **/

margin:0 Auto;

BORDER:1PX Solid RGB (196, 231, 232);

Background:rgb (31, 169, 156);

}

/*** the row style of a path map **/

. Row {

height:20px;

}

. Cell {

height:20px;

width:20px;

Box-sizing:border-box;

border:1px solid lightgray;

Float:left;

}

The style of/*** snake body **/

Activesnake {

/*** snake body and randomly appearing small squares through the JS implementation **/

Background:rgb (10, 75, 70);

}

. Mask {

Background:rgb (106, 249, 184);

}

. box {

width:300px;

Margin:auto;

margin-top:15px;

}

. Box button {

BORDER:1PX solid blue;

width:80px;

height:30px;

Background:rgb (31, 169, 156);

}

</style>

/***style Partial End **/

/***javascript**/

<script type= "Text/javascript" >//or external import

/*** gets the label element **/

var score = document.getElementById (' score ');

var map = document.getElementById (' Snake_map ');

/*** in order to dynamically change the size of the map, the following two variables are set to store the number of rows and columns (that is, the number of squares) **/

var rowNumber = 30;//number of rows

var cellnumber = 20;//Number of columns

/*** Setting the width and height of the map **/

var mapwidth = Cellnumber * 20;

var mapheight = RowNumber * 20;

Map.style.width = mapwidth + ' px ';

Map.style.height = mapheight + ' px ';

/***speed is the time parameter in the timer **/

var speed = 300;

/*** creates a two-dimensional array that records the position of all the div on the map **/

var snakedivposition = [];

/*** creates a MAP element with a double for loop **/

for (var i = 0; i < RowNumber; i++) {

/*** Creating Rows div**/

var rowdiv = document.createelement (' div ');

/***CSS style settings **/

Rowdiv.classname = ' Row ';

/*** add a line div to the path map **/

Map.appendchild (ROWDIV);

/*** creates a row series group to store each div block in the current row **/

var rowarray = [];

for (var j = 0; J < Cellnumber; J + +) {

/*** creates a column element in each row **/

var celldiv = document.createelement (' div ');

/***CSS style settings **/

Celldiv.classname = ' cell ';

/*** adds a column element to the current row **/

Rowdiv.appendchild (CELLDIV);

/*** adds a block to the row array at the same time **/

Rowarray.push (CELLDIV);

}

/*** the current inner loop ends, add the row array to the two-dimensional array **/

Snakedivposition.push (Rowarray);

}

/*** creating a snake body model **/

/*** creates a one-dimensional array to store the length of the snake body **/

var snake = [];

/*** the starting length of the fixed snake body **/

for (var i = 0; i < 3; i++) {

/*** set the color style for the snake body **/

Snakedivposition[0][i].classname = ' cell Activesnake ';

/*** stored in an array of snakes **/

Snake[i] = Snakedivposition[0][i];

}

/*** define variables to control the snake body **/

/*** The starting position offset of the snake head **/

var x = 2;

var y = 0;

/*** Fractional Timer **/

var scorecount = ' 0 '

/*** records the location of a randomly occurring small square **/

var maskx = 0;

var Masky = 0;

/*** records the direction of movement of the snake body, initially to the right **/

var direction = ' right ';

/*** is used to determine if a snake's moving direction needs to be changed **/

var changedir = true;

/*** Delay Timer **/

var delaytimer = null;

/*** Add a keyboard event listener direction key to change the direction of the snake's movement **/

Document.onkeydown = function (event) {

/*** determine if you need to change the direction true (required) false (not required) **/

if (!changedir) {

Return;//return NULL represents a direct end function, and subsequent code does not execute

}

/*** Get Event **/

event = event| | window.event;

/*** in order to properly handle the movement of snakes, it is necessary to judge the snake head and snake body *

* If the snake moves to the right, the left and right keys are invalid */

if (Direction = = ' Right ' && event.keycode = = 37) {

Return

}

if (direction = = ' Left ' && event.keycode = = 39) {

Return

}

if (direction = = ' up ' && event.keycode = = 40) {

Return

}

if (direction = = ' Down ' && event.keycode = = 38) {

Return

}

/*** determines the direction of movement of the snake by KeyCode **/

Switch (event.keycode) {

Case 37:

Direction = ' Left ';

Break

Case 38:

Direction = ' up ';

Break

Case 39:

Direction = ' right ';

Break

Case 40:

Direction = ' down ';

Break

}

Changedir = false;

Delaytimer = SetTimeout (function () {

/*** set Whether you need to change direction **/

Changedir = true;

},speed);

}

/***movetimer Get Timer **/

var Movetimer;

/*** Game starts running **/

function Change () {

Movetimer = setinterval (function () {

/*** Off Delay Timer *

* Set the position of the snake head according to the direction of direction setting **/

switch (direction) {

Case ' left ':

x--;

Break

Case ' right ':

x + +;

Break

Case ' up ':

y--;

Break

Case ' down ':

y++;

Break

}

/*** determine if the game is over **/

if (x < 0| | x >= cellnumber | | y < 0| | y >= rowNumber) {

Alert (' Game Over ');

/*** End Snake Move Timer **/

Clearinterval (Movetimer);

return;/*** terminating keyboard Events **/

}

/*** judge whether to touch oneself **/

for (var i = 0; i < snake.length; i++) {

/*** will then compare the position of the snake head to the position of the div that made up the snake at this point, and if the same, the game ends **/

if (snake[i] = = Snakedivposition[y][x]) {

Alert (' Game Over ');

Clearinterval (Movetimer);

Return

}

}

/*** determine if the position of the snake head is mask**/

if (maskx = = x && Masky = = y) {

Snakedivposition[masky][maskx].classname = ' cell Activesnake ';

/*** Snake Head Add div**/

Snake.push (Snakedivposition[masky][maskx]);

/*** Record score **/

scorecount++;

/*** Update current score **/

score.innerhtml = Scorecount;

/*** random generation of new mask**/

Createmask ();

} else {

/*** Let the snake move, the tail of the snake to remove its own color, into the color of the lattice **/

Snake[0].classname = ' cell ';

/*** remove the tail div from the array **/

Snake.shift ();

/*** navigates to the new serpent head added to the serpent array **/

Snakedivposition[y][x].classname = ' cell Activesnake ';

Snake.push (Snakedivposition[y][x]);

}

},speed);

}

/*** defining random Functions **/

function Random (Min,max) {

Return Math.floor (Math.random () * (max-min+1) + min);

}

function Createmask () {

/*** randomly generates the new mask's X-value and y-value **/

maskx = random (0,cellnumber-1);

Masky = random (0,rownumber-1);

/*** if the coordinates of a randomly generated mask are **/on the snake,

if (Snakedivposition[masky][maskx].classname = = ' cell Activesnake ') {

/*** Regenerate **/

Createmask ();

} else {

Snakedivposition[masky][maskx].classname = ' cell mask ';

}

}

Change ();

Createmask ();

</script>

JavaScript--(snake game)

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.