Skip to content
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
Binary file added .DS_Store
Binary file not shown.
22 changes: 20 additions & 2 deletions closures.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,16 @@ console.log(counter.getCount());
// - addMessage method that adds a message to the array
// - getMessage(index) method that returns the message at index index

const createMessageHolder = () => {};
const createMessageHolder = () => {
const messageArray = [];
const addMessage = message => messageArray.push(message);
const getMessage = index => messageArray[index];

return {
addMessage,
getMessage
}
};

// Test
const messageHolder = createMessageHolder();
Expand Down Expand Up @@ -55,10 +64,19 @@ console.log(addThree(41));
// This will return a function a function greet
// - This accepts a single argument, name (i.e. "Matt")
// - This function should return the greeting combined with the name, (i.e. "Hello Matt")
const createGreeting = function(greeting) {};
const createGreeting = function(greeting) {
const greet = name => {
return `${greeting}, ${name}`;
}
return greet;
};

// Test
const welcomeGreet = createGreeting('Welcome');

(greeting) => {
return `${greeting}, `
}
console.log(welcomeGreet('Alice'));

const helloGreet = createGreeting('Hello');
Expand Down
10 changes: 7 additions & 3 deletions higher-order.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
// This function should execute the callback function the number of times specified.
// When the function is being executed, the repetition number (i.e. 1 for the first call)
// should be passed to the callback.
const repeatFn = (times, callback) => {};
const repeatFn = (times, callback) => {
for (let index = 0; index < times; index++) {
callback(index + 1);
}
};

// Test repeatFn
const addButton = num => {
Expand All @@ -14,9 +18,9 @@ repeatFn(6, addButton);
const toThePower = (num, pow) => {
let product = 1;
repeatFn(pow, () => {
product += product * num;
product = product * num;
});
return product;
};

console.log(toThePower(3, 3));
console.log(toThePower(2, 5));
110 changes: 110 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE-edge">
<meta name="viewpot" content="width=device-width, initial-scale=1.0">
<title>Rock Paper Scissors</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="./style.css">
<script src="https://kit.fontawesome.com/9bfbb90b34.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row text-center align-items-center">
<div class="col-12">
<h1>Rock Paper Scissors</h1>
</div>
</div>

<div class="row text-center align-items-center">
<div id="icons" class="col-12">
<i class="fas fa-hand-rock"></i><i class="fas fa-hand-paper"></i><i class="fas fa-hand-scissors"></i>
</div>
</div>

<div class="row">
<div id="interface" class="col-6 offset-3">
<form id="startForm">
<div class="form-group row">
<label for="inputEmail3" class="col-sm-3 col-form-label">First name</label>
<div class="col-sm-9">
<input type="text" class="form-control" pattern="\w{3,}" id="firstName" placeholder="First name..." required>
</div>
</div>
<fieldset class="form-group">
<div class="row">
<legend class="col-form-label col-sm-3 pt-0">Best of...</legend>
<div class="col-sm-9">
<div class="form-check">
<input class="form-check-input" type="radio" name="gameRounds" id="gameRounds1" value="1" checked>
<label class="form-check-label" for="1">
1 round
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="gameRounds" id="gameRounds2" value="3">
<label class="form-check-label" for="3">
3 rounds
</label>
</div>
<div class="form-check disabled">
<input class="form-check-input" type="radio" name="gameRounds" id="gameRounds3" value="5">
<label class="form-check-label" for="5">
5 rounds
</label>
</div>
</div>
</div>
</fieldset>
<div class="form-group row">
<div class="col-sm-10 offset-sm-3">
<button id="startButton" type="submit" class="btn btn-primary btn-lg">Let the battle commence!</button>
</div>
</div>
</form>
<div id="rules" class="row">
<div class="col-sm-10 offset-sm-3">
<button type="button" class="btn btn-light" data-toggle="modal" data-target="#exampleModal">
Rules
</button>
</div>
</div>
</div>
</div>

<div id="gamePlay" class="row text-center align-items-center">
<div id="gamePlayLeft" class="col-5"></div>
<div id="results" class="col-2"></div>
<div id="gamePlayRight" class="col-5"></div>
</div>

<!--<div class="row text-center align-items-center">
<div id="results" class="col-12"></div>
</div>--!>
</div>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Rock Paper Scissors Rules</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body text-center">
<img src="./rps_rules.png" width="400" alt="Rock Paper Scissors Rules">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="./script.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script></body>
</body>
</html>
Binary file added rps_rules.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
216 changes: 216 additions & 0 deletions script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
const startButton = document.getElementById('startButton');
const icons = document.getElementById('icons');
const interface = document.getElementById('interface');
const results = document.getElementById('results');
const userForm = document.createElement('form');
const gamePlayRow = document.getElementById('gamePlay');
const startForm = document.getElementById('startForm');
const rules = document.getElementById('rules');

const iconSet = {
rock: {
id: 'rock',
classes: ['fas', 'fa-hand-rock']
},
paper: {
id: 'paper',
classes: ['fas', 'fa-hand-paper']
},
scissor: {
id: 'scissor',
classes: ['fas', 'fa-hand-scissors']
},
}

localStorage.setItem('computerScore', 0);
localStorage.setItem('playerScore', 0);

function gameReset() {
startForm.style.display = 'block';
rules.style.display = 'block';
icons.style.display = 'block';
interface.style.display = 'block';
gamePlayLeft.innerHTML = '';
gamePlayRight.innerHTML = '';
results.innerHTML = '';
localStorage.clear();
localStorage.setItem('computerScore', 0);
localStorage.setItem('playerScore', 0);
}

function gamePlay(e) {
e.preventDefault();

// Store name and number of rounds locally
localStorage.setItem('firstName', firstName.value);
const selectedRound = Array.from(document.getElementsByName('gameRounds')).filter(radio => radio.checked);
localStorage.setItem('gameRounds', selectedRound[0].value);

// Hide form and rules button
startForm.style.display = 'none';
rules.style.display = 'none';

// Hide icons
icons.style.display = 'none';
interface.style.display = 'none';

let playerScoreDisplay = document.createElement('h4');
playerScoreDisplay.innerText = `Score = ${localStorage.getItem('playerScore')}`;

let computerScoreDisplay = document.createElement('h4');
computerScoreDisplay.innerText = `Score = ${localStorage.getItem('computerScore')}`;

// Add clickable icons to left play area (player)
let gamePlayLeft = document.getElementById('gamePlayLeft');
gamePlayLeft.innerHTML = '';
gamePlayLeft.appendChild(playerScoreDisplay);
addIcons(gamePlayLeft);

let playerName = document.createElement('h5');
playerName.innerText = localStorage.getItem('firstName');
gamePlayLeft.appendChild(playerName);

// Add visual icons to right play area (opponent)
let gamePlayRight = document.getElementById('gamePlayRight');
gamePlayRight.innerHTML = '';
gamePlayRight.appendChild(computerScoreDisplay);
addIcons(gamePlayRight);

let opponentName = document.createElement('h5');
opponentName.innerText = 'Computer';
gamePlayRight.appendChild(opponentName);

// Add click event listener to left game play div to catch bubbling clicks on icons
gamePlayLeft.addEventListener('click', initiateOpponentTurn);
}

function initiateOpponentTurn(e) {
// Manage user clicks and initiate call to rock paper scissors API
if(e.target.classList.contains('fas')) {
e.target.style.borderColor = 'red';
gamePlayLeft.removeEventListener('click', initiateOpponentTurn);
opponentThinkingAnimation(e.target.id);
}
}

function opponentThinkingAnimation(playerChoice) {
document.getElementById('gamePlayRight').querySelector('h5').innerText = 'Thinking';

let counter = 0;
let thinking = setInterval(() => {
document.getElementById('gamePlayRight').querySelector('h5').innerText += '.';
counter++;
if(counter >= 5) {
clearInterval(thinking);
opponentChooses(playerChoice);
}
}, 500);
}

function opponentChooses(playerChoice) {
fetch(`https://rock-paper-scissor2.p.rapidapi.com/api/${playerChoice}`, {
"method": "GET",
"headers": {
"x-rapidapi-host": "rock-paper-scissor2.p.rapidapi.com",
"x-rapidapi-key": "cnQ72noorzmsh02s3Fs3vtWTfKgFp1Z4j59jsnWAJadd9knCwY"
}
})
.then(data => data.json())
.then(response => {
const opponentSide = document.getElementById('gamePlayRight');
opponentSide.querySelector(`#${response.computer}`).style.borderColor = 'red';
outputRoundResults(response);
})
.catch(err => {
console.error(err);
});
}

function outputRoundResults(response) {
const resultsText = document.createElement('h3');

if(response.cstat === 'computer won') {
resultsText.innerHTML = `${capitalize(response.computer)}<br>BEATS<br>${capitalize(response.you)}`;
localStorage.setItem('computerScore', +localStorage.getItem('computerScore') + 1);
document.querySelector('#gamePlayRight h4').innerText = `Score = ${localStorage.getItem('computerScore')}`;
}
else if (response.pstat === 'you won'){
resultsText.innerHTML = `${capitalize(response.you)}<br>BEATS<br>${capitalize(response.computer)}`;
localStorage.setItem('playerScore', +localStorage.getItem('playerScore') + 1);
document.querySelector('#gamePlayLeft h4').innerText = `Score = ${localStorage.getItem('playerScore')}`;
}
else {
resultsText.innerHTML = `Draw<br><hr>`;
}
results.appendChild(resultsText);

const roundsToWin = Math.ceil(localStorage.getItem('gameRounds') / 2);

if(localStorage.getItem('playerScore') >= roundsToWin || localStorage.getItem('computerScore') >= roundsToWin ) {
gameOverMenu();
}
else {
nextRoundMenu();
}
}

function nextRoundMenu() {
let resumeButton = document.createElement('button');
resumeButton.innerText = `Begin next round`;
resumeButton.classList.add('btn', 'btn-primary', 'btn-large');
resumeButton.addEventListener('click', (e) => {
document.getElementById('results').innerText = '';
resumeButton.remove();
gamePlay(e);
});
results.appendChild(resumeButton);
}

function gameOverMenu() {

let message = document.createElement('h5');
let winner = '';
localStorage.getItem('computerScore') > localStorage.getItem('playerScore') ? winner = 'Computer' : winner = localStorage.getItem('firstName');
message.innerText = `${winner} wins!`;

let newGameButton = document.createElement('button');
newGameButton.innerText = `Play again`;
newGameButton.classList.add('btn', 'btn-primary', 'btn-large');
newGameButton.addEventListener('click', () => {
newGameButton.remove();
gameReset();
});
results.appendChild(message);
results.appendChild(newGameButton);
}

function addIcons(element) {
let gamePlayDiv = document.createElement('div');
gamePlayDiv.id = 'icons';
gamePlayDiv.classList.add('col-12');

for(const icon in iconSet) {
let iconElement = document.createElement('i');
iconSet[icon].classes.forEach(classToAdd => iconElement.classList.add(classToAdd));
iconElement.id = iconSet[icon].id;
setAttributes(iconElement, {title: capitalize(iconSet[icon].id)});
gamePlayDiv.appendChild(iconElement);
}

element.appendChild(gamePlayDiv);
gamePlayRow.style.display = 'flex';
}

startForm.addEventListener('submit', gamePlay);

// Helper functions

function setAttributes(element, attributes) {
for(let key in attributes) {
element.setAttribute(key, attributes[key]);
}
}

function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
Loading