1- // TODO: Handle user selection (rock, paper, scissors)
2- // TODO: Generate computer choice
3- // TODO: Determine winner/loser/draw
4- // TODO: Update and display scoreboard
5- // TODO: Restart game functionality
6-
71function initRockPaperScissors ( ) {
8- // TODO: Handle user choice
9- // TODO: Generate computer choice
10- // TODO: Determine winner
11- // TODO: Update scoreboard
2+ const choices = [ "rock" , "paper" , "scissors" ] ;
3+ let userScore = 0 ;
4+ let computerScore = 0 ;
5+
6+ const userScoreSpan = document . getElementById ( "user-score" ) ;
7+ const computerScoreSpan = document . getElementById ( "computer-score" ) ;
8+ const resultDiv = document . getElementById ( "result" ) ;
9+ const displayChoicesDiv = document . getElementById ( "display-choices" ) ;
10+ const btns = document . querySelectorAll ( ".rps-btn" ) ;
11+ const restartBtn = document . getElementById ( "restart-btn" ) ;
12+
13+ function getComputerChoice ( ) {
14+ return choices [ Math . floor ( Math . random ( ) * 3 ) ] ;
15+ }
16+
17+ function getResult ( user , computer ) {
18+ if ( user === computer ) return "draw" ;
19+ if (
20+ ( user === "rock" && computer === "scissors" ) ||
21+ ( user === "paper" && computer === "rock" ) ||
22+ ( user === "scissors" && computer === "paper" )
23+ )
24+ return "win" ;
25+ return "lose" ;
26+ }
27+
28+ function displayScores ( ) {
29+ userScoreSpan . textContent = userScore ;
30+ computerScoreSpan . textContent = computerScore ;
31+ }
32+
33+ function handleClick ( e ) {
34+ const userChoice = e . target . dataset . choice ;
35+ const computerChoice = getComputerChoice ( ) ;
36+ const outcome = getResult ( userChoice , computerChoice ) ;
37+ displayChoicesDiv . textContent = `You: ${ capitalize (
38+ userChoice
39+ ) } | Computer: ${ capitalize ( computerChoice ) } `;
40+ if ( outcome === "win" ) {
41+ userScore ++ ;
42+ resultDiv . textContent = "You win!" ;
43+ resultDiv . style . color = "#349946" ;
44+ } else if ( outcome === "lose" ) {
45+ computerScore ++ ;
46+ resultDiv . textContent = "You lose!" ;
47+ resultDiv . style . color = "#d43d29" ;
48+ } else {
49+ resultDiv . textContent = "It's a draw!" ;
50+ resultDiv . style . color = "#4078b3" ;
51+ }
52+ displayScores ( ) ;
53+ }
54+
55+ function capitalize ( str ) {
56+ return str . charAt ( 0 ) . toUpperCase ( ) + str . slice ( 1 ) ;
57+ }
58+
59+ btns . forEach ( ( btn ) => {
60+ btn . addEventListener ( "click" , handleClick ) ;
61+ } ) ;
62+
63+ restartBtn . addEventListener ( "click" , function ( ) {
64+ userScore = 0 ;
65+ computerScore = 0 ;
66+ displayScores ( ) ;
67+ resultDiv . textContent = "" ;
68+ displayChoicesDiv . textContent = "" ;
69+ } ) ;
70+
71+ // Initial score display
72+ displayScores ( ) ;
1273}
1374
14- window . addEventListener ( ' DOMContentLoaded' , initRockPaperScissors ) ;
75+ window . addEventListener ( " DOMContentLoaded" , initRockPaperScissors ) ;
0 commit comments