-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
84 lines (70 loc) · 1.66 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Defining HTML Elements
const board = document.getElementById("game-board")
// game Variables
let gridSize = 20;
let snake = [{x:10,y:10}]
let food = generateFood()
let direction = "right";
//drawing board map, snake, food
function draw(){
board.innerHTML = "";
drawSnake();
drawFood();
}
//snake
function drawSnake(){
snake.forEach((segmemt)=>{
const snakeElement = createGameElement("div","snake")
setPosition(snakeElement, segmemt);
board.appendChild(snakeElement)
})
}
//Food
function drawFood(){
const foodElement = createGameElement ("div", "food");
setPosition(foodElement, food)
board.appendChild(foodElement)
}
//generate food
function generateFood(){
const y = Math.floor((Math.random()*gridSize )+1);
const x = Math.floor((Math.random()*gridSize )+1);
return {x,y};
}
// create a snake and food cube/div
function createGameElement(tag, className){
const element = document.createElement(tag);
element.className = className;
return element;
}
//set the position to snake and food
function setPosition(element, position){
element.style.gridColumn = position.x;
element.style.gridRow = position.y;
}
//moving the snake
function move(){
const head = {...snake[0]};
switch (direction) {
case "up":
head.y--;
break;
case "down":
head.y++;
break;
case "right":
head.x++;
break;
case "left":
head.x--;
break;
}
snake.unshift(head);
snake.pop();
}
//testing the move function
// setInterval(() => {
// move();
// draw();
// }, 200);
draw()