Browse Source

Add pause/play button

master
Dylan Baker 3 years ago
parent
commit
c6490d7e35
3 changed files with 49 additions and 2 deletions
  1. 11
    2
      src/Board.tsx
  2. 18
    0
      src/Controls.tsx
  3. 20
    0
      src/index.css

+ 11
- 2
src/Board.tsx View File

@@ -1,5 +1,6 @@
1 1
 import React, { useState } from 'react';
2 2
 import Cell from './Cell';
3
+import Controls from './Controls';
3 4
 
4 5
 interface Props {
5 6
   width?: number;
@@ -11,9 +12,12 @@ const Board = (props: Props) => {
11 12
   const height = props.height ?? 5;
12 13
 
13 14
   const initialGrid: boolean[][] = Array(height).fill(Array(width).fill(false));
15
+
14 16
   const [grid, setGrid] = useState<boolean[][]>(initialGrid);
15 17
 
16
-  const toggle = (x: number, y: number) => {
18
+  const [running, setRunning] = useState<boolean>(false);
19
+
20
+  const toggleCell = (x: number, y: number) => {
17 21
     const newGrid = [...grid];
18 22
     const newRow = [...newGrid[y]];
19 23
     newRow[x] = !newGrid[y][x];
@@ -21,12 +25,17 @@ const Board = (props: Props) => {
21 25
     setGrid(newGrid);
22 26
   };
23 27
 
28
+  const toggleRunning = () => {
29
+    setRunning(!running);
30
+  };
31
+
24 32
   return (
25 33
     <div className="board">
34
+      <Controls running={running} toggle={toggleRunning} />
26 35
       {grid.map((row, y) => (
27 36
         <div className="row" key={y}>
28 37
           {row.map((cell, x) => (
29
-            <Cell x={x} y={y} alive={cell} toggle={toggle} key={x} />
38
+            <Cell x={x} y={y} alive={cell} toggle={toggleCell} key={x} />
30 39
           ))}
31 40
         </div>
32 41
       ))}

+ 18
- 0
src/Controls.tsx View File

@@ -0,0 +1,18 @@
1
+import React from 'react';
2
+
3
+interface Props {
4
+  running: boolean;
5
+  toggle: () => void;
6
+}
7
+
8
+const Controls = (props: Props) => {
9
+  const { running, toggle } = props;
10
+
11
+  return (
12
+    <div className="controls">
13
+      <button onClick={toggle}>{running ? 'Pause' : 'Play'}</button>
14
+    </div>
15
+  );
16
+};
17
+
18
+export default Controls;

+ 20
- 0
src/index.css View File

@@ -49,3 +49,23 @@ code {
49 49
 .cell.alive {
50 50
   background: black;
51 51
 }
52
+
53
+.controls {
54
+  display: flex;
55
+  margin-bottom: 1em;
56
+  width: 100%;
57
+}
58
+
59
+.controls button {
60
+  background: transparent;
61
+  border: 1px solid black;
62
+  cursor: pointer;
63
+  flex: 1;
64
+  font-size: 18px;
65
+  padding: 0.25em 0;
66
+}
67
+
68
+.controls button:hover {
69
+  background: black;
70
+  color: white;
71
+}

Loading…
Cancel
Save