-
Notifications
You must be signed in to change notification settings - Fork 0
/
Game.js
90 lines (84 loc) · 2.41 KB
/
Game.js
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
import React, { useState } from "react";
import styles from './Game.module.css';
const CHOICES = [
{ name: "rock", emoji: "✊" },
{ name: "paper", emoji: "✋" },
{ name: "scissors", emoji: "✌️" },
];
const choiceStyles = {
display: 'flex',
alignItems: 'center',
marginBottom: 40,
};
const emojiStyles = {
fontSize: 64,
marginRight: 20,
};
const nameStyles = {
margin: 0,
fontSize: 24,
color: '#ffff',
};
const resultStyle = {
marginTop: 40,
fontSize: 48,
color: '#ffff',
};
function Game() {
const [playerChoice, setPlayerChoice] = useState(null);
const [codeyChoice, setCodeyChoice] = useState(null);
const [result, setResult] = useState(null);
function handlePlayerChoice(choice) {
const codeyChoice = CHOICES[Math.floor(Math.random() * CHOICES.length)];
setPlayerChoice(choice);
setCodeyChoice(codeyChoice);
if (choice.name === codeyChoice.name) {
setResult("Tie!");
} else if (
(choice.name === "rock" && codeyChoice.name === "scissors") ||
(choice.name === "paper" && codeyChoice.name === "rock") ||
(choice.name === "scissors" && codeyChoice.name === "paper")
) {
setResult("You win!");
} else {
setResult("You lose!");
}
}
function resetGame() {
setPlayerChoice(null);
setCodeyChoice(null);
setResult(null);
}
return (
<div className={styles.container}>
<h1 style={{ fontSize: 48, marginTop: 0 }}>Rock Paper Scissors</h1>
<div className={styles.choices}>
{CHOICES.map((choice) => (
<button
className={styles.button}
key={choice.name}
onClick={() => handlePlayerChoice(choice)}
aria-label={choice.name}
>
{choice.emoji}
</button>
))}
</div>
{playerChoice && codeyChoice && (
<div className={styles.results}>
<div style={choiceStyles}>
<span style={emojiStyles}>{playerChoice.emoji}</span>
<p style={nameStyles}>You chose {playerChoice.name}</p>
</div>
<div style={choiceStyles}>
<span style={emojiStyles}>{codeyChoice.emoji}</span>
<p style={nameStyles}>The computer chose {codeyChoice.name}</p>
</div>
<h2 style={resultStyle}>{result}</h2>
<button className={styles.button} onClick={resetGame}>Play again</button>
</div>
)}
</div>
);
}
export default Game;