Skip to content

Commit 62e56a5

Browse files
committed
feat: Menambahkan fitur 2 buah apel
1 parent 87c6ffc commit 62e56a5

1 file changed

Lines changed: 20 additions & 9 deletions

File tree

‎snake-game/index.js‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,11 @@ let snake = {
3737
direction: initDirection(),
3838
score: 0,
3939
}
40-
let apple = {
40+
let apple1 = {
41+
color: "red",
42+
position: initPosition(),
43+
}
44+
let apple2 = {
4145
color: "red",
4246
position: initPosition(),
4347
}
@@ -74,7 +78,8 @@ function draw() {
7478
for (let i = 1; i < snake.body.length; i++) {
7579
drawCell(ctx, snake.body[i].x, snake.body[i].y, snake.color);
7680
}
77-
drawCell(ctx, apple.position.x, apple.position.y, apple.color);
81+
drawCell(ctx, apple1.position.x, apple1.position.y, apple1.color);
82+
drawCell(ctx, apple2.position.x, apple2.position.y, apple2.color);
7883

7984
drawScore(snake);
8085
}, REDRAW_INTERVAL);
@@ -95,9 +100,15 @@ function teleport(snake) {
95100
}
96101
}
97102

98-
function eat(snake, apple) {
99-
if (snake.head.x == apple.position.x && snake.head.y == apple.position.y) {
100-
apple.position = initPosition();
103+
function eat(snake, apple1, apple2) {
104+
if (snake.head.x == apple1.position.x && snake.head.y == apple1.position.y) {
105+
apple1.position = initPosition();
106+
snake.score++;
107+
//this
108+
snake.body.push({x: snake.head.x, y: snake.head.y});
109+
}
110+
if (snake.head.x == apple2.position.x && snake.head.y == apple2.position.y) {
111+
apple2.position = initPosition();
101112
snake.score++;
102113
//this
103114
snake.body.push({x: snake.head.x, y: snake.head.y});
@@ -107,25 +118,25 @@ function eat(snake, apple) {
107118
function moveLeft(snake) {
108119
snake.head.x--;
109120
teleport(snake);
110-
eat(snake, apple);
121+
eat(snake, apple1, apple2);
111122
}
112123

113124
function moveRight(snake) {
114125
snake.head.x++;
115126
teleport(snake);
116-
eat(snake, apple);
127+
eat(snake, apple1, apple2);
117128
}
118129

119130
function moveDown(snake) {
120131
snake.head.y++;
121132
teleport(snake);
122-
eat(snake, apple);
133+
eat(snake, apple1, apple2);
123134
}
124135

125136
function moveUp(snake) {
126137
snake.head.y--;
127138
teleport(snake);
128-
eat(snake, apple);
139+
eat(snake, apple1, apple2);
129140
}
130141

131142
function move(snake) {

0 commit comments

Comments
 (0)