-
Notifications
You must be signed in to change notification settings - Fork 12
/
App.svelte
executable file
·336 lines (293 loc) · 8.21 KB
/
App.svelte
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
<script>
import { onDestroy } from "svelte";
import { fly, scale } from "svelte/transition";
import GameOverModal from "./GameOverModal.svelte";
import {
DIRECTION_VECTORS,
DIRECTION_NAMES,
getNewApplePosition,
getNewDirectionFromEventKey,
getNextSnake,
isStraightOr180Turn,
getNextHeadDirectionAndQueue,
isEqual,
isInsideBoard,
isSnakeEatingItself,
} from "./utils";
import NesContainer from "./NesContainer.svelte";
import StartModal from "./StartModal.svelte";
const TICK_TIME = 100;
const BOARD_DIMENSIONS = { x: 20, y: 20 };
const GAME_STATES = Object.freeze({
START_SCREEN: "START_SCREEN",
PLAYING: "PLAYING",
PAUSED: "PAUSED",
GAME_OVER: "GAME_OVER",
});
// Letting the state variables go uninitialized is safe,
// because they are initialized by resetGame before they are ever read
let apple;
let gameState;
let headDirection;
let score;
let snake;
let willGrow;
let headDirectionQueue;
function resetGame() {
const initialSnake = [
{ x: 4, y: 4 },
{ x: 4, y: 3 },
{ x: 4, y: 2 },
];
apple = getNewApplePosition(BOARD_DIMENSIONS, initialSnake);
gameState = GAME_STATES.START_SCREEN;
headDirection = DIRECTION_NAMES.SOUTH;
score = 0;
snake = initialSnake;
willGrow = false;
headDirectionQueue = [];
}
resetGame();
// Snake logic
function moveSnake() {
const [nextQueue, nextDirection] = getNextHeadDirectionAndQueue(
headDirectionQueue,
headDirection
);
headDirectionQueue = nextQueue;
headDirection = nextDirection;
snake = getNextSnake(snake, DIRECTION_VECTORS[headDirection], willGrow);
willGrow = false;
}
$: if (
!isInsideBoard(BOARD_DIMENSIONS, snake[0]) ||
isSnakeEatingItself(snake)
) {
gameState = GAME_STATES.GAME_OVER;
}
// Apple logic
$: if (isEqual(snake[0], apple)) {
eatApple();
}
function eatApple() {
score += 1;
willGrow = true;
apple = getNewApplePosition(BOARD_DIMENSIONS, snake);
}
// User interaction
function handleKeydown(event) {
if (gameState === GAME_STATES.START_SCREEN) {
gameState = GAME_STATES.PLAYING;
return;
}
if (gameState === GAME_STATES.PAUSED) {
if (event.key === " ") {
gameState = GAME_STATES.PLAYING;
}
return;
}
if (gameState === GAME_STATES.PLAYING) {
if (event.key === " ") {
gameState = GAME_STATES.PAUSED;
}
const keyDirection = getNewDirectionFromEventKey(event.key);
if (!keyDirection) {
return;
}
headDirectionQueue = [...headDirectionQueue, keyDirection];
}
}
// Starting and stopping gameplay
let stopTicking = () => {};
const startTicking = () => {
const id = setInterval(moveSnake, TICK_TIME);
stopTicking = () => clearInterval(id);
return () => clearInterval(id);
};
// Reacting to changed states
$: handleStateChange(gameState);
// Extracting it as a separate function to avoid it being called when variables other than gameState
// are reassigned, namely stopTicking, which is reassigned on startTicking
function handleStateChange(newState) {
if (newState === GAME_STATES.START_SCREEN) {
resetGame();
} else if (newState === GAME_STATES.PLAYING) {
startTicking();
} else if (newState === GAME_STATES.PAUSED) {
stopTicking();
} else if (newState === GAME_STATES.GAME_OVER) {
stopTicking();
}
}
// Stop calling functions in intervals when the functions stop existing (i.e. when the component unmounts)
onDestroy(stopTicking);
const CELL_SIZE = 25;
// Styling
function calculatePositionAsStyle(coordinate) {
return `left: ${coordinate.x * CELL_SIZE}px; top: ${
coordinate.y * CELL_SIZE
}px`;
}
$: gameOver = gameState === GAME_STATES.GAME_OVER;
</script>
<svelte:body on:keydown={handleKeydown} />
<div
class="main-content min-width"
style="--cell-size: {CELL_SIZE}px; --tick-time: {TICK_TIME}ms; --board-size-x: {BOARD_DIMENSIONS.x}; --board-size-y: {BOARD_DIMENSIONS.y}"
>
<div class="score">{score}</div>
<div class="board">
{#each snake.slice(1) as bodyPart}
<div class="body-part" style={calculatePositionAsStyle(bodyPart)} />
{/each}
<div class="body-part head" style={calculatePositionAsStyle(snake[0])} />
<div
class="body-part tail"
style={calculatePositionAsStyle(snake[snake.length - 1])}
/>
<!-- This extra tail is added to compensate for tail flickering in Chrome and Safari -->
<div
class="body-part tail"
style={calculatePositionAsStyle(snake[snake.length - 2])}
/>
{#key score}
<div in:scale style={calculatePositionAsStyle(apple)} class="apple" />
{/key}
{#if gameOver}
<div
in:scale={{ delay: 300 }}
style={calculatePositionAsStyle(snake[0])}
class="skull"
/>
{/if}
</div>
<div class="signature">
<p>
Made with
<a href="https://svelte.dev/">
<img alt="Svelte logo" src="/svelte.png" />
Svelte
</a>
in the
<a href="https://github.com/Vages/svelte-snake-workshop">
Svelte Snake Workshop
</a>
</p>
</div>
</div>
{#if gameState === GAME_STATES.START_SCREEN}
<div class="modal-container" out:fly={{ y: -100 }}>
<!-- This div, together with the class modal-container is required to center the content -->
<div style="position: relative; left: -50%;">
<StartModal />
</div>
</div>
{/if}
{#if gameState === GAME_STATES.PAUSED}
<div class="modal-container" transition:fly={{ y: -100 }}>
<!-- This div, together with the class modal-container is required to center the content -->
<div style="position: relative; left: -50%;">
<NesContainer>
<h2>Pause</h2>
Space to resume
</NesContainer>
</div>
</div>
{/if}
{#if gameState === GAME_STATES.GAME_OVER}
<div class="modal-container" in:fly={{ delay: 1300, y: -100 }}>
<!-- This div, together with the class modal-container is required to center the content -->
<div style="position: relative; left: -50%;">
<GameOverModal
on:close_modal={() => {
gameState = GAME_STATES.START_SCREEN;
}}
{score}
/>
</div>
</div>
{/if}
<style>
:root {
--checker-color: #f0f0f0;
}
.modal-container {
position: absolute;
left: 50%;
top: 2rem;
}
.min-width {
width: min-content;
}
.main-content {
margin: 1rem auto 0 auto;
display: grid;
grid-template-columns: auto;
gap: 2rem;
align-items: center;
text-align: center;
}
.score {
justify-self: right;
}
.signature {
font-size: 0.5rem;
}
.signature img {
height: 2em;
margin-right: -0.5em;
margin-top: -0.25em;
}
.body-part,
.skull,
.apple {
position: absolute;
width: var(--cell-size);
height: var(--cell-size);
text-align: center;
line-height: 1;
}
.body-part {
background-color: green;
}
.head {
transform: scale(1.3);
}
.head,
.tail {
transition: top var(--tick-time) linear, left var(--tick-time) linear;
}
.apple::before {
content: "🍎";
font-size: calc(var(--cell-size) * 0.8);
}
.skull::before {
content: "☠️";
overflow: hidden;
}
.skull {
/* Transform cannot be applied to a before element, so we must apply it here */
transform: scale(3, 3) translateY(4px);
transform-origin: 50% 50%;
}
.board {
--border-width: var(--cell-size);
width: calc(var(--board-size-x) * var(--cell-size));
height: calc(var(--board-size-y) * var(--cell-size));
position: relative;
margin: var(--border-width);
outline: var(--border-width) solid black;
background-image: linear-gradient(
45deg,
var(--checker-color) 25%,
transparent 25%
),
linear-gradient(-45deg, var(--checker-color) 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, var(--checker-color) 75%),
linear-gradient(-45deg, transparent 75%, var(--checker-color) 75%);
background-size: calc(var(--cell-size) * 2) calc(var(--cell-size) * 2);
background-position: 0 0, 0 var(--cell-size),
var(--cell-size) calc(-1 * var(--cell-size)),
calc(-1 * var(--cell-size)) 0;
}
</style>