Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rock_paper_scissors added #56

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions rock_paper_scissors/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@

# Rock-Paper-Scissors Game

## Overview

This project is a simple implementation of the classic **Rock-Paper-Scissors** game using JavaScript. It allows a human player to compete against the computer in a best-of-five series, with the first to reach five wins being declared the winner.

## Features

- **Interactive Gameplay:** The player inputs their choice via a prompt, and the computer's choice is generated randomly.
- **Score Tracking:** The game keeps track of both the player's and the computer's scores, updating after each round.
- **Game Logic Implementation:** Includes the core logic to determine the winner of each round based on the rules of Rock-Paper-Scissors.

## Code Highlights

### Random Computer Choice
The `computer_random()` function generates a random integer between 1 and 3, corresponding to Rock, Paper, or Scissors:

```javascript
function computer_random() {
return Math.floor(Math.random() * 3) + 1;
}
```

### Human Choice Handling
The `human_choice()` function prompts the user to enter their choice and normalizes it to lowercase for easier processing:

```javascript
function human_choice() {
let choice = prompt("Enter the choice");
return choice.toLowerCase();
}
```

### Choice Mapping
The `choice_number()` function maps the human-readable choice (`"rock"`, `"paper"`, `"scissors"`) to a corresponding numeric value:

```javascript
function choice_number(human_choice) {
switch(human_choice) {
case("rock"):
return 1;
case("paper"):
return 2;
case("scissors"):
return 3;
default:
console.log("Invalid input");
return -1;
}
}
```

### Game Logic
The `update_score()` function compares the human and computer choices to determine the winner of the round, and updates the score accordingly:

```javascript
function update_score(human, computer) {
if (human == computer) {
alert("It's a Draw");
} else if ((human == 1 && computer == 2) || (human == 2 && computer == 3) || (human == 3 && computer == 1)) {
alert("Computer Won");
score_c++;
} else {
alert("Human Won");
score_h++;
}
}
```

### Game Loop
The game loop continues until either the player or the computer wins five rounds:

```javascript
while (score_h < 5 && score_c < 5) {
let entered_choice = human_choice();
let human_number = choice_number(entered_choice);
let random_choice = computer_random();
update_score(human_number, random_choice);
}
```

## Learning and Skills Demonstrated

- **Control Structures:** Utilized `switch` statements for mapping choices and `if-else` logic for game mechanics.
- **User Interaction:** Employed JavaScript's `prompt` for user input and `alert` for output, demonstrating basic UI interaction.
- **Randomization:** Used `Math.random()` for generating the computer's choice, ensuring a fair and unpredictable opponent.
- **Loops and Conditions:** Implemented a game loop with a stopping condition based on scores, showcasing understanding of control flow.

## Future Enhancements

- **Input Validation:** Improve the game by handling invalid user inputs more gracefully.
- **UI/UX Improvements:** Replace prompts and alerts with a more engaging graphical user interface (GUI).
- **Scoreboard:** Add a visual scoreboard to track the scores more intuitively.

## Conclusion

This project is a fundamental exercise in JavaScript programming, demonstrating essential concepts such as random number generation, user input handling, and conditional logic. It serves as a solid foundation for more complex interactive applications.
31 changes: 31 additions & 0 deletions rock_paper_scissors/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock Papers Scissors</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Rock Papers Scissors</h1>
</header>

<div class="score-board">
<div id="user-label" class="badge">user</div>

<span id="user-score">0</span>:<span id="comp-score">0</span>
<div id="comp-label" class="badge">comp</div>
</div>

<div class="result"><p>Start Playing...</p></div>
<div class="choice">
<div class="choices" id="r">✊</div>
<div class="choices" id="p">🤚</div>
<div class="choices" id="s">✌️</div>
</div>

<p id="action-message">Make your move...</p>
<script src="main.js"></script>
</body>
</html>
84 changes: 84 additions & 0 deletions rock_paper_scissors/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
let userScore = 0;
let compScore = 0;

const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");

const scoreBoard_div = document.querySelector(".scoreBoard");
const result_div = document.querySelector(".result");

const scissor_div = document.getElementById("s");
const rock_div = document.getElementById("r");
const paper_div = document.getElementById("p");

function getCompChoice() {
const choices = ['r', 'p', 's'];
const randomNumber = Math.floor(Math.random() * 3);
return choices[randomNumber];
}
function win() {
userScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_div.innerHTML = "<p style='text-align: center; font-family: \"Press Start 2P\", cursive; font-weight: bold;'>You win!</p>";
checkGameOver();
}
function lose() {
compScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_div.innerHTML = "<p style='text-align: center; font-family: \"Press Start 2P\", cursive; font-weight: bold;'>You Lose!</p>";
checkGameOver();
}
function draw() {
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_div.innerHTML = "<p style='text-align: center; font-family: \"Press Start 2P\", cursive; font-weight: bold;'>Its a Draw!</p>";
checkGameOver();
}
function checkGameOver() {
if (userScore === 5 || compScore === 5) {
setTimeout(function() {
if (userScore === 5) {
alert("You win the game!");
} else {
alert("You lose the game!");
}
userScore = 0; // Reset user score
compScore = 0; // Reset computer score
userScore_span.innerHTML = userScore; // Update the user score on screen
compScore_span.innerHTML = compScore; // Update the computer score on screen
}, 100);
}
}
function game(userChoice) {
const compChoice = getCompChoice();
if(userChoice == compChoice) {
console.log("It's a draw");
draw();
}
else if((userChoice == 'r' && compChoice == 'p') || (userChoice == 'p' && compChoice == 's') || (userChoice == 's' && compChoice == 'r')) {
console.log("You lose");
lose();
}
else if((userChoice == 'p' && compChoice == 'r') || (userChoice == 's' && compChoice == 'p') || (userChoice == 'r' && compChoice == 's')) {
console.log("You win");
win();
}

}

function main() {
rock_div.addEventListener('click', function () {
game("r")
})
paper_div.addEventListener('click', function () {
game("p")
})
scissor_div.addEventListener('click', function () {
game("s")
})
}

document.addEventListener('DOMContentLoaded', main);

91 changes: 91 additions & 0 deletions rock_paper_scissors/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;

}
header{
background-color: rgb(255, 200, 61);
padding:20px ;
}
header > h1{
color: rgb(31, 31, 31);
text-align: center;
font-family: 'Press Start 2P', cursive;
font-size:x-large
}
body{
background-color: rgb(58, 58, 58) ;
}
.score-board{
border: 3px solid white;
text-align: center;
width: 200px;
margin: 20px auto;
color: white;
font-size: 20px;
border-radius: 8px;
padding: 15px 20px;
font-family: 'Press Start 2P', cursive;
position: relative;
}
.badge{
background-color: brown ;
margin: 0px;
padding: 3px;
font-size: 14px;
}

#user-label{
position: absolute;
top: 16px;
left: -30px;
}
#comp-label{
position: absolute;
top: 16px;
right: -30px;
}


.result{
color: white;
font-size: 20px;
}
.result > p{
text-align: center;
font-family: 'Press Start 2P', cursive;
font-weight: bold;
}

.choice{
text-align: center;
user-select: none;

}

.choices{
display: inline-block;
font-size: 85px;
margin: 40px;
border: 4px solid white;
border-radius: 50%;
padding: 10px;
transition: transform 0.3s ease;
}


.choices:hover{
transform: scale(1.2);
background-color: black;
cursor: pointer;

}

#action-message{
text-align: center;
font-family: 'Press Start 2P', cursive;
color: white;
margin-top: 10px;
}