To practice java script code use below online editor
http://plnkr.co/ --> click on 'launch editor' --> you would observe sample
settings are available on right hand side, using this we can do basic settings on plunker editor:
Java script is Case Sensitive.
Basic Hello World program
Add below line in script.js and click on run for output. You would see output in console of browser (press F12).
Example 1:
console.log("Hello World!!");
Example 2:
let aa = "this is",
bb = "example";
console.log(aa,bb);
Output in console of browser: this is example
Example 3:
let aa = 10.00;
let bb = 20.00;
console.log(aa+bb);
output: 30
Example 4:
let aa = 10.00;
let bb = "20.00";
console.log(aa+bb);
output: 1020.00
Operations in Java Script:
It is similar to java / c all of the + - * / % works as expected similar to other object oriented languages.
Comments in JavaScript:
// this is a comment
let name = "madhu";
or
// this is comment 1
//this is comment 2
let name = "madhu";
or
/* this is comment 1
this is comment 2 */
let name = "madhu";
or
let answer = 32; // this is freezing point
console.log(answer);
Boolean Data Types:
let flag = true;
console.log(flag, typeof(flag));
output: true "boolean"
Difference between undefined and null:
when a variable is declared without any value then its value is undefined.
let x;
console.log(x);
output: undefined // we can not assign undefined to a variable.
null can be assigned to a variable using our source code.
declaring and accessing array:
let a = [];
console.log(a[0]); // undefined
let a = ["a1","a2","a3"];
console.log(a[0]);
console.log(a[1]);
console.log(a[2]);
console.log(a);
let a = [1,2,3,4];
console.log(a);
console.log(a.length);
let values = [];
values.push(1);
values.push(2);
values.push(3);
console.log(values);
output: [1,2,3]
let values = [1,2,3];
values.pop();
console.log(values);
output: [1,2]
let values = [1,2,3];
let result = values.pop();
console.log(result);
output: 3 // this will work similar to stack push and pop by removing last inserted item (LIFO).
let values = [1,2,3,44];
let result = values.shift();
console.log(result, values);
output: 1, [2 3 44]
splice() method used to delete the elements in given range also insert some elements.
let values = [1,2,3,4,5];
let result = values.splice(0,1);
console.log(values);
output: [2,3,4,5] // from 0th index delete one element
let values = [1,2,3,4,5];
let result = values.splice(0,1,6,7);
console.log(values);
output: [6,7, 2,3,4,5] // from 0th index delete one element, then insert 6 & 7.
we have several methods on arrays as specified here.
Player Cards Game Phase 1 for POC:
let deck = [ "Ace of Spades",
"Two of Spades",
"Three of Spades"];
let playerCards = [ deck[0], deck[2]];
console.log("Welcome to BlackJack");
console.log("You are dealt:");
console.log(" "+playerCards[0]);
console.log(" "+playerCards[1]);
Program flow:
let text = 'Hyderabad';
let num = 7;
if(text === 'Hyderabad')
{
num = 17;
}
console.log(num);
output: 17
what qualifies false in javascript:
false
0
NaN
null
undefined
"" // two double quotes with empty value
'' // two single quotes with empty value
If else example:
let state = 'TS';
let taxPer = 7;
if(text ==='TS')
{
taxPer = 17;
}
else
{
taxPer = 10;
}
console.log(taxPer);
output: 17
Switch Statement:
let state = 'TX';
switch (state)
case 'NY' :
console.log("NY");
break;
case 'TX':
console.log("TX");
break;
default:
console.log("default");
break;
}
for () loop:
for(let i=0;i<10;i++)
{
console.log(i);
}
while loop:
let i=10;
while(i<=10)
{
console.log(i);
i--;
}
Functions:
Example 1:
function showMessage()
{
console.log("hello world");
}
showMessage();
Example 2:
function showMessage(name,age)
{
console.log("Hello"+name, age);
}
showMessage('madhu',37);
output: Hello madhu 37
showMessage('madhu');
output: Hello madhu undefined
Example 3:
// function returning values
function ageCalculator(year)
{
if (year > 1980)
return 30;
else if(year > 1970)
return 40;
else
return 50;
}
Example 4:
//variable scope, scope is limited to its function.
function tripleSum(number)
{
let output = number*3;
return output;
}
console.log(tripleSum(3)); // print 9
console.log(output); // output variable is undefined (error)
Objects:
Example 1:
let student = {
name : "madhu",
rollno : 1224,
dept : "csit",
active : false
};
console.log(student.name); // madhu
console.log(student.rollno); // 1224
console.log(student.active); // false
Example 2:
//passing objects to functions
let card = {
suit : "diamonds",
value : "queen"
};
function changeSuit(card)
{
card.suit = "spades";
}
changeSuit(card);
console.log(card.suit);
}
Example 3:
//array of objects
let cards =
[
{
name : 'aa',
id : 123
},
{
name : 'bb',
id : 124
}
];
console.log(cards[1].id); //output is 123
Go to wiki and search for Built-in Objects for more information.
Example 4:
// NaN
let a = 2/0;
console.log(Number.isNaN(a)); // true
DOM
Document Object Model: defines how data on webpage is organized and manipulated.
Example 1:
//changing paragraph text
HTML
<p id="text-area"></p>
JavaScript
let paragraph = document.getElementById('text-area');
paragraph.innerText = "This is paragraph text…";
Example 2:
HTML
<button id="okButton">Ok</button>
JavaScript::
let okButton = document.getElementById('ok-button');
okButton.addEventListener('click', function() {
// code goes here
});
Example 3:
// ::Removing and adding elements back:: javascript
let paragraph = document.getElementById('text-area');
paragraph.style.display = 'none'; // remove it
paragraph.style.display = 'inline'; // add it back
Demo of our learnings:
HTML code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="title">Blackjack</h1>
<h4>by Mark Zamoyta</h4>
<p id="text-area">Welcome to Blackjack!</p>
<button id="new-game-button">New Game!</button>
<button id="hit-button">Hit!</button>
<button id="stay-button">Stay</button>
<script src="blackjack-m6.js"></script>
</body>
</html>
java script code:
http://plnkr.co/ --> click on 'launch editor' --> you would observe sample
settings are available on right hand side, using this we can do basic settings on plunker editor:
Java script is Case Sensitive.
Basic Hello World program
Add below line in script.js and click on run for output. You would see output in console of browser (press F12).
Example 1:
console.log("Hello World!!");
Example 2:
let aa = "this is",
bb = "example";
console.log(aa,bb);
Output in console of browser: this is example
Example 3:
let aa = 10.00;
let bb = 20.00;
console.log(aa+bb);
output: 30
Example 4:
let aa = 10.00;
let bb = "20.00";
console.log(aa+bb);
output: 1020.00
Operations in Java Script:
It is similar to java / c all of the + - * / % works as expected similar to other object oriented languages.
Comments in JavaScript:
// this is a comment
let name = "madhu";
or
// this is comment 1
//this is comment 2
let name = "madhu";
or
/* this is comment 1
this is comment 2 */
let name = "madhu";
or
let answer = 32; // this is freezing point
console.log(answer);
Boolean Data Types:
let flag = true;
console.log(flag, typeof(flag));
output: true "boolean"
Difference between undefined and null:
when a variable is declared without any value then its value is undefined.
let x;
console.log(x);
output: undefined // we can not assign undefined to a variable.
null can be assigned to a variable using our source code.
declaring and accessing array:
let a = [];
console.log(a[0]); // undefined
let a = ["a1","a2","a3"];
console.log(a[0]);
console.log(a[1]);
console.log(a[2]);
console.log(a);
let a = [1,2,3,4];
console.log(a);
console.log(a.length);
let values = [];
values.push(1);
values.push(2);
values.push(3);
console.log(values);
output: [1,2,3]
let values = [1,2,3];
values.pop();
console.log(values);
output: [1,2]
let values = [1,2,3];
let result = values.pop();
console.log(result);
output: 3 // this will work similar to stack push and pop by removing last inserted item (LIFO).
let values = [1,2,3,44];
let result = values.shift();
console.log(result, values);
output: 1, [2 3 44]
splice() method used to delete the elements in given range also insert some elements.
let values = [1,2,3,4,5];
let result = values.splice(0,1);
console.log(values);
output: [2,3,4,5] // from 0th index delete one element
let values = [1,2,3,4,5];
let result = values.splice(0,1,6,7);
console.log(values);
output: [6,7, 2,3,4,5] // from 0th index delete one element, then insert 6 & 7.
we have several methods on arrays as specified here.
Player Cards Game Phase 1 for POC:
let deck = [ "Ace of Spades",
"Two of Spades",
"Three of Spades"];
let playerCards = [ deck[0], deck[2]];
console.log("Welcome to BlackJack");
console.log("You are dealt:");
console.log(" "+playerCards[0]);
console.log(" "+playerCards[1]);
Program flow:
let text = 'Hyderabad';
let num = 7;
if(text === 'Hyderabad')
{
num = 17;
}
console.log(num);
output: 17
what qualifies false in javascript:
false
0
NaN
null
undefined
"" // two double quotes with empty value
'' // two single quotes with empty value
If else example:
let state = 'TS';
let taxPer = 7;
if(text ==='TS')
{
taxPer = 17;
}
else
{
taxPer = 10;
}
console.log(taxPer);
output: 17
Switch Statement:
let state = 'TX';
switch (state)
case 'NY' :
console.log("NY");
break;
case 'TX':
console.log("TX");
break;
default:
console.log("default");
break;
}
for () loop:
for(let i=0;i<10;i++)
{
console.log(i);
}
while loop:
let i=10;
while(i<=10)
{
console.log(i);
i--;
}
Functions:
Example 1:
function showMessage()
{
console.log("hello world");
}
showMessage();
Example 2:
function showMessage(name,age)
{
console.log("Hello"+name, age);
}
showMessage('madhu',37);
output: Hello madhu 37
showMessage('madhu');
output: Hello madhu undefined
Example 3:
// function returning values
function ageCalculator(year)
{
if (year > 1980)
return 30;
else if(year > 1970)
return 40;
else
return 50;
}
Example 4:
//variable scope, scope is limited to its function.
function tripleSum(number)
{
let output = number*3;
return output;
}
console.log(tripleSum(3)); // print 9
console.log(output); // output variable is undefined (error)
Objects:
Example 1:
let student = {
name : "madhu",
rollno : 1224,
dept : "csit",
active : false
};
console.log(student.name); // madhu
console.log(student.rollno); // 1224
console.log(student.active); // false
Example 2:
//passing objects to functions
let card = {
suit : "diamonds",
value : "queen"
};
function changeSuit(card)
{
card.suit = "spades";
}
changeSuit(card);
console.log(card.suit);
}
Example 3:
//array of objects
let cards =
[
{
name : 'aa',
id : 123
},
{
name : 'bb',
id : 124
}
];
console.log(cards[1].id); //output is 123
Go to wiki and search for Built-in Objects for more information.
Example 4:
// NaN
let a = 2/0;
console.log(Number.isNaN(a)); // true
DOM
Document Object Model: defines how data on webpage is organized and manipulated.
Example 1:
//changing paragraph text
HTML
<p id="text-area"></p>
JavaScript
let paragraph = document.getElementById('text-area');
paragraph.innerText = "This is paragraph text…";
Example 2:
HTML
<button id="okButton">Ok</button>
JavaScript::
let okButton = document.getElementById('ok-button');
okButton.addEventListener('click', function() {
// code goes here
});
Example 3:
// ::Removing and adding elements back:: javascript
let paragraph = document.getElementById('text-area');
paragraph.style.display = 'none'; // remove it
paragraph.style.display = 'inline'; // add it back
Demo of our learnings:
HTML code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="title">Blackjack</h1>
<h4>by Mark Zamoyta</h4>
<p id="text-area">Welcome to Blackjack!</p>
<button id="new-game-button">New Game!</button>
<button id="hit-button">Hit!</button>
<button id="stay-button">Stay</button>
<script src="blackjack-m6.js"></script>
</body>
</html>
java script code:
// // Blackjack // by Mark Zamoyta // // Card variables let suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades'], values = ['Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two']; // DOM variables let textArea = document.getElementById('text-area'), newGameButton = document.getElementById('new-game-button'), hitButton = document.getElementById('hit-button'), stayButton = document.getElementById('stay-button'); // Game variables let gameStarted = false, gameOver = false, playerWon = false, dealerCards = [], playerCards = [], dealerScore = 0, playerScore = 0, deck = []; hitButton.style.display = 'none'; stayButton.style.display = 'none'; showStatus(); newGameButton.addEventListener('click', function() { gameStarted = true; gameOver = false; playerWon = false; deck = createDeck(); shuffleDeck(deck); dealerCards = [ getNextCard(), getNextCard() ]; playerCards = [ getNextCard(), getNextCard() ]; newGameButton.style.display = 'none'; hitButton.style.display = 'inline'; stayButton.style.display = 'inline'; showStatus(); }); hitButton.addEventListener('click', function() { playerCards.push(getNextCard()); checkForEndOfGame(); showStatus(); }); stayButton.addEventListener('click', function() { gameOver = true; checkForEndOfGame(); showStatus(); }); function createDeck() { let deck = []; for (let suitIdx = 0; suitIdx < suits.length; suitIdx++) { for (let valueIdx = 0; valueIdx < values.length; valueIdx++) { let card = { suit: suits[suitIdx], value: values[valueIdx] }; deck.push( card ); } } return deck; } function shuffleDeck(deck) { for (let i = 0; i < deck.length; i++) { let swapIdx = Math.trunc(Math.random() * deck.length); let tmp = deck[swapIdx]; deck[swapIdx] = deck[i]; deck[i] = tmp; } } function getCardString(card) { return card.value + ' of ' + card.suit; } function getNextCard() { return deck.shift(); } function getCardNumericValue(card) { switch(card.value) { case 'Ace': return 1; case 'Two': return 2; case 'Three': return 3; case 'Four': return 4; case 'Five': return 5; case 'Six': return 6; case 'Seven': return 7; case 'Eight': return 8; case 'Nine': return 9; default: return 10; } } function getScore(cardArray) { let score = 0; let hasAce = false; for (let i = 0; i < cardArray.length; i++) { let card = cardArray[i]; score += getCardNumericValue(card); if (card.value === 'Ace') { hasAce = true; } } if (hasAce && score + 10 <= 21) { return score + 10; } return score; } function updateScores() { dealerScore = getScore(dealerCards); playerScore = getScore(playerCards); } function checkForEndOfGame() { updateScores(); if (gameOver) { // let dealer take cards while(dealerScore < playerScore && playerScore <= 21 && dealerScore <= 21) { dealerCards.push(getNextCard()); updateScores(); } } if (playerScore > 21) { playerWon = false; gameOver = true; } else if (dealerScore > 21) { playerWon = true; gameOver = true; } else if (gameOver) { if (playerScore > dealerScore) { playerWon = true; } else { playerWon = false; } } } function showStatus() { if (!gameStarted) { textArea.innerText = 'Welcome to Blackjack!'; return; } let dealerCardString = ''; for (let i=0; i < dealerCards.length; i++) { dealerCardString += getCardString(dealerCards[i]) + '\n'; } let playerCardString = ''; for (let i=0; i < playerCards.length; i++) { playerCardString += getCardString(playerCards[i]) + '\n'; } updateScores(); textArea.innerText = 'Dealer has:\n' + dealerCardString + '(score: '+ dealerScore + ')\n\n' + 'Player has:\n' + playerCardString + '(score: '+ playerScore + ')\n\n'; if (gameOver) { if (playerWon) { textArea.innerText += "YOU WIN!"; } else { textArea.innerText += "DEALER WINS"; } newGameButton.style.display = 'inline'; hitButton.style.display = 'none'; stayButton.style.display = 'none'; } }
No comments:
Post a Comment