This task involves implementing the game logic for the “Rock, Paper, Scissors” game. It starts by adding a card component to showcase the game’s outcome. Next, the task sets up JavaScript for the gameplay logic. It involves creating a new JavaScript file and linking it to the HTML file. Then, it adds id attributes to some elements for easy access in the JavaScript file. Lastly, the JavaScript file contains code that runs when a user interacts with the “Rock”, “Paper”, or “Scissors” buttons on the webpage.
Step 1: Add a Card Component for Game Outcomes
Now, let’s integrate a card component into our app to showcase the game outcome.
A card is essentially a bordered box with padding around its content. It offers options for headers, footers, content, colors, and more.
Paste the following snippet at the end of the body element, precisely above the <script> tag:
Here’s the outcome:
Step 2: Set Up JavaScript for Gameplay Logic
Our application’s design and styling are complete! Now, it’s time to implement the game.
Create an index.js file and link it to index.html by adding the following script element at the end of the body element, right above the </body> tag:
Additionally, add id attributes to some elements for easy access in index.js:
Next, add the following code to index.js:
The index.js file contains JavaScript code that runs when a user interacts with the “Rock”, “Paper”, or “Scissors” buttons on the webpage.
The first three lines retrieve references to these buttons using the document.getElementById method. The ids “rock”, “paper”, and “scissors” correspond to these buttons.
The play function is then defined. It takes an event object, which automatically passes to event handlers in JavaScript and contains information about the specific event. The event.target.id property is used to get the id of the clicked button, which is then logged to the console.
The addEventListener method attaches the play function as an event handler to the “click” event for each button. When any of these buttons are clicked, the play function executes.
Now, run and test the application: open the developer tool and click on each button.
Step 3: Implement Computer’s Random Choice
Let’s modify the script to allow the computer to select a choice randomly:
Now, run and test the application: click on any of the button and check the console.
Step 4: Integrate Game Logic to Determine Winner
Now, let’s incorporate the game logic:
Now, run and test the application: click on any of the button and check the console.
Step 5: Display Game Results on the Web Page
Instead of displaying the game state in the console, let’s modify the application to inject the results into the HTML page.
Here’s how the final script.js should look:
Now, let’s run the application: click on any of the button!