Skip to content

Week4-hw completion. #4

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

Open
wants to merge 4 commits into
base: master
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
25 changes: 25 additions & 0 deletions blackjack.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
* {
box-sizing : border-box;
}

body {
margin: 0;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
}
.title {
color: blue;
}
.approval {
color: green;
}
.warning {
color: red;
}
span {
font-weight: bold;
}
.summary {
font-weight: bold;
font-style: italic;
}
3 changes: 3 additions & 0 deletions blackjack.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
<html>
<head>
<title>Blackjack</title>
<link rel="stylesheet" href="blackjack.css">
</head>
<body>
<h1>Show hands and results</h1>
<div id="showHand"></div>
<script src="createCardDeck.js"></script>
<script src="blackjack.js"></script>
</body>
Expand Down
165 changes: 152 additions & 13 deletions blackjack.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,22 @@ const blackjackDeck = getDeck();
* @constructor
* @param {string} name - The name of the player
*/
class CardPlayer {}; //TODO
class CardPlayer {
constructor(name){
this.name = name;
this.hand = [];
}

drawCard(){
const randomCard = blackjackDeck[Math.floor(Math.random()*52)];
return this.hand.push(randomCard);
};

}; //TODO

// CREATE TWO NEW CardPlayers
const dealer; // TODO
const player; // TODO
const dealer = new CardPlayer('Dealer'); // TODO
const player = new CardPlayer('Player'); // TODO

/**
* Calculates the score of a Blackjack hand
Expand All @@ -18,9 +29,54 @@ const player; // TODO
* @returns {number} blackJackScore.total
* @returns {boolean} blackJackScore.isSoft
*/

const calcPoints = (hand) => {
// CREATE FUNCTION HERE
// Define total var with starting value = 0
let total = 0;
// Define isSoft var with default value is false
let isSoft = false;
// Check if the array of cards has an "Ace"
const findAce = hand.find((card) => card.displayVal === 'Ace');
// If there is an Ace in hand
if (findAce !== undefined) {
// Filter the other cards that are not "Ace"
const otherCards = hand.filter((card) => card.displayVal !=='Ace');
// If the array is not empty
if (otherCards.length > 0) {
// Looping through this cards array
otherCards.forEach(other => {
// Calculate the total points of other cards
total += other.val;
});
}

// Filter Ace cards
const aceCards = hand.filter((ace) => ace.displayVal === 'Ace');
// Looping through Ace cards
for (let i = 0; i < aceCards.length; i++) {
// If there is more than 1 Ace card or the current total points (including the current Ace card value) > 21
if (aceCards[i].val === 11 && (aceCards[i+1] !== undefined || (total + aceCards[i].val) > 21)) {
// Set the value of this Ace card = 1
aceCards[i].val = 1;
}
// Calculate total points
total += aceCards[i].val;
}

// Find Ace cards that have value equal 11
const findAce11 = aceCards.find((card) => card.val === 11);
// Set isSoft = true if there is an Ace in the Ace cards array that is being counted as 11 points
isSoft = (findAce11 !== undefined);

} else {
// Looping through the hand array
hand.forEach(card => {
// Calculate the total of all cards in the hand
total += card.val;
});
}
// Return object blackJackScore
return blackJackScore = {total,isSoft};
}

/**
Expand All @@ -30,9 +86,35 @@ const calcPoints = (hand) => {
* @returns {boolean} whether dealer should draw another card
*/
const dealerShouldDraw = (dealerHand) => {
// CREATE FUNCTION HERE
// Get score of dealer hand
const dealerScore = calcPoints(dealerHand);
// Check if dealerScore <= 16 or "dealerScore equal 17 and there is an Ace in dealerHand"
if (dealerScore.total <= 16 || (dealerScore.total === 17 && dealerScore.isSoft)) {
return true;
} else {
return false;
}
};

/**
* Define displayHTML function to show info in HTML page
* @param {string} text
* @param {string} className (optional)
*/
const displayHTML = (text, className = '') => {
// Create a new <p> element
const resultElement = document.createElement('p');
resultElement.innerHTML = text;
// Set CSS class for this element if className is given
if (className !== '') {
resultElement.className = className;
}
// Get element "showHand"
const showHandElement = document.getElementById('showHand');
// Add child element
showHandElement.appendChild(resultElement);
};

}

/**
* Determines the winner if both player and dealer stand
Expand All @@ -41,9 +123,22 @@ const dealerShouldDraw = (dealerHand) => {
* @returns {string} Shows the player's score, the dealer's score, and who wins
*/
const determineWinner = (playerScore, dealerScore) => {
// CREATE FUNCTION HERE

}
// Define winner var
let winner = '';
// Check if who wins
if (playerScore > dealerScore) {
winner = `You win!`;
} else if (playerScore === dealerScore) {
winner = `You are tied!`
} else {
winner = `Dealer wins!`;
}
// Show result in HTML page
const text = `Player score: <span class='approval'>${playerScore}</span>, Dealer score: <span class='warning'>${dealerScore}</span>. <span class='summary'>${winner}</span>`;
displayHTML(text);
// Return the final result
return `Player score: ${playerScore}, Dealer score: ${dealerScore}. ${winner}`
};

/**
* Creates user prompt to ask if they'd like to draw a card
Expand All @@ -60,7 +155,11 @@ const getMessage = (count, dealerCard) => {
*/
const showHand = (player) => {
const displayHand = player.hand.map((card) => card.displayVal);
console.log(`${player.name}'s hand is ${displayHand.join(', ')} (${calcPoints(player.hand).total})`);
console.log( `${player.name}'s hand is ${displayHand.join(', ')} (${calcPoints(player.hand).total})`);

// Display info in HTML page
const showHandText = `<span class='approval'>${player.name}'s</span> hand is <span class='approval'>${displayHand.join(', ')}</span> (<span class='title'>${calcPoints(player.hand).total}</span>)`;
displayHTML(showHandText);
}

/**
Expand All @@ -71,30 +170,70 @@ const startGame = function() {
dealer.drawCard();
player.drawCard();
dealer.drawCard();

// Player part
let playerScore = calcPoints(player.hand).total;
showHand(player);

// If the player gets exactly 21 after drawing her first 2 cards, the player immediately wins
if (playerScore === 21) {
// Display in HTML page
const text = `You get 21 after first 2 cards drawing. You win!`;
displayHTML(text, 'summary');
// Return the final result. Game over!
return text;
}

// Dealer part
let dealerScore = calcPoints(dealer.hand).total;
// If the dealer draws exactly 21 after drawing her first 2 cards, the dealer immediately wins
if (dealerScore === 21) {
showHand(dealer);
// Display in HTML page
const text = `Dealer gets 21 after first 2 cards drawing. Dealer wins!`;
displayHTML(text, 'summary');
// Return the final result. Game over!
return text;
}

// Player continues to draw new card
while (playerScore < 21 && confirm(getMessage(playerScore, dealer.hand[0]))) {
player.drawCard();
playerScore = calcPoints(player.hand).total;
showHand(player);
}

if (playerScore > 21) {
// Display this message below in HTML page
const text = `You went over <span class='title'>21</span> - you lose!`;
displayHTML(text, 'warning');
// Game over.
return 'You went over 21 - you lose!';
}
console.log(`Player stands at ${playerScore}`);

// Display player info in HTML page
const playerInfo = `Player stands at <span class='title'>${playerScore}</span>`;
displayHTML(playerInfo);

let dealerScore = calcPoints(dealer.hand).total;
// Dealer continues to draw new card
while (dealerScore < 21 && dealerShouldDraw(dealer.hand)) {
dealer.drawCard();
dealerScore = calcPoints(dealer.hand).total;
showHand(dealer);
}
if (dealerScore > 21) {
// Display this message below in HTML page
const text = `Dealer went over <span class='warning'>21</span> - you win!`;
displayHTML(text,'summary');
// Game over.
return 'Dealer went over 21 - you win!';
}
console.log(`Dealer stands at ${dealerScore}`);

// Display dealer info in HTML page
const dealerInfo = `Dealer stands at <span class='title'>${dealerScore}</span>`;
displayHTML(dealerInfo);
// Return the result
return determineWinner(playerScore, dealerScore);
}
// console.log(startGame());
console.log(startGame());
9 changes: 8 additions & 1 deletion cardsWorthTen.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,14 @@ const cards = [
* @param {array} cards
* @return {string} displayVal
*/
const cardsWorthTen = cards => {};
const cardsWorthTen = cards => {
// Filter all cards that have value equal 10
const cardsWorthTenArray = cards.filter((card) => card.val === 10);
// Get the name of all cards that have value equal 10
const displayVal = cardsWorthTenArray.map(card => card.displayVal).join(',');
// Return string "displayVal"
return displayVal;
};

console.log(cardsWorthTen(cards));
// should return/log "10, Jack, Queen, King"
46 changes: 43 additions & 3 deletions createCardDeck.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,51 @@
* @returns {Array} deck - a deck of cards
*/
const getDeck = () => {

// Define suits array with 4 items: hearts, diamonds, clubs, spades
const suits = ['hearts','diamonds','clubs','spades'];
// Define cards array
const cards = [];
// Set values (val, displayVal, suit) for each card in cards array
// Scan through suits array
for (let i = 0; i < suits.length; i++) {
// For loops from 1 to 13
for (let j = 1; j <=13; j++) {
// Define val & displayVal vars
let val;
let displayVal;
switch (j) {
case 1:
val = 11;
displayVal = 'Ace';
break;
case 11:
val = 10;
displayVal = 'Jack';
break;
case 12:
val = 10;
displayVal = 'Queen';
break;
case 13:
val = 10;
displayVal = 'King';
break;
default:
val = j;
displayVal = j.toString();
break;
}
// Set value for each card
cards.push({
val,
displayVal,
suit: suits[i]
});
}
}
return cards;
}



// CHECKS
const deck = getDeck();
console.log(`Deck length equals 52? ${deck.length === 52}`);
Expand Down
18 changes: 14 additions & 4 deletions foodIsCooked.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,22 @@
* @returns {boolean} isCooked
*/
const foodIsCooked = function(kind, internalTemp, doneness) {
// Write function HERE

// Check if kind is checken or not
if (kind === 'chicken') {
// Return true if the internal temp >= 165 and vice versa
return (internalTemp >= 165);
// check if kind is beef or not
} else if (kind === 'beef') {
if (doneness === 'rare') {
return (internalTemp >= 125);
} else if (doneness === 'medium') {
return (internalTemp >= 135);
} else if (doneness === 'well') {
return (internalTemp >= 155);
}
}
}



// Test function
console.log(foodIsCooked('chicken', 90)); // should be false
console.log(foodIsCooked('chicken', 190)); // should be true
Expand Down
10 changes: 9 additions & 1 deletion logCardDeck.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,12 @@ const cards = [
*
* @param {array} deck A deck of cards
*/
const logCardDeck = deck => {};
const logCardDeck = deck => {
// Get all values of the deck
const deckValues = Object.values(deck);
// Looping through deck values
deckValues.forEach(value => console.log(value));

};

logCardDeck(cards);