Skip to content

Commit 194905c

Browse files
author
Rich Harris
committed
better slot:fragment exercise
1 parent faace89 commit 194905c

File tree

3 files changed

+107
-27
lines changed

3 files changed

+107
-27
lines changed
Lines changed: 83 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,86 @@
11
<script>
2-
import Box from './Box.svelte';
2+
import Board from './Board.svelte';
3+
4+
let squares = Array(9).fill('');
5+
let next = 'x';
6+
7+
function getLine(squares) {
8+
const lines = [
9+
[0, 1, 2],
10+
[3, 4, 5],
11+
[6, 7, 8],
12+
[0, 3, 6],
13+
[1, 4, 7],
14+
[2, 5, 8],
15+
[0, 4, 8],
16+
[2, 4, 6]
17+
];
18+
19+
for (const line of lines) {
20+
const [a, b, c] = line;
21+
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
22+
return line;
23+
}
24+
}
25+
26+
return null;
27+
}
28+
29+
$: winningLine = getLine(squares);
330
</script>
431

5-
<Box>
6-
<div slot="footer">
7-
<p>All rights reserved.</p>
8-
<p>Copyright (c) 2019 Svelte Industries</p>
9-
</div>
10-
</Box>
32+
<div class="container">
33+
<Board size={3}>
34+
<svelte:fragment slot="game">
35+
{#each squares as square, i}
36+
<button
37+
class="square"
38+
class:winning={winningLine?.includes(i)}
39+
disabled={square}
40+
on:click={() => {
41+
squares[i] = next;
42+
next = next === 'x' ? 'o' : 'x';
43+
}}
44+
>
45+
{square}
46+
</button>
47+
{/each}
48+
</svelte:fragment>
49+
</Board>
50+
51+
<button on:click={() => {
52+
squares = Array(9).fill('');
53+
next = 'x';
54+
}}>
55+
Reset
56+
</button>
57+
</div>
58+
59+
<style>
60+
.container {
61+
display: flex;
62+
flex-direction: column;
63+
gap: 1em;
64+
align-items: center;
65+
justify-content: center;
66+
width: min(calc(100vmin - 2em), 20em);
67+
height: 100%;
68+
margin: 0 auto;
69+
}
70+
71+
.square, .square:disabled {
72+
background: white;
73+
border-radius: 0;
74+
color: #222;
75+
opacity: 1;
76+
font-size: 2em;
77+
}
78+
79+
.winning {
80+
font-weight: bold;
81+
}
82+
83+
.container:has(.winning) .square:not(.winning) {
84+
color: #ccc;
85+
}
86+
</style>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<script>
2+
export let size;
3+
</script>
4+
5+
<div class="board" style="--size: {size}">
6+
<slot name="game" />
7+
</div>
8+
9+
<slot name="controls" />
10+
11+
<style>
12+
.board {
13+
display: grid;
14+
grid-template-columns: repeat(var(--size), 1fr);
15+
grid-template-rows: repeat(var(--size), 1fr);
16+
width: 100%;
17+
aspect-ratio: 1;
18+
background: black;
19+
gap: 1px;
20+
padding: 0.5em;
21+
border-radius: 0.2em;
22+
filter: drop-shadow(0.2em 0.2em 1em rgba(0,0,0,0.3));
23+
}
24+
</style>

content/tutorial/02-advanced-svelte/09-special-elements/10-svelte-fragment/app-a/src/lib/Box.svelte

Lines changed: 0 additions & 20 deletions
This file was deleted.

0 commit comments

Comments
 (0)