-
Notifications
You must be signed in to change notification settings - Fork 8
/
playgroundExample.source.tsx
58 lines (50 loc) · 1.4 KB
/
playgroundExample.source.tsx
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
import { useState } from 'react';
import { Button } from 'example-library';
import './playgroundExample.css';
const hands = [
{ title: 'rock', children: '✊' },
{ title: 'paper', children: '✋' },
{ title: 'scissors', children: '✌️' },
];
function getRandomChoice() {
return Math.floor(Math.random() * 3);
}
export default () => {
const [wins, setWins] = useState(0);
const [losses, setLosses] = useState(0);
const [ties, setTies] = useState(0);
const [opponentChoice, setOpponentChoice] = useState(getRandomChoice);
const [previousChoice, setPreviousChoice] = useState('');
function onChoice(choice: number) {
return () => {
const result = (choice - opponentChoice + 2) % 3;
[setWins, setLosses, setTies][result]((c) => c + 1);
setPreviousChoice(hands[opponentChoice].children);
setOpponentChoice(getRandomChoice);
};
}
return (
<>
<h1>Complex example (rock, paper, scissors)</h1>
<h2>
<pre>
Wins: {wins} | Losses: {losses} | Ties: {ties}
</pre>
</h2>
{hands.map((hand, i) => (
<Button
onClick={onChoice(i)}
backgroundColor="whitesmoke"
className="button-nice"
key={hand.title}
{...hand}
/>
))}
{previousChoice && (
<h2>
<pre>Opponent's previous choice: {previousChoice}</pre>
</h2>
)}
</>
);
};