-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
120 lines (103 loc) · 2.69 KB
/
index.html
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<html>
<head>
<style>
body{
font-family: 'Comic Sans MS';
}
</style>
<title>Try hard snake!!</title>
</head>
<body>
<canvas style="border: 1px solid black;" id="playground" width="400" height="400">
</canvas>
<h4> Score: <span id="scoreSpan"> 0 </span></h4>
<button onClick="window.location.reload();">Try again</button>
<br/>
<small>To play use the arrow keys of your keyboard</small>
</body>
<script>
var scoreLabelElement =document.getElementById('scoreSpan');
var canvas = document.getElementById("playground");
var ctx = canvas.getContext('2d');
var direction = [1, 0] // defaults right
var snakeFood = []
var currentScore = 0;
var snake = [
[2, 0],
[1, 0],
[0, 0],
]
var game = (function(el){
return {
set score(value){
el.textContent = value
},
get score(){
return el.textContent
}
};
})()
ctx.scale(10, 10);
document.addEventListener("keydown", function (e) {
if (e.which == 38 ) { // up
direction = [0, -1]
} if (e.which == 40 ) { //down
direction = [0, 1]
} if (e.which == 39 ) { //right
direction = [1, 0]
} if (e.which == 37 ) { // left
direction = [-1, 0]
}
})
function generateFood() {
let newX = Math.round(Math.random() * (40))
let newY = Math.round(Math.random() * (40))
if(snake.find(([x,y])=> x == newX && y == newY)){
generateFood()
}else{
snakeFood = [newX, newY]
}
}
function defeat() {
clearInterval(game);
ctx.clearRect(0, 0, 400, 400);
ctx.font = "6px Comic Sans MS";
var gradient = ctx.createLinearGradient(0, 0, 20, 20);
gradient.addColorStop(0, "rgb(255, 0, 0)");
gradient.addColorStop(1, "rgb(255, 255, 0)");
ctx.fillStyle = gradient;
ctx.textAlign = "center";
ctx.fillText("You lose :(", 20, 20);
}
function print() {
ctx.clearRect(0, 0, 400, 400);
ctx.fillStyle = "red"
ctx.fillRect(snakeFood[0], snakeFood[1], 1, 1)
ctx.fillStyle = "black"
snake.forEach(([x, y]) => {
ctx.fillRect(x, y, 1, 1)
})
}
generateFood();
print();
var game = setInterval(() => {
const currentX = snake[0][0] + direction[0];
const currentY = snake[0][1] + direction[1];
if(snake.find(([x,y])=> x == currentX && y == currentY)){
return defeat();
}
if((currentX > 39 || currentX < 0)|| (currentY> 39 || currentY < 0)){
return defeat()
}
snake.unshift([currentX, currentY])
if (currentX == snakeFood[0] && currentY == snakeFood[1]) {
generateFood()
currentScore++
scoreLabelElement.textContent = currentScore
} else {
snake.pop()
}
print();
}, 100);
</script>
</html>