Variabel Hacks
An introduction to JavaScript variables, input, and output
Popcorn Hack 1
Make a code cell that show usage of compound assignment in a Data Type Operations.
%%html
<div>
<label for="strength">Enter Strength (1, 2, 3, 4, 5):</label>
<input type="number" id="strength" name="strength" min="1" max="5" step="1" value="1">
<button onclick="fight()">FIGHT!</button>
<lable for="output" id="output"></lable>
</div>
<script>
if (typeof playerStats === 'undefined') {
var playerStats = { // Use var to define it globally in this context
strength: null,
test: 3
};
}
function getStrength(){
const amount = document.getElementById("strength").value
let output = document.getElementById("output");
if (amount > 5 || amount < 1){
console.warn("entered invaled number")
output.innerHTML = "Not a valid number"
return false
}
console.log("setting strength to:" + amount)
playerStats.strength = amount
console.log(playerStats)
return amount
}
function getEnemyStrength(){
let enemyStrength = Math.round(Math.random() * (5 - 1) + 1)
console.log(enemyStrength)
return enemyStrength
}
function fight(){
if(playerStats == null || playerStats == undefined) {return warn("player stats not found or loaded")}
console.log("starting battle")
const enemyStrength = getEnemyStrength()
const playerStrength = getStrength()
let output = document.getElementById("output");
if (playerStrength == false){return}
let won = false
if (playerStrength == enemyStrength){
console.log("TIE")
output.innerHTML = "TIE"
return
}
if (playerStrength > enemyStrength){
console.log("WON")
output.innerHTML = "WON"
return
}else{
console.log("LOST")
output.innerHTML = "LOST"
return
}
}
</script>
Popcorn Hack 2
Make a code cell that changes block into a square, versus HD resolution
%%html
<p>This example uses data types, operators, and functions to scale a block based on a user-defined width.</p>
<!-- Input definitions -->
<div>
<label for="width">Enter Width (1280, 1920, 2560, 3840):</label>
<input type="number" id="width" name="width" min="1280" max="3840" step="640" value="1280">
<button onclick="submitScale()">Submit</button>
</div>
<!-- Document Object Model (DOM) output locations -->
<div id="output"></div>
<div id="error"></div>
<!-- Block display -->
<div id="block" style="width: 64px; height: 36px; background-color: red;"></div>
<script>
// Function to validate and output the scale value
function submitScale() {
const BLOCK_SCALE_DIVISOR = 20;
const ASPECT_RATIO = 9 / 16;
let block = document.getElementById('block');
let width = parseInt(document.getElementById('width').value);
// Restrict sizes to common HD resolutions
if (width === 1280 || width === 1920 || width === 2560 || width === 3840 || width > 0 || width < 0) {
// Calculate height based on 16:9 aspect ratio
let height = width;
// Calculate block size as 1/20th of the scale dimensions
let blockSize = Math.min(width, height) / BLOCK_SCALE_DIVISOR;
// Set/clear error messages when the value is valid
document.getElementById('error').innerHTML = "";
// Output the scale value to the console
document.getElementById('output').innerHTML = "Scale set to: " + width + " x " + height + " (Block size: " + blockSize + "px)";
// Adjust the size of the block
block.style.width = blockSize + "px";
block.style.height = blockSize + "px";
} else {
// Set/clear output messages when there is an error
document.getElementById('output').innerHTML = "";
// Output an error message to the console
// Output an error message to the HTML page
document.getElementById('error').innerHTML = "Invalid HD resolution: " + width;
// Clear the block size
block.style.width = "0px";
block.style.height = "0px";
}
console.error("HD resolution:", block.style.width, "x", block.style.height);
}
</script>
This example uses data types, operators, and functions to scale a block based on a user-defined width.
Popcorn Hack 3
Try to place a square in every corner.
%%html
<p>This example uses data types, operators, and functions to scale a block based on a user-defined width.</p>
<!-- Input definitions -->
<div>
<label for="widthCanvas">Enter Width (1280, 1920, 2560, 3840):</label>
<input type="number" id="widthCanvas" name="widthCanvas" min="1280" max="3840" step="640" value="1280">
<button onclick="submitScaleImg()">Submit</button>
</div>
<!-- Document Object Model (DOM) output locations -->
<div id="outputMsg"></div>
<div id="errorMsg"></div>
<!-- Canvas for background display -->
<canvas id="canvas"></canvas>
<script>
// Function to validate and output the scale value
function submitScaleImg() {
const BLOCK_SCALE_DIVISOR = 20;
const ASPECT_RATIO = 9 / 16;
const SCALE_DOWN_FACTOR = 0.5;
let canvas = document.getElementById('canvas');
let c = canvas.getContext('2d');
let width = parseInt(document.getElementById('widthCanvas').value);
// Restrict sizes to common HD resolutions
if (width === 1280 || width === 1920 || width === 2560 || width === 3840) {
// Calculate height based on 16:9 aspect ratio
let height = Math.round(width * ASPECT_RATIO);
// Set the canvas dimensions
canvas.width = width * SCALE_DOWN_FACTOR;
canvas.height = height * SCALE_DOWN_FACTOR;
// Calculate block size as 1/20th of the scale dimensions and scale down by 50%
let blockSize = Math.min(width, height) / BLOCK_SCALE_DIVISOR;
// Set/clear error messages when the value is valid
document.getElementById('errorMsg').innerHTML = "";
// Output the scale value to the console
document.getElementById('outputMsg').innerHTML = "Scale set to: " + width + " x " + height + " (Block size: " + blockSize + "px)";
// Load background image
let imageBackground = new Image();
imageBackground.src = 'https://samayass.github.io/samayaCSA/images/background.png';
imageBackground.onload = function() {
// Clear the canvas before drawing
c.clearRect(0, 0, canvas.width, canvas.height);
// Draw the background image on the canvas
c.drawImage(imageBackground, 0, 0, canvas.width, canvas.height);
// Draw the red block on the canvas
c.fillStyle = 'red';
c.fillRect((canvas.width) - blockSize, (canvas.height) - blockSize, blockSize, blockSize);//bottom right
c.fillRect((canvas.width) - blockSize, (canvas.height) - canvas.height, blockSize, blockSize);//top right
c.fillRect((canvas.width) - canvas.width, (canvas.height) - blockSize, blockSize, blockSize);//bottom left
c.fillRect((canvas.width) - canvas.width, (canvas.height) - canvas.height, blockSize, blockSize);//bottom left
};
} else {
// Set/clear output messages when there is an error
document.getElementById('outputMsg').innerHTML = "";
// Output an error message to the console
console.error("Invalid HD resolution:", width);
// Output an error message to the HTML page
document.getElementById('errorMsg').innerHTML = "Invalid HD resolution: " + width;
// Clear the canvas
c.clearRect(0, 0, canvas.width, canvas.height);
}
}
</script>
This example uses data types, operators, and functions to scale a block based on a user-defined width.
What is what?
In this section I will explain what something is with a code example
JSON Objects
%%html
<script>
/* in "" I have the index name of the value which is optinal but makes the
code easier to understand */
let car = {
"color" : "red",
"Year made" : 3490,
"maker" : "Ford",
"4 wheel drive" : true,
"can fly" : true
}
console.log(car)
</script>
JASON Arrays
%%html
<script>
(function() {//function helps prevent the variable erroring i dont know hy it erros outside of a scope
let numbers = [89, 23, 27, 84, 34, 19];
console.log(numbers[1]);
})();
</script>
Input/Output
%%html
<div>
<label for="enterLabel">Enter Number</label> <!-- text label-->
<input type="number" id="numberInputed" name="number" step="1" value="1"><!-- input section-->
<button onclick="inputFunction()">Submit!</button><!--button-->
</div>
<script>
function inputFunction(){
console.log(document.getElementById("numberInputed").value)
}
</script>
Data Types
%%html
<script>
/*
Types of variables
to create a variable you need to put let,cont, or var infront of the name
followed by an = or no = to set its value
-let
let makes the variable only recognised insed its scope
-const
const makes the variable only recognised insed its scope but its value can not be changed
-var
var makes the variable reconisable anywhere in the script including outside its scope
*/
if (typeof number3 === 'undefined') {
var number3 = 9
}
variables()
function variables(){
let number1 = 2
const number2 = 9
console.log(number3)//being called outside of scope but still works
}
variables()
</script>
Number:
- Represents numerical values, health and timeInMilliSeconds
- String:
- Represents text, such as the user’s name or keypress.
- Boolean:
- Represents true/false values, such as isAlive.
- Undefined:
- Represents a variable that has been declared but not yet assigned a value.
- Null:
- Represents the intentional absence of any object value, such as an empty inventory slot.
- Symbol:
- Represents a unique and immutable value, often used as unique identifiers for game objects.
- BigInt:
- Represents very large integers, such as the total number of points accumulated over many games.
Operaters
%%html
<script>
function operate(num1,num2){
console.log(num1 + " + " + num2 + " = " + (num1+num2))
console.log(num1 + " - " + num2 + " = " + (num1-num2))
console.log(num1 + " * " + num2 + " = " + (num1*num2))
console.log(num1 + " / " + num2 + " = " + (num1/num2))
}
operate(5,10)
</script>