Renderings: p1-jj.byteimg.com/tos-cn-i-t2…
Initialize (){initialize game board and game score display area make snake () make bean () listen keyboard ()} Make snake (){loop snake initialize length times {create new joints for snakes, Each joint is a div snake head turned red snake's new joint push the array snake's new joint left distance from the previous snake joint left snake's new joint is displayed on the panel}} Make beans (){if(old beans exist){remove old beans from the game board} Create new beans, each bean is a span call random coordinates (), Generate birth coordinates for the new bean random coordinates (){panel width 1000 divided by 20 (bean width 20px), equally divided into 500 parts multiplied by a random number and rounded to give an integer from 0 to 500 multiplied by 20 to give an integer multiple of 20 in the range from 0 to 1000, Traverses the snake joint array {if(conflicts with the current bean coordinate){random coordinate (); }}} for the assignment of the new crop horizontal ordinate Will be appended to the panel of the new crop monitored the keyboard () {} in the press the left key: when not for the right direction, the direction to the left Press the on button: when the direction is not for the direction instead According to the right: when the direction to the left, to the right direction Press the next button: when not on for direction, the direction is changed to next Press the space bar: Pause and start game effect switch} Game start (){clear old timer start new timer {snake move () bump yourself () : judge whether this move snake bump into his eating beans () : Judge whether the snake gets dots}} Snake movement (){get the left distance and the upper distance of the snake head to judge the current snake movement direction {if(the corresponding direction is out of bounds){end of the game ()} snake body movement () snake head movement} snake body movement (){loop all snake body {the back joints horizontally replace the front joints End game ()}}} Eat beans (){if(snake head coordinates match the current bean coordinates){score ++ create a new snake joint New snake joints are added to the array of snakes. New snake joints are displayed in the game board. Make beans ()}} End of game (){clear timer refresh page display score indicating end of game} Pause the game (){clear timer} Game reset (){refresh page}Copy the code
Layout: snake. HTML
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gluttony snake</title>
<link rel="stylesheet" type="text/css" href="snake.css">
<script type="text/javascript" src="snake.js"></script>
</head>
<body>
<header>
<article id="head_left">Gluttony snake v1.0</article>
<article id="head_right">Your current score is<span id="score">0</span> 分</article>
</header>
<section id="board"></section>
<footer>
<button class="buttons" onclick="start();">Start [start]</button>
<button class="buttons" onclick="pause();">[pause]</button>
<button class="buttons" onclick="reset();">Reset [reset]</button>
</footer>
</body>
</html>
Copy the code
Style: snake. CSS
/* Overall: center */
body {width: 1000px; margin: 0auto; }/* Scoreboard: adjust line height and margins */
header {
height: 30px; background-color: black; color: white;
line-height: 30px; margin: 10px auto;
}
/* Game title: Adjust left margin, ignore inside margin and border, float left, text slant, word spacing */
#head_left {
width: 700px; padding-left: 20px; box-sizing: border-box;
float: left; font-style: italic; letter-spacing: 10px;
}
/* Scoring tips: Adjust the right margin, ignore the margin and border, float right, text to the right */
#head_right {
width: 300px; padding-right: 20px; box-sizing: border-box;
float: right; text-align: right;
}
/* Score number: text in bold, underlined */
#score {
color: yellow; font-weight: bold; text-decoration: underline;
}
/* Game board: center, parent set to relative point */
#board {
height: 500px; background-color: black;
margin: 0 auto; position: relative;
}
/* Dots: displayed as blocks, rounded corners, Z-axis, absolute positioning */
#board span {
width: 20px; height: 20px; background-color: yellow;
display: block; border-radius: 50%;
z-index: 0; position: absolute;
}
/* Snake: rounded corners, absolute positioning, z axis */
#board div {
width: 20px; height: 20px; background-color: skyblue;
border-radius: 50%; position: absolute; z-index: 1;
}
/* Function button area: content centered */
footer { text-align: center; }
/* Function button: text color, margin */
footer .buttons{
width: 150px; height: 30px;background-color: black;
color: yellow; margin: 10px;
}
Copy the code
Script: snake. Js
let snakeArray = []; /* Initializes the array of snake joints */
let isPause = false; /* Whether the game is paused: not paused */
let snakeSize = 5; /* Initial length of snake */
let direct = "right"; /* Snake initial direction: right */
let speed = 80; /* Snake initial movement speed: 80*/
let score, timer, board, bean; /* Game initial score display area, timer, panel, bean */
// initialize (){
onload = () = > {
// Initialize the game board and game score display area
board = document.querySelector("#board");
score = document.querySelector("#score");
/ / build a snake ()
createSnake();
/ / build bean ()
createBean();
// Monitor keyboard ()
keyListener();
};
/ / build a snake () {
function createSnake() {
// Loop snake initializes length times {
for (let i = 0; i < snakeSize; i++) {
// Create new joints for the snake, each joint is a div
let snake = document.createElement("div");
// The snake's head turns red
if (i === 0) {
snake["style"] ["backgroundColor"] = "red";
}
// Snake's new joint pushes into array
snakeArray.push(snake);
// The left distance of the new snake joint is to the left of the previous snake joint
snake["style"] ["left"] = (snakeSize - i - 1) * 20 + "px";
// The snake's new joints are displayed on the panelboard.appendChild(snake); }}Made bean () {/ /
function createBean() {
// if(there are old beans){
if (bean) {
// Remove old beans from the game board
board.removeChild(bean);
}
// Create new beans, each bean is a span
bean = document.createElement("span");
let x = null, y = null;
// Call random coordinates () to generate birth coordinates for the new bean
randomXY();
// random coordinates (){
function randomXY() {
// The width of the panel is 1000 divided by 20 (beans width 20px), divided into 500 equal parts
// Multiply by a random number and round to get an integer between 0 and 500
// Multiply by 20 to get an integer multiple of 20 in the range 0-1000
// Do the same thing
x = parseInt("" + (Math.random() * (1000 / 20))) * 20;
y = parseInt("" + (Math.random() * (500 / 20))) * 20;
// walk through the snake joint array {
for (let i = 0; i < snakeArray.length; i++) {
// if(conflicts with the current bean coordinates){
if (snakeArray[i]["offsetLeft"] === x) {
if (snakeArray[i]["offsetTop"] === y) {
// random coordinates ();
randomXY();
break; }}}}// Assign the horizontal and vertical coordinates to the new bean
bean["style"] ["left"] = x + "px";
bean["style"] ["top"] = y + "px";
// Append the new bean to the panel
board.appendChild(bean);
}
// Listen to the keyboard
function keyListener() {
document.onkeydown = event= > {
let oEvent = event || window.event;
switch (oEvent.keyCode) {
case 37 :
// Press the left key: when the direction is not right, change the direction to left
if(direct ! = ="right") {
direct = "left";
}
break;
case 38 :
// Press the up key: When the direction is not down, the direction is up
if(direct ! = ="down") {
direct = "up";
}
break;
case 39 :
// Right-click: When the direction is not left, the direction is right
if(direct ! = ="left") {
direct = "right";
}
break;
case 40 :
// When the direction is not up, the direction is down
if(direct ! = ="up") {
direct = "down";
}
break;
case 32 :
// Press the space bar: pause and start the game effect toggle
if(! isPause) { pause(); }else{ start(); } isPause = ! isPause;break; }}}// Start the game (){
function start() {
// Clear the old timer
clearInterval(timer);
// Start a new timer {
timer = setInterval(() = > {
// Snake move ()
move();
// Bump yourself () : judge whether the moving snake bumps itself
isHit();
// Eat beans () : Judge whether the snake eats beans this time
isEat();
}, speed);
}
// Snake move (){
function move() {
// Get the left and upper distance of the snake head
let hLeft = snakeArray[0].offsetLeft;
let hTop = snakeArray[0].offsetTop;
// Determine the current snake movement direction {
switch (direct) {
case "left":
// if(out of bounds in the corresponding direction){
if (hLeft <= 0) {
// Game over ()
gameover();
return;
}
// Snake body move ()
snakeBodyMove();
// The snake head moves
snakeArray[0] ["style"] ["left"] = hLeft - 20 + "px";
break;
case "up":
if (hTop <= 0) {
gameover();
return;
}
snakeBodyMove();
snakeArray[0] ["style"] ["top"] = hTop - 20 + "px";
break;
case "right":
if (hLeft >= 1000 - 20) {
gameover();
return;
}
snakeBodyMove();
snakeArray[0] ["style"] ["left"] = hLeft + 20 + "px";
break;
case "down":
if (hTop >= 500 - 20) {
gameover();
return;
}
snakeBodyMove();
snakeArray[0] ["style"] ["top"] = hTop + 20 + "px";
break;
}
// Snake body move (){
function snakeBodyMove() {
// Loop all snake bodies {
for (let i = snakeArray.length - 1; i > 0; i--) {
// The back joint replaces the front joint transversely
snakeArray[i]["style"] ["left"] = snakeArray[i - 1] ["style"] ["left"];
// The back joint replaces the front joint lengthwise
snakeArray[i]["style"] ["top"] = snakeArray[i - 1] ["style"] ["top"]; }}}/* Determine if the move hit you */
function isHit() {
// Walk through all snake bodies {
for (let i = 1, j = snakeArray.length; i < j; i++) {
// if(snakehead coordinates conflict with some snakebody joint coordinates){
if (snakeArray[0].offsetLeft === snakeArray[i].offsetLeft) {
if (snakeArray[0].offsetTop === snakeArray[i].offsetTop) {
// End the game ()
gameover();
break; }}}}// Eat beans (){
function isEat() {
// if(snakehead coordinates are the same as the current bean coordinates){
if (snakeArray[0].offsetLeft === bean.offsetLeft) {
if (snakeArray[0].offsetTop === bean.offsetTop) {
/ / score + +
score.innerText = parseInt(score.innerText) + 1;
// Create a new snake joint
let snake = document.createElement("div");
// The birth coordinates of the new snake joints are the coordinates of the eaten beans
snake["style"] ["left"] = bean["style"] ["left"];
snake["style"] ["top"] = bean["style"] ["top"];
// Add a new snake joint to the snake array
snakeArray.push(snake);
// The new snake joint is displayed in the game panel
board.appendChild(snake);
/ / build bean ()createBean(); }}}// Game over (){
function gameover() {
// Empty the timer
clearInterval(timer);
// Refresh the page
location.reload();
// The game is over
alert("game over!");
}
// Pause the game (){
function pause() {
// Empty the timer
clearInterval(timer)
}
// Game reset (){
function reset() {
// Refresh the page
location.reload();
}
Copy the code
Js operations
- What is the relationship between javascript and Java?
- When was JS born? Which company was it born in?
- What was JS originally used for? What is it used for now?
- What kind of language is JS? What standards do they follow?
- Is JS an object-oriented language?
- Why is JS cross-platform?
- Where can I write the JS code?
- Is JS a strongly typed language?
- What are the three components of JS? What are their characteristics?
- Window.onload =function(){} What is the difference between writing and not writing?
- Window.onload =function(){} Does it take effect at the same time?
- How to grab a label in the DOM by id?
- Is write() a DOM operation or a BOM operation?
- Open () If you want to open a blank page, what should the path argument say?
- What is the return value of open()?
- How does close() close the upper page in a frame window?
- What’s the difference between the location.href and the open() hop?
- What is the difference between alert(), confirm() and prompt()?
- What is the return value of prompt()?
- What are the two words for mouse-over and mouse-out events?
- Odiv. backgroundColor=”red”, why not successfully change the backgroundColor?
- Function () {this};
- How to determine whether a checkbox or radio is checked in JS?
- How does JS submit a form?
- Which method can be used to add focus to input?
- What’s the difference between querySelector() and querySelectorAll()?
- How do I fetch an element by its name attribute?
- We can use function to define a method ourselves. Are the four elements of this custom method the same as in Java?
- How do I call one method from another?