How to Build a Snake Game In JavaScript
This snake game that is played automatically by a Javascript rather than by a human player. The snake's movements would be determined by an algorithm, rather than being controlled by the player.The objective of the game is to navigate the snake and eat food items that appear on the screen. As the snake consumes food, it grows longer. The game becomes progressively more challenging as the snake grows longer, making it harder to navigate without self-collision.You can get the complete code from Github
The snake game typically consists of the following elements:
Board: Playing area where the game is played. It provides the boundaries within which the snake moves and the food items are placed.
Snake: It moves around the screen, eating food and growing longer as it does so. The snake usually consists of a series of connected squares or circles that move as a single unit.
Food (Apple): The snake needs to eat food to survive and grow longer. Food items are usually represented by small dots or icons that appear randomly on the screen.
Score: Each earning score will be list on top of the snake.
Game over: The game ends when the snake collides with its own body.
Actually we can simply to watch the snake move and see how long it can survive without crashing into own body.
Write three Div elements (board,snake & apple) in this below file.
snake.html
1 <html>
2 <head>
3 <meta charset = "utf-8"/>
4 <title>Snake Games</title>
5 <link rel="stylesheet" href="style.css"/>
6 </head>
7 <body>
8 <center>
9 <div id="board">
10 <div id="apple"></div>
11 <div class="snake"></div>
12 </div>
13 </center>
14 </body>
15 </html>
16 <script src="action.js"></script>
This file only decide how snake can move and where apple should be appear in the board.
Alter this value blockSize = 30 if you want to change the size of apple and snake, remaining default values can alter in style.css file.
action.js
1 var boardobj;
2 var appleobj;
3 var snakeobj;
4 var runobj;
5 var newobj;
6
7 var snakeLength = 0;
8 // Default width & height for both Snake and Apple (Note you change the board width and height in style.css file)
9 var blockSize = 30;
10 var nextMoveAllow = 1;
11
12 var temp = 0;
13 var tempSnakeLeft;
14 var tempSnakeTop;
15 var secondTemp = 0;
16 var thirdTemp = 0;
17
18 var boardTop;
19 var boardLeft;
20 var appleTop;
21 var appleLeft;
22 var snakeTop;
23 var snakeLeft;
24
25 var totalBox = 0;
26
27 function start() {
28 //Create object for board, apple and snake elements
29 boardobj = document.getElementById("board");
30 appleobj = document.getElementById("apple");
31 snakeobj = document.getElementById("board").getElementsByClassName("snake");
32
33 //Set apple default width & height
34 appleobj.style.width = blockSize+"px";
35 appleobj.style.height = blockSize+"px";
36
37 //Set Snake(head portion) default width & height
38 snakeobj[0].style.width = blockSize+"px";
39 snakeobj[0].style.height = blockSize+"px";
40
41 //Calculate the correct board width and height
42 boardLeft = boardobj.offsetWidth;
43 temp = boardLeft%blockSize;
44 if(temp != 0) {
45 boardLeft = boardLeft - temp;
46 }
47 totalBox = boardLeft/blockSize;
48
49 boardTop = boardobj.offsetHeight;
50 temp = boardTop%blockSize;
51 if(temp != 0) {
52 boardTop = boardTop - temp;
53 }
54 totalBox = totalBox * (boardLeft/blockSize);
55
56 //Set the correct board
57 boardobj.style.width = boardLeft;
58 boardobj.style.height = boardTop;
59
60 //Set Snake(head portion) in default position
61 snakeobj[0].style.top = "0px";
62 snakeobj[0].innerHTML = snakeLength;
63 snakeobj[0].style.left = "0px";
64 //Set Snake head color
65 snakeobj[0].style.backgroundColor = "#539165";
66 snakeobj[0].style.border = "initial";
67 applelocation();
68 }
69
70 function run() {
71 //Find the Snake(head portion) top and left position
72 snakeTop = snakeobj[0].style.top;
73 snakeTop = snakeTop.replace("px","");
74 snakeTop = parseInt(snakeTop);
75
76 snakeLeft = snakeobj[0].style.left;
77 snakeLeft = snakeLeft.replace("px","");
78 snakeLeft = parseInt(snakeLeft);
79
80 //Both Snake and Apple top position is same, so Snake should find whether it move to left or right side
81 if(snakeTop == appleTop || snakeLeft < appleLeft || snakeLeft > appleLeft) {
82 if(snakeLeft < appleLeft)
83 { snakeLeft = snakeLeft + blockSize; }
84 else
85 { snakeLeft = snakeLeft - blockSize; }
86
87 if(snakeLeft < 0)
88 { snakeLeft = boardLeft-blockSize; }
89 else if(snakeLeft == boardLeft)
90 { snakeLeft = 0; }
91
92 if(snakeTop == appleTop && snakeLeft == appleLeft) //Apple will eat by snake, if both are same position
93 { eat(); }
94 else
95 { follow(); }
96 }
97 else if(snakeLeft == appleLeft || snakeTop < appleTop || snakeTop > appleTop) { //Both Snake and Apple left position is same, so Snake should find whether it move to up or down side.
98 if(snakeTop < appleTop)
99 { snakeTop = snakeTop + blockSize; }
100 else
101 { snakeTop = snakeTop - blockSize; }
102
103 if(snakeTop < 0)
104 { snakeTop = boardTop-blockSize; }
105 else if(snakeTop == boardTop)
106 { snakeTop = 0; }
107
108 if(snakeTop == appleTop && snakeLeft == appleLeft) //Apple will eat by snake, if both are same position
109 { eat(); }
110 else
111 { follow(); }
112 }
113 }
114
115 function eat() {
116 snakeLength = snakeLength + 1;
117 //Create new oject and attached into snake body
118 newobj = document.createElement("div");
119 newobj.innerHTML = snakeLength;
120 newobj.classList.add("snake");
121 boardobj.appendChild(newobj);
122 //Set default width, height, positions to new object
123 snakeobj[snakeLength].style.width = blockSize+"px";
124 snakeobj[snakeLength].style.height = blockSize+"px";
125 newobj.style.top = snakeobj[snakeLength-1].style.top;
126 newobj.style.left = snakeobj[snakeLength-1].style.left;
127
128 //Snake start move
129 follow();
130
131 //Generate new Apple in random location
132 applelocation();
133 }
134
135 function applelocation() {
136 thirdTemp = 1;
137 //New apple position is examine in board size.That position should be empty not occupied by any snake bodies
138 while(thirdTemp <= totalBox) {
139 appleTop = Math.floor(Math.random * boardTop - blockSize + 1);
140 temp = appleTop%blockSize;
141 if(temp != 0) {
142 appleTop = appleTop - temp;
143 }
144 appleLeft = Math.floor(Math.random * boardLeft - blockSize + 1);
145 temp = appleLeft%blockSize;
146 if(temp != 0) {
147 appleLeft = appleLeft - temp;
148 }
149
150 //Check new Apple position is match within any of snake bodies, if it match again new apple positions will calculated.
151 secondTemp = snakeLength;
152 while(secondTemp > 0) {
153 if(snakeobj[secondTemp-1].style.left == appleLeft+"px" && snakeobj[secondTemp-1].style.top == appleTop+"px") {
154 break;
155 }
156 secondTemp--;
157 }
158
159 //Assign new position to apple
160 if(secondTemp == 0) {
161 appleobj.style.top = appleTop+"px";
162 appleobj.style.left = appleLeft+"px";
163 break;
164 }
165 thirdTemp++;
166 }
167 if(secondTemp != 0) {
168 clearInterval(runobj);
169 alert("No Space found for Apple !");
170 }
171 }
172
173
174 function follow() {
175 if(snakeLength >= 1) {
176 nextMoveAllow = 1;
177 temp = snakeLength;
178 while(temp > 0) {
179 if(snakeobj[temp-1].style.left == snakeLeft+"px" && snakeobj[temp-1].style.top == snakeTop+"px") {
180 checkothermove();
181 break;
182 }
183 temp--;
184 }
185
186 if(nextMoveAllow == 1) { //In place Snake start moving one position
187 temp = snakeLength;
188 while(temp > 0) {
189 snakeobj[temp].style.left = snakeobj[temp-1].style.left;
190 snakeobj[temp].style.top = snakeobj[temp-1].style.top;
191 temp--;
192 }
193 }
194 else
195 {
196 snakeobj[0].classList.add("clash");
197 snakeobj[temp-1].classList.add("clash");
198 clearInterval(runobj);
199 alert("Snake Crashed");
200 }
201 }
202 snakeobj[0].style.left = snakeLeft+"px";
203 snakeobj[0].style.top = snakeTop+"px";
204 }
205
206 //Find the Snake new position to move then only it can eat the Apple
207 function checkothermove() {
208 secondTemp = 1;
209 snakeTop = snakeobj[0].style.top;
210 snakeTop = snakeTop.replace("px","");
211 snakeTop = parseInt(snakeTop);
212
213 snakeLeft = snakeobj[0].style.left;
214 snakeLeft = snakeLeft.replace("px","");
215 snakeLeft = parseInt(snakeLeft);
216
217 while(secondTemp <= 4) {
218 nextMoveAllow = 1;
219 tempSnakeLeft = snakeLeft;
220 tempSnakeTop = snakeTop;
221
222 if(secondTemp == 1)
223 { tempSnakeTop = tempSnakeTop + blockSize } //Downward
224 else if(secondTemp == 2)
225 { tempSnakeTop = tempSnakeTop - blockSize } //Upperward
226 else if(secondTemp == 3)
227 { tempSnakeLeft = tempSnakeLeft + blockSize } //Right Side
228 else if(secondTemp == 4)
229 { tempSnakeLeft = tempSnakeLeft - blockSize } //Left Side
230
231 if(0 <= tempSnakeLeft && tempSnakeLeft < boardLeft && 0 <= tempSnakeTop && tempSnakeTop < boardTop) {
232 temp = snakeLength;
233 while(temp > 0) {
234 if(snakeobj[temp-1].style.left == tempSnakeLeft+"px" && snakeobj[temp-1].style.top == tempSnakeTop+"px") {
235 nextMoveAllow = 0;
236 break;
237 }
238 temp--;
239 }
240 if(nextMoveAllow == 1) {
241 snakeLeft = tempSnakeLeft;
242 snakeTop = tempSnakeTop;
243 break;
244 }
245 }
246 else
247 {
248 nextMoveAllow = 0;
249 }
250 secondTemp++;
251 }
252 }
253
254 //Script Starting Point
255 start();
256 var runobj = setInterval(run,100);
Apply styles to elements.
style.css
1 body {
2 margin:0px;
3 padding:0px;
4 }
5
6
7 #board {
8 /* Board Width & Height */
9 width:80%;
10 height:80%;
11 position:relative;
12 background:#222831;
13 border:2px solid #E5D9B6;
14 margin:5px;
15 }
16
17 .snake {
18 position:absolute;
19 vertical-align:middle;
20 /* Snake Color */
21 background-color:#CDE990;
22 border:2px solid #AACB73;
23 box-sizing:border-box;
24 }
25
26 #apple {
27 position:absolute;
28 /* Apple Color */
29 background-color:#ED2B2A;
30 border:2px solid #D21312;
31 box-sizing:border-box;
32 }
33
34 .clash {
35 background-color:#ffffff;
36 }
No comments:
Post a Comment