diff --git a/Blogs.md b/Blogs.md new file mode 100644 index 000000000..092fd1d68 --- /dev/null +++ b/Blogs.md @@ -0,0 +1,10 @@ +--- +layout: post +title: Blogs +description:Blogs +categories: [Javascript] +menu: nav/javascript_project.html +permalink: /javascript/project/Blogs +toc: true +comments: false +--- diff --git a/Makefile b/Makefile index 7d9cdaf86..0e48753f0 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Configuration, override port with usage: make PORT=4200 PORT ?= 4100 -REPO_NAME ?= student_2025 +REPO_NAME ?= Amal_2025 LOG_FILE = /tmp/jekyll$(PORT).log SHELL = /bin/bash -c @@ -92,4 +92,4 @@ stop: @# kills previously running logging processes @@ps aux | awk -v log_file=$(LOG_FILE) '$$0 ~ "tail -f " log_file { print $$2 }' | xargs kill >/dev/null 2>&1 || true @# removes log - @rm -f $(LOG_FILE) + @rm -f $(LOG_FILE) \ No newline at end of file diff --git a/README4YML.md b/README4YML.md deleted file mode 100644 index defd8f31a..000000000 --- a/README4YML.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -layout: post -title: Readme -toc: true ---- - -{% include_relative README.md %} diff --git a/Snake.md b/Snake.md new file mode 100644 index 000000000..aa3806558 --- /dev/null +++ b/Snake.md @@ -0,0 +1,389 @@ +--- +layout: post +title: Snake Game +description: A Javascript Snake game that contains score and preferences. +categories: [Javascript] +menu: nav/javascript_project.html +permalink: /javascript/project/snake +toc: true +comments: false +--- + + + + +
+
+

Snake score: 0

+
+
+ + + +
+

Game Over, press space to try again

+ new game + settings +
+ + + +
+

Settings Screen, press space to go back to playing

+ new game +
+

Speed: + + + + + + +

+

Wall: + + + + +

+
+
+
+ + +``` diff --git a/_config.yml b/_config.yml index 4f8d1eb3b..fdc1298d8 100644 --- a/_config.yml +++ b/_config.yml @@ -1,9 +1,24 @@ +header_pages: + - navigation/snake.md + - navigation/blog.md + - navigation/search.md + - navigation/about.md + - navigation/rpg2x.md + - navigation/typing-game.md + - navigation/codenite.md + - navigation/calculator.md + - navigation/sccer.md + - navigation/Home-Page.md + - navigation/ideas.md + - navigation/blogs.md + - README4YML.md + title: Nighthawk Pages description: "Class of 2025" owner_name: John Mortensen github_username: nighthawkcoders -github_repo: "student_2025" -baseurl: "/student_2025" +github_repo: "Amal_2025" +baseurl: "/Amal_2025" future: true remote_theme: jekyll/minima minima: @@ -13,14 +28,12 @@ minima: - { platform: x, user_url: "https://x.com/NighthawkCoding/" } - { platform: youtube, user_url: "https://www.youtube.com/@nighthawkcodingsociety2868" } # remote_theme: pages-themes/midnight@v0.2.0 -# remote_theme: pages-themes/cayman@v0.2.0 +remote_theme: pages-themes/cayman@v0.2.0 # remote_theme: pages-themes/dinky@v0.2.0 -# remote_theme: pages-themes/minimal@v0.2.0 # remote_theme: pages-themes/time-machine@v0.2.0 +# remote_theme: pages-themes/architect@v0.2.0 + plugins: - jekyll-remote-theme -header_pages: - - navigation/blog.md - - navigation/search.md - - navigation/about.md - - README4YML.md + + diff --git a/_includes/nav/home.html b/_includes/nav/home.html new file mode 100644 index 000000000..f19cee900 --- /dev/null +++ b/_includes/nav/home.html @@ -0,0 +1,56 @@ + + + + + + +
CSP
+ diff --git a/_includes/nav/javascript_project.html b/_includes/nav/javascript_project.html new file mode 100644 index 000000000..3ea0d6ef1 --- /dev/null +++ b/_includes/nav/javascript_project.html @@ -0,0 +1,13 @@ + + + + + + + + + + + + +
PlayBinaryCalculatorGame-of-LifeMusicSnakeBlogs
diff --git a/_notebooks/2024-10-25-variables.ipynb b/_notebooks/2024-10-25-variables.ipynb new file mode 100644 index 000000000..38a28042c --- /dev/null +++ b/_notebooks/2024-10-25-variables.ipynb @@ -0,0 +1,496 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "layout: post\n", + "title: JavaScript Variables\n", + "description: JavaScript Variables\n", + "categories: [JavaScript]\n", + "comments: True\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Variables in JavaScript\n", + "\n", + " Taught by Aria, Cason, and Ethan\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What are variables in JavaScript?\n", + "Variables in JavaScript are used to store data that can be referenced and manipulated in a program. They act as containers for values and can hold different types of data, such as numbers, strings, objects, and more.\n", + "\n", + "- Variables are used to simplify code\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The three types of keywords for a variable declaration in JavaScript are\n", + " var, let, and const. \n", + " \n", + " **NOTE:** Var is an outdated keyword in Javascript. \n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Creating variables\n", + "\n", + "Variables can be created and assigned values by using the assignment operator \"=\"\n", + "\n", + "\n", + "### Variable naming\n", + "\n", + "- **Camel Case (camelCase):** Commonly used in JavaScript, Java, and C#. Example: `myVariableName`\n", + "\n", + "- **Pascal Case (PascalCase):** Often used in C#, and for class names in many languages. Example: `MyVariableName`\n", + "\n", + "- **Snake Case (snake_case):** Frequently used in Python and Ruby. Example: `my_variable_name`\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nconst userName = \"Mario\"; \nlet favFood = \"spaghetti\";\nconst favSport = \"kart racing\";\n\nconsole.log(\"Hello! You can call me \" + userName); //This will print \"Hello! You can call me Mario\"\nconsole.log(\"I LOVE eating \" + favFood); //This will print \"I LOVE eating Spaghetti\"\nconsole.log(\"My favorite sport is \" + favSport); //This will print \"My favorite sport is kart racing\"\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%javascript\n", + "\n", + "const userName = \"Mario\"; \n", + "let favFood = \"spaghetti\";\n", + "const favSport = \"kart racing\";\n", + "\n", + "console.log(\"Hello! You can call me \" + userName); //This will print \"Hello! You can call me Mario\"\n", + "console.log(\"I LOVE eating \" + favFood); //This will print \"I LOVE eating Spaghetti\"\n", + "console.log(\"My favorite sport is \" + favSport); //This will print \"My favorite sport is kart racing\"" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- As you can see, because this is in javascript, camelCase is being used\n", + "\n", + "- Once a variable is created, it may be used throughout the entire program\n", + "\n", + "*Here it is in use, open your console to see the output!*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Variable Types\n", + "\n", + "### Data Types in JavaScript:\n", + "- Primitive Data Types:\n", + " - `Number` \n", + " - `String`\n", + " - `Boolean`\n", + " - `Null`\n", + " - `Undefined`\n", + " - `Symbol`\n", + "- Non-primitive Data Types:\n", + " - `Object`\n", + " - `Array`\n", + " - `Function`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "### Integer Variables in JavaScript\n", + "\n", + "Integer variables in JavaScript are used to store whole numbers without any decimal points. They can be positive, negative, or zero. In JavaScript, integers are typically represented using the `number` data type.\n", + "\n", + "### Example:\n" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nconst a = 25; //This is a number variable\nlet b = 10; //This is a number variable\nlet sum = a + b; //This is a number variable\n\nconsole.log(a); //This will print 25\nconsole.log(b); //This will print 10\nconsole.log(sum); //This will print 35\nconsole.log(a * b); //This will print 250\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "\n", + "const a = 25; //This is a number variable\n", + "let b = 10; //This is a number variable\n", + "let sum = a + b; //This is a number variable\n", + "\n", + "console.log(a); //This will print 25\n", + "console.log(b); //This will print 10\n", + "console.log(sum); //This will print 35\n", + "console.log(a * b); //This will print 250" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Strings\n", + "\n", + "When phrases or sentences are assigned a variable name, they can be referenced later.\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "\n", + "\n", + "let question = \"How much do you like this lesson?\"; //This is a string variable\n", + "let answer = \"a lot!\"; //This is a string variable\n", + "\n", + "console.log(question); //This will print \"How much do you like this lesson?\"\n", + "console.log(answer); //This will print \"a lot!\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Popcorn Hack #1\n", + "\n", + "### Open the notebook with the Hacks in it, \"2024-10-29-variables_popcorn_hax.ipynb\", and complete the first popcorn hack\n", + "\n", + "### Booleans\n", + "\n", + "Booleans in JavaScript are a fundamental data type that can hold one of two values: true or false. They are often used in conditional statements to control the flow of a program.\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nconst isCoder = true; //This is a boolean variable\nconst isDesigner = false; //This is a boolean variable\n\nconsole.log(isCoder); //This will print true\nconsole.log(isDesigner); //This will print false\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "\n", + "const isCoder = true; //This is a boolean variable\n", + "const isDesigner = false; //This is a boolean variable\n", + "\n", + "console.log(isCoder); //This will print true\n", + "console.log(isDesigner); //This will print false" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Nulls" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `null` value signifies the deliberate absence of any object value. It is commonly used to indicate that a variable should not hold any value.\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nlet myBankBalance = null; //This is a null variable\n\nconsole.log(myBankBalance); //This will print null \n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + "\n", + "let myBankBalance = null; //This is a null variable\n", + "\n", + "console.log(myBankBalance); //This will print null " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Undefined\n", + "\n", + "A variable in JavaScript that has been declared but not assigned a value will have the value `undefined`.\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nlet myHeight; //This is an undefined variable\n\nconsole.log(myHeight); //This will print undefined\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "\n", + "let myHeight; //This is an undefined variable\n", + "\n", + "console.log(myHeight); //This will print undefined" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Symbol\n", + "\n", + "Symbols are unique and immutable data types primarily used as object property keys.\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nlet myRPG = Symbol(\"Pokemon\"); //This is a symbol variable\n\nconsole.log(myRPG); //This will print Symbol(Pokemon)\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + "\n", + "let myRPG = Symbol(\"Pokemon\"); //This is a symbol variable\n", + "\n", + "console.log(myRPG); //This will print Symbol(Pokemon)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Popcorn Hack #2\n", + "\n", + "### Open the notebook with the Hacks in it, \"2024-10-29-variables_popcorn_hax.ipynb\", and complete the second popcorn hack" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Arrays and Objects\n", + "\n", + "**Arrays**\n", + "\n", + "Arrays are data structures that allow you to store multiple values in a single variable. Each value in an array is called an element, and arrays can hold values of any data type.\n", + "\n", + "**Objects**\n", + "\n", + "Objects are collections of key-value pairs, where each key (also known as a property) is associated with a value. Objects are a fundamental data type in JavaScript and are similar to dictionaries in Python. They are also referred to as **JSON Objects**.\n", + "\n", + "**Functions**\n", + "\n", + " a block of code designed to perform a particular task. Functions are fundamental building blocks in JavaScript and allow you to encapsulate code for reuse, modularity, and organization\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "//This is an array variable\nlet characterPosition = [\"1 fish\", \"2 fish\", \"red fish\", \"blue fish\"]; //This is an array variable\n console.log(characterPosition); //This will print [\"1 fish\", \"2 fish\", \"red fish\", \"blue fish\"]\n\n //This is an object variable\n let character = \n {name: \"Mario\", \n age: 35, \n height: 1.55, \n weight: 70\n }; //This is an object variable\n console.log(character); //This will print {name: \"Mario\", age: 35, height: 1.55, weight: 70}\n\n //This is a function variable\n function request(song) {\n return \"Now playing \" + songName + \" by \" + artistName;\n }\n\nlet songName = \"Despacito\"; //This is a string variable\nlet artistName = \"Luis Fonsi\"; //This is a string variable\n\n console.log(request(\"Despacito\")); //This will print \"Now playing Despacito by Luis Fonsi\"\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + "//This is an array variable\n", + "let characterPosition = [\"1 fish\", \"2 fish\", \"red fish\", \"blue fish\"]; //This is an array variable\n", + " console.log(characterPosition); //This will print [\"1 fish\", \"2 fish\", \"red fish\", \"blue fish\"]\n", + "\n", + " //This is an object variable\n", + " let character = \n", + " {name: \"Mario\", \n", + " age: 35, \n", + " height: 1.55, \n", + " weight: 70\n", + " }; //This is an object variable\n", + " console.log(character); //This will print {name: \"Mario\", age: 35, height: 1.55, weight: 70}\n", + "\n", + " //This is a function variable\n", + " function request(song) {\n", + " return \"Now playing \" + songName + \" by \" + artistName;\n", + " }\n", + "\n", + "let songName = \"She\"; //This is a string variable\n", + "let artistName = \"Tyler the Creator and Frank Ocean\"; //This is a string variable\n", + "\n", + " console.log(request(\"Despacito\")); //This will print \"Now playing Despacito by Luis Fonsi\"" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/_notebooks/2024-10-28-variables_hw.ipynb b/_notebooks/2024-10-28-variables_hw.ipynb new file mode 100644 index 000000000..bd279ec27 --- /dev/null +++ b/_notebooks/2024-10-28-variables_hw.ipynb @@ -0,0 +1,61 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Variables Homework (Show what you know!) \n", + "\n", + "### Homework Problem: Understanding JavaScript Variables \n", + "\n", + "### Creating Variables\n", + "\n", + "\n", + "1. **Create three variables as an object variable**:\n", + " - A variable called `studentName` that stores your name as a string.\n", + " - A variable called `age` that stores your age as a number.\n", + " - A variable called `isStudent` that stores a boolean value indicating whether you are a student (use `true` or `false`).\n", + "\n", + " 2. **Create a function variable that displays that your favorite song is playing**:\n", + " \n", + " - A variable called `favoriteSong` that stores the name of your favorite song.\n", + " - A variable called `songArtist` that stores the song's artist.\n", + " - A function called `playFavoriteSong` that logs a message saying \"Now playing [favoriteSong] by [songArtist]\".\n", + "\n", + "\n", + "\n", + "3. **Using the variables you created**, write a sentence using `console.log()` to display:\n", + " - Your name.\n", + " - Your age.\n", + " - Whether you are a student.\n", + " - An output that states that your favorite song is now playing\n", + "\n", + "\n", + " Example output:\n", + "My name is [Your Name], I am [Your Age] years old, and it is [true/false] that I am a student. \n", + "Now playing Champion by Kanye West" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/2024-10-29-variables_popcorn_hax.ipynb b/_notebooks/2024-10-29-variables_popcorn_hax.ipynb new file mode 100644 index 000000000..9d77794a4 --- /dev/null +++ b/_notebooks/2024-10-29-variables_popcorn_hax.ipynb @@ -0,0 +1,126 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Variables Hacks \n", + "\n", + " Taught by Aria, Cason, and Ethan" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "plaintext" + } + }, + "source": [ + "\n", + "### Popcorn Hack 1: Variable Naming, and Strings in JavaScript \n", + "\n", + "#### Instructions:\n", + "1. Open a new cell and set its type to `Code`.\n", + "\n", + "2. Using the correct `variable naming case` for JavaScript \n", + "\n", + "3. Create a string variable for `\"gameQuestion\"` and let it equal: `\"My favorite video game is \"`\n", + "\n", + "4. create a variable for `\"gameAnswer\"` and let it equal: your favorite game\n", + "\n", + "5. output your `gameQuestion` and `gameAnswer` to the console `[EX: console.log(gameQuestion + gameAnswer);]`\n", + "\n", + "6. Open your console and see if it displayed the correct message \n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "data": { + "application/javascript": "let favorite-game==school\nlet gameanswer ==favorite-game\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "let favoritegame==fortnite\n", + "let gameanswer==fortnite\n", + "console.log(favoritegame+gameanswer)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "source": [ + "\n", + "### Popcorn Hack 2: Null, Undefined, Symbol, in JavaScript \n", + "\n", + "#### Instructions:\n", + "\n", + "1. Open a new cell and set its type to `Code`.\n", + "\n", + "2. Create a variable `nullVar` and set it to `null`.\n", + "\n", + "3. Create a variable `undefinedVar` and leave it uninitialized.\n", + "\n", + "4. Create a variable `symbolVar` and set it to a new Symbol with a description of your choice. `[EX: let myRPG = Symbol(\"Pokemon\");]`\n", + "\n", + "5. Output all three variables to the console using `console.log()`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%%js \n", + "\n", + "let nullvar = null;\n", + "console.log(myBankBalance);\n", + "let undefinedvar;\n", + "console.log(undefinedvar);\n", + "\n", + "\n", + "\n", + "\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Foundation/2024-08-21-sprint1_plan.ipynb b/_notebooks/Foundation/2024-08-21-sprint1_plan.ipynb index 7ecbc1151..9e0c3e669 100644 --- a/_notebooks/Foundation/2024-08-21-sprint1_plan.ipynb +++ b/_notebooks/Foundation/2024-08-21-sprint1_plan.ipynb @@ -67,8 +67,14 @@ } ], "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, "language_info": { - "name": "python" + "name": "python", + "version": "3.10.12" } }, "nbformat": 4, diff --git a/_notebooks/Foundation/Sprint1/2024-09-15-javascript_output_objects.ipynb b/_notebooks/Foundation/Sprint1/2024-09-15-javascript_output_objects.ipynb new file mode 100644 index 000000000..d3a661850 --- /dev/null +++ b/_notebooks/Foundation/Sprint1/2024-09-15-javascript_output_objects.ipynb @@ -0,0 +1,625 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "layout: post\n", + "title: JS Output w/ Objects\n", + "description: Quick launch into Variables, Functions, Arrays, Classes, Objects.\n", + "categories: [JavaScript]\n", + "---" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## JavaScript and Jupyter references\n", + "> JavaScript is the most important language you need to learn as a frontend developer. Jupyter Notebooks is a convenient way to learn portions of the language without the overhead of creating a full Website. \n", + "\n", + "- JavaScript / Jupyter General References\n", + " - [W3Schools HTML Reference](https://www.w3schools.com/html/default.asp)\n", + " - [W3Schools JS Reference](https://www.w3schools.com/js/)\n", + " - Theme setup for Jupyter [Article](https://linuxhint.com/change-theme-jupyter-notebook/). Or do these commands from shell...\n", + " - Install pip: pip install jupyterthemes\n", + " - Revert to original theme: jt -r \n", + " - List themes: jt -l\n", + " - Install with Theme, Name, Logo: jt -t onedork -T -N -kl" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### output using HTML and CSS\n", + " Multiple cells are used to setup HTML in this lesson. Many of the JavaScript cells will use the output tag(s) to write into the HTML that has been setup. \n", + "- %%html is used to setup HTML code block\n", + "- \"style\" tag enables visuals customization\n", + "- \"div\" tag is setup to receive data" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [], + "source": [ + "%%html \n", + "\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
\n", + " Hello!\n", + "
\n", + " \n", + "" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### other outputs explored\n", + "There are several ways to ouput the classic introduction message: \"Hello, World!\" \n", + "- Before you go further, open Console on your Browser. JavaScript developer leaves Console open all the time!!!\n", + "- The function console.log() outputs to Console, this is often used for inspection or debugging.\n", + "- \"Hello, World\" is a String literal. This is the referred to as Static text, as it does not change. Developer call this a hard coded string.\n", + "- \"Hello, World\" literal is a parameter to console.log(), element.txt() and alert().\n", + "- The element.textContent is part of Jupyter Notebook %%js magic. This is convenient for Notebook and testing.\n", + "- The alert command outputs the parameter to a dialog box, so you can see it in this Jupyter notebook. The alert commands are shown, but are commented out as the stop run all execution of the notebook.\n", + "- Note, in a Web Application Debugging: An alert is often used for less savy Developers. Console is used by more savy developers; console often requires setting up a lot of outputs. Source level debugging is the most powerful solution for debugging and does not require alert or console commands." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js // required to allow cell to be JavaScript enabled\n", + "\n", + "console.log(\"JavaScript/Jupyter Output Intro\");\n", + "\n", + "// Browser Console output; debugging or tracing\n", + "console.log(\"Hello, World!\");\n", + "\n", + "// HTML page output using DOM (Document Object Model) from previous cell\n", + "document.getElementById(\"output\").textContent = \"Hello, World!\";\n", + "\n", + "// Jupyter Only, output for development\n", + "element.append(\"Hello, World!\"); // element is an output option as part of %%js magic\n", + "\n", + "// alert(\"Hello, World!\");" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### multiple outputs using a variable\n", + "This second example is a new sequence of code, two or more lines of code forms a sequence. This example defines a variable, thank goodness!!! In the previous example we were typing the string `\"Hello, World\" over and over`. Observe with the variable `msg=\"Hello, World!\";` we type the string once and now use `msg` over and over.\n", + "- The variable \"var msg =\" is used to capture the data\n", + "- The console.log(msg) outputs to console, be sure to Inspect it!\n", + "- The element.text() is part of Jupyter Notebooks and displays as output blow the code on this page. Until we build up some more interesting data for Web Site, we will not use be using the Python HTML, CSS technique.\n", + "- The alert(msg) works the same as previous, but as the other commands uses msg as parameter." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "console.log(\"Variable Definition\");\n", + "\n", + "var msg = \"Hello, World Again!\";\n", + "\n", + "// Use msg to output code to Console and Jupyter Notebook\n", + "console.log(msg); //right click browser select Inspect, then select Console to view\n", + "document.getElementById(\"output\").textContent = msg;\n", + "element.append(msg);\n", + "//alert(msg);" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### output showing use of a function\n", + "This example passes the defined variable \"msg\" to the newly defined \"function logIt(output)\".\n", + "- There are multiple steps in this code..\n", + " - The definition of the function: \"function logIt(output) {}\" and everything between curly braces is the definitions of the function. Passing a parameter is required when you call this function.\n", + " - The \"call to the function:\"logIt(msg)\" is the call to the function, this actually runs the function. The variable \"msg\" is used a parameter when calling the logIt function.\n", + "- Showing reuse of function...\n", + " - There are two calls to the logIt function\n", + " - This is called Prodedural Abstraction, a term that means reusing the same code" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "\n", + "console.log(\"Function Definition\");\n", + "\n", + "/* Function: logIt\n", + " * Parameter: msg\n", + " * Description: The parameter is \"msg\" is output to console, jupyter and \"output\" element in HTML\n", + "*/\n", + "function logIt(msg) {\n", + " console.log(msg); \n", + " element.append(msg);\n", + " document.getElementById(\"output\").textContent = msg;\n", + " //alert(output);\n", + "}\n", + "\n", + "// sequence of code build logIt parameter using concatenation\n", + "var msg = \"Hello, Students!\" // replaces content of variable\n", + "var classOf = \"Welcome CS class of 2024-2025.\"\n", + "logIt(msg + \" \" + classOf); // concatenation of strings" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### output showing Loosely typed data\n", + "JavaScript is a loosely typed language, meaning you don't have to specify what type of information will be stored in a variable in advance. \n", + "- To define a variable you prefix the name with var or const. The variable type is determined by JavaScript at runtime.\n", + "- Python and many interpretive languages are loosely typed like JavaScript. This is considered programmer friendly. \n", + "- Java which is a compiled language is strongly typed, thus you will see terms like String, Integer, Double, and Object in the source code. \n", + "- In JavaScript, the typeof keyword returns the type of the variable. Become familiar with type as it is valuable in conversation and knowing type help you understand how to modify data. Each variable type will have built in methods to manage content within the data type." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "console.log(\"Examine Data Types\");\n", + "\n", + "// Function to add typeof to output\n", + "function getType(output) {\n", + " return typeof output + \": \" + output;\n", + "}\n", + "\n", + "// Function defintion\n", + "function logIt(msg) {\n", + " console.log(getType(msg)); // logs string\n", + " console.info(msg); // logs object\n", + " document.getElementById(\"output\").textContent = msg;\n", + " element.append(getType(msg) + \" \"); // adds to Jupyter output\n", + " //alert(getType(msg));\n", + "}\n", + "\n", + "// Common Types\n", + "element.append(\"Common Types \");\n", + "logIt(\"Mr M\"); // String\n", + "logIt(1997); // Number\n", + "logIt(true); // Boolean\n", + "\n", + "// Object Type, this definition is often called a array or list\n", + "element.append(\"Object Type, array \");\n", + "var scores = [\n", + " 90,\n", + " 80, \n", + " 100\n", + "]; \n", + "logIt(scores);\n", + "\n", + "// Complex Object, this definition is often called hash, map, hashmap, or dictionary\n", + "element.append(\"Object Type, hash or dictionary \");\n", + "var person = { // key:value pairs seperated by comma\n", + " \"name\": \"Mr M\", \n", + " \"role\": \"Teacher\"\n", + "}; \n", + "logIt(person);\n", + "logIt(JSON.stringify(person)); //method used to convert this object into readable format" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Build a Person object, JSON, and show output\n", + "JavaScript and other languages have special properties and syntax to store and represent data. In fact, a class in JavaScript is a special function.\n", + "\n", + "- Definition of class allows for a collection of data, the \"class Person\" allows programmer to retain name, github id, and class of a Person.\n", + "- Instance of a class, the \"const teacher = new Person(\"Mr M\", \"jm1021\", 1977)\" makes an object \"teacher\" which is an object representation of \"class Person\".\n", + "- Setting and Getting properties After creating teacher and student objects, observe that properties can be changed/muted or extracted/accessed." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "console.log(\"Person objects\");\n", + "\n", + "/* class: Person\n", + " * Description: A collection of Person data\n", + "*/\n", + "class Person {\n", + " /* method: constructor\n", + " * parameters: name, ghID - GitHub ID, classOf - Graduation Class \n", + " * description: returns object when \"new Person()\" is called with matching parameters\n", + " * assignment: this.name, this.ghID, ... are properties retained in the returned object\n", + " * default: role uses a default property, it is set to \"Student\"\n", + " */\n", + " constructor(name, ghID, classOf, role=\"Student\") {\n", + " this.name = name;\n", + " this.ghID = ghID;\n", + " this.classOf = classOf;\n", + " this.role = role;\n", + " }\n", + "\n", + " /* method: setter\n", + " * parameters: role - role in classroom\n", + " * description: this.role is updated from default value to value contained in role parameter\n", + " */\n", + " setRole(role) {\n", + " this.role = role;\n", + " }\n", + " \n", + " /* method: getter\n", + " * description: turns properties of object into JSON object\n", + " * return value: JSON object\n", + " */\n", + " getJSON() {\n", + " const obj = {name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};\n", + " const json = JSON.stringify(obj);\n", + " return json;\n", + " }\n", + "\n", + " /* method: logIT\n", + " * description: this Person object is logged to console\n", + " */\n", + " \n", + " logIt() {\n", + " //Person Object\n", + " console.info(this);\n", + " \n", + " // HTML output\n", + " document.getElementById(\"output\").textContent = this.getJSON();\n", + "\n", + " //Log to Jupter\n", + " element.append(this.role + \" object in JSON: \");\n", + " element.append(this.getJSON()); \n", + " element.append(\" \");\n", + "\n", + "\n", + " //alert(this.getJSON());\n", + " }\n", + " \n", + "}\n", + "\n", + "// make a new Person Object\n", + "const teacher = new Person(\"Mr M\", \"jm1021\", 1977); // object type is easy to work with in JavaScript\n", + "// update role to Teacher\n", + "var role = \"Teacher\";\n", + "teacher.setRole(role); // set the role\n", + "teacher.logIt(); // log to console\n", + "\n", + "// make a new Person Object\n", + "const student = new Person(\"Jane Doe\", \"jane\", 2007); // object type is easy to work with in JavaScript\n", + "student.logIt(); // log to console" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Build a Classroom Array/List of Persons, JSON, and show output\n", + "Many key elements are shown again. New elements include...\n", + "- Building an Array, \"const students\" is an array of many students. \n", + "- Building a Classroom, this shows combining using spread." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "console.log(\"Classroom object\");\n", + "\n", + "/* class: Person\n", + " * Description: A collection of Person data\n", + "*/\n", + "class Person {\n", + " /* method: constructor\n", + " * parameters: name, ghID - GitHub ID, classOf - Graduation Class \n", + " * description: returns object when \"new Person()\" is called with matching parameters\n", + " * assignment: this.name, this.ghID, ... are properties retained in the returned object\n", + " * default: this.role is a default property retained in object, it is set to \"Student\"\n", + " */\n", + " constructor(name, ghID, classOf, role=\"Student\") {\n", + " this.name = name;\n", + " this.ghID = ghID;\n", + " this.classOf = classOf;\n", + " this.role = role;\n", + " }\n", + "\n", + " /* method: setter\n", + " * parameters: role - role in classroom\n", + " * description: this.role is updated from default value to value contained in role parameter\n", + " */\n", + " setRole(role) {\n", + " this.role = role;\n", + " }\n", + " \n", + " /* method: getter\n", + " * description: turns properties of object into JSON object\n", + " * return value: JSON object\n", + " */\n", + " getJSON() {\n", + " const obj = {name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};\n", + " const json = JSON.stringify(obj);\n", + " return json;\n", + " }\n", + "\n", + " /* method: logIT\n", + " * description: this Person object is logged to console\n", + " */\n", + " logIt() {\n", + " //Person Object\n", + " console.info(this);\n", + " // HTML output tag\n", + " document.getElementById(\"output\").textContent = this.getJSON();\n", + "\n", + " //Log to Jupter\n", + " element.append(\"Person json
\");\n", + " element.append(this.getJSON() + \"
\"); \n", + "\n", + " //alert(this.getJSON());\n", + " }\n", + " \n", + "}\n", + "\n", + "/* class: Classroom\n", + " * Description: A collection of Person objects\n", + "*/\n", + "class Classroom {\n", + " /* method: constructor\n", + " * parameters: teacher - a Person object, students - an array of Person objects\n", + " * description: returns object when \"new Classroom()\" is called containing properties and methods of a Classroom\n", + " * assignment: this.classroom, this.teacher, ... are properties retained in the returned object\n", + " */\n", + " constructor(teacher, students) {\n", + " /* spread: this.classroom contains Teacher object and all Student objects\n", + " * map: this.json contains of map of all persons to JSON\n", + " */\n", + " this.teacher = teacher;\n", + " this.students = students;\n", + " this.classroom = [teacher, ...students]; // ... spread option\n", + " this.json = '{\"classroom\":[' + this.classroom.map(person => person.getJSON()) + ']}';\n", + " }\n", + "\n", + " /* method: logIT\n", + " * description: this Classroom object is logged to console\n", + " */\n", + " logIt() {\n", + " //Classroom object\n", + " console.log(this);\n", + "\n", + " // HTML output\n", + " document.getElementById(\"data\").textContent = this.json;\n", + " document.getElementById(\"output\").textContent = this.json;\n", + "\n", + " //Classroom json\n", + " element.append(\"Classroom object in JSON: \");\n", + " element.append(this.json);\n", + "\n", + " //alert(this.json);\n", + " }\n", + "}\n", + "\n", + "/* function: constructCompSciClassroom\n", + " * Description: Create data for Classroom and Person objects\n", + " * Returns: A Classroom Object\n", + "*/\n", + "function constructCompSciClassroom() {\n", + " // define a Teacher object\n", + " const teacher = new Person(\"Mr M\", \"jm1021\", 1977, \"Teacher\"); // optional 4th parameter\n", + "\n", + " // define a student Array of Person objects\n", + " const students = [ \n", + " new Person(\"Anthony\", \"tonyhieu\", 2022),\n", + " new Person(\"Bria\", \"B-G101\", 2023),\n", + " new Person(\"Allie\", \"xiaoa0\", 2023),\n", + " new Person(\"Tigran\", \"Tigran7\", 2023),\n", + " new Person(\"Rebecca\", \"Rebecca-123\", 2023),\n", + " new Person(\"Vidhi\", \"VidhiKulkarni\", 2024)\n", + " ];\n", + "\n", + " // make a CompSci classroom from formerly defined teacher and student objects\n", + " return new Classroom(teacher, students); // returns object\n", + "}\n", + "\n", + "// assigns compsci to the object returned by \"constructCompSciClassroom()\" function\n", + "const compsci = constructCompSciClassroom();\n", + "// output of Objects and JSON in CompSci classroom\n", + "compsci.logIt();\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### for loop to generate Table Rows in HTML output\n", + "This code extracts JSON text from HTML, that was placed in DOM in a previous JavaScript cell, then it parses text into a JavaScript object. In addition, there is a for loop that iterates over the extracted object generating formated rows and columns in an HTML table.\n", + "\n", + "- Table generation is broken into parts...\n", + " - table data is obtained from a classroom array inside of the extracted object. \n", + " - the JavaScript for loop allows the construction of a new row of data for each Person hash object inside of the the Array.\n", + " - in the loop a table row ` ... ` is created for each Hash object in the Array.\n", + " - in the loop table data, a table column, ` ... ` is created for name, ghID, classOf, and role within the Hash object.\n", + " \n", + "```\n", + " ----------------\n", + " | HTML |\n", + " | DOM | \n", + " | data output | - ref: id=\"data\", id=\"output\"\n", + " ----------------\n", + " ⇓ ⇑\n", + " get set\n", + " ----------------\n", + " | JavaScript | - get data: \n", + " | code | const jsonText = document.getElementById(\"data\").innerHTML;\n", + " |getElementById| - set output: \n", + " ---------------- document.getElementById(\"output\").innerHTML = htmlOut;\n", + "\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%%js\n", + "console.log(\"Classroom Web Page\");\n", + "\n", + "// extract JSON text from output element in HTML page\n", + "const jsonText = document.getElementById(\"data\").innerHTML;\n", + "console.log(jsonText);\n", + "\n", + "// convert JSON text to a JavaScript Object to process\n", + "const classroom = JSON.parse(jsonText).classroom;\n", + "console.log(classroom);\n", + "\n", + "// make an HTML Out format for pretty display\n", + "/* Template literals (`), can make HTML generation more concise;\n", + " * the map functions generates row strings and the join method combines them;\n", + " * this replaces longer and ugly for loop and string concatenation.\n", + "*/\n", + "const htmlOut = `\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " ${classroom.map(row => `\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " `).join('')}\n", + " \n", + "
NameGitHub IDClass OfRole
${row.name}${row.ghID}${row.classOf}${row.role}
\n", + "`;\n", + "\n", + "// assign/set htmlOut to output element in HTML page\n", + "document.getElementById(\"output\").innerHTML = htmlOut;\n", + "\n", + "// show raw HTML\n", + "console.log(htmlOut);\n", + "element.append(htmlOut);" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Hacks\n", + "> Work with output and objects.\n", + "- Explain each of the outputs types.\n", + "- Using the last two code cells. Make a table of Cars, Games, Team Member. Something that you and pair share as interests." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.5" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/_notebooks/Foundation/Sprint1/sprint 2/2024-09-30-data-types-operations.ipynb b/_notebooks/Foundation/Sprint1/sprint 2/2024-09-30-data-types-operations.ipynb new file mode 100644 index 000000000..c7ac126a2 --- /dev/null +++ b/_notebooks/Foundation/Sprint1/sprint 2/2024-09-30-data-types-operations.ipynb @@ -0,0 +1,582 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "comments: true\n", + "layout: post\n", + "title: JavaScript Data Types and Operators\n", + "description: Learn about the different data types in JavaScript.\n", + "permalink: /csse/javascript/fundamentals/data-types/\n", + "categories: [JavaScript Fundamentals]\n", + "courses: { csse: {week: 6} }\n", + "type: ccc\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Primitive Data Types\n", + "\n", + "In game development, understanding the different data types in JavaScript is crucial for managing the various elements and attributes of your game. Primitive data types include numbers, strings, booleans, undefined, null, symbols, and BigInts. Reference data types include objects, arrays, and functions. Each type plays a unique role in creating a dynamic and interactive gaming experience.\n", + "\n", + "1. **Number**:\n", + " - Represents numerical values, health and timeInMilliSeconds\n", + "\n", + "2. **String**:\n", + " - Represents text, such as the user's name or keypress.\n", + "\n", + "3. **Boolean**:\n", + " - Represents true/false values, such as isAlive.\n", + "\n", + "4. **Undefined**:\n", + " - Represents a variable that has been declared but not yet assigned a value.\n", + "\n", + "5. **Null**:\n", + " - Represents the intentional absence of any object value, such as an empty inventory slot.\n", + "\n", + "6. **Symbol**:\n", + " - Represents a unique and immutable value, often used as unique identifiers for game objects.\n", + "\n", + "7. **BigInt**:\n", + " - Represents very large integers, such as the total number of points accumulated over many games.\n", + "\n", + "### Reference Data Types\n", + "\n", + "1. **Object**:\n", + " - Represents a collection of key-value pairs, such as a player's attributes or game settings.\n", + "\n", + "2. **Array**:\n", + " - Represents an ordered collection of values, such as a list of high scores or inventory items.\n", + "\n", + "3. **Function**:\n", + " - Represents a block of code designed to perform a specific task, such as attacking an enemy or saving the game." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\n/* Primitive Data Types\nThese are data types that store a single value.\n*/\n\n// Number: Represents numerical values, such as health and speed\nlet health = 100; // Integer\nlet playerSpeed = 5.75; // Float representing the player's speed\n\nconsole.log(\"Health (Number):\", health, \"Type:\", typeof health);\nconsole.log(\"Player Speed (Number):\", playerSpeed, \"Type:\", typeof playerSpeed);\n\n// String: Represents text, such as the user's name or keypress\nlet userName = \"Hero123\"; // User name\nlet keyPress = 'a'; // Keypress\n\nconsole.log(\"User Name (String):\", userName, \"Type:\", typeof userName);\nconsole.log(\"Key Press (String):\", keyPress, \"Type:\", typeof keyPress);\n\n// Compare single character to its ASCII value\nlet asciiValue = keyPress.charCodeAt(0);\nconsole.log(\"ASCII Value of Key Press:\", asciiValue, \"Type:\", typeof asciiValue);\nconsole.log(\"Is Key Press 'a' (ASCII 97)?\", asciiValue === 97);\n\n// Boolean: Represents true/false values, such as isAlive\nlet isAlive = true;\n\nconsole.log(\"Is Alive (Boolean):\", isAlive, \"Type:\", typeof isAlive);\n\n// Undefined: Represents a variable that has been declared but not yet assigned a value\nlet questReward;\n\nconsole.log(\"Quest Reward (Undefined):\", questReward, \"Type:\", typeof questReward);\n\n// Null: Represents the intentional absence of any object value, such as an empty inventory slot\nlet inventorySlot = null;\n\nconsole.log(\"Inventory Slot (Null):\", inventorySlot, \"Type:\", typeof inventorySlot);\n\n// Symbol: Represents a unique and immutable value, often used as unique identifiers for game objects\nlet uniqueID = Symbol('playerID');\n\nconsole.log(\"Unique ID (Symbol):\", uniqueID, \"Type:\", typeof uniqueID);\n\n// BigInt: Represents very large integers, such as the total time played in milliseconds\nlet totalTimePlayed = 1234567890123456789012345678901234567890n;\n\nconsole.log(\"Total Time Played (BigInt):\", totalTimePlayed, \"Type:\", typeof totalTimePlayed);\n\n/* Reference Data Types\nThese are data types that store references to memory locations.\n*/\n\n// Object: Represents a collection of key-value pairs, such as player attributes or game settings\nlet playerAttributes = {\n name: \"Hero123\",\n health: 100,\n mana: 50\n};\n\nconsole.log(\"Player Attributes (Object):\", playerAttributes, \"Type:\", typeof playerAttributes);\n\n// Array: Represents an ordered collection of values, such as a list of high scores or inventory items\nlet highScores = [1500, 1200, 900, 600, 300];\n\nconsole.log(\"High Scores (Array):\", highScores, \"Type:\", typeof highScores);\n\n// Function: Represents a block of code designed to perform a specific task, such as attacking an enemy or saving the game\nfunction attackEnemy() {\n console.log(\"Enemy attacked!\");\n}\n\nconsole.log(\"Attack Enemy (Function):\", attackEnemy, \"Type:\", typeof attackEnemy);\nattackEnemy();\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "\n", + "/* Primitive Data Types\n", + "These are data types that store a single value.\n", + "*/\n", + "\n", + "// Number: Represents numerical values, such as health and speed\n", + "let health = 100; // Integer\n", + "let playerSpeed = 5.75; // Float representing the player's speed\n", + "\n", + "console.log(\"Health (Number):\", health, \"Type:\", typeof health);\n", + "console.log(\"Player Speed (Number):\", playerSpeed, \"Type:\", typeof playerSpeed);\n", + "\n", + "// String: Represents text, such as the user's name or keypress\n", + "let userName = \"Hero123\"; // User name\n", + "let keyPress = 'a'; // Keypress\n", + "\n", + "console.log(\"User Name (String):\", userName, \"Type:\", typeof userName);\n", + "console.log(\"Key Press (String):\", keyPress, \"Type:\", typeof keyPress);\n", + "\n", + "// Compare single character to its ASCII value\n", + "let asciiValue = keyPress.charCodeAt(0);\n", + "console.log(\"ASCII Value of Key Press:\", asciiValue, \"Type:\", typeof asciiValue);\n", + "console.log(\"Is Key Press 'a' (ASCII 97)?\", asciiValue === 97);\n", + "\n", + "// Boolean: Represents true/false values, such as isAlive\n", + "let isAlive = true;\n", + "\n", + "console.log(\"Is Alive (Boolean):\", isAlive, \"Type:\", typeof isAlive);\n", + "\n", + "// Undefined: Represents a variable that has been declared but not yet assigned a value\n", + "let questReward;\n", + "\n", + "console.log(\"Quest Reward (Undefined):\", questReward, \"Type:\", typeof questReward);\n", + "\n", + "// Null: Represents the intentional absence of any object value, such as an empty inventory slot\n", + "let inventorySlot = null;\n", + "\n", + "console.log(\"Inventory Slot (Null):\", inventorySlot, \"Type:\", typeof inventorySlot);\n", + "\n", + "// Symbol: Represents a unique and immutable value, often used as unique identifiers for game objects\n", + "let uniqueID = Symbol('playerID');\n", + "\n", + "console.log(\"Unique ID (Symbol):\", uniqueID, \"Type:\", typeof uniqueID);\n", + "\n", + "// BigInt: Represents very large integers, such as the total time played in milliseconds\n", + "let totalTimePlayed = 1234567890123456789012345678901234567890n;\n", + "\n", + "console.log(\"Total Time Played (BigInt):\", totalTimePlayed, \"Type:\", typeof totalTimePlayed);\n", + "\n", + "/* Reference Data Types\n", + "These are data types that store references to memory locations.\n", + "*/\n", + "\n", + "// Object: Represents a collection of key-value pairs, such as player attributes or game settings\n", + "let playerAttributes = {\n", + " name: \"Hero123\",\n", + " health: 100,\n", + " mana: 50\n", + "};\n", + "\n", + "console.log(\"Player Attributes (Object):\", playerAttributes, \"Type:\", typeof playerAttributes);\n", + "\n", + "// Array: Represents an ordered collection of values, such as a list of high scores or inventory items\n", + "let highScores = [1500, 1200, 900, 600, 300];\n", + "\n", + "console.log(\"High Scores (Array):\", highScores, \"Type:\", typeof highScores);\n", + "\n", + "// Function: Represents a block of code designed to perform a specific task, such as attacking an enemy or saving the game\n", + "function attackEnemy() {\n", + " console.log(\"Enemy attacked!\");\n", + "}\n", + "\n", + "console.log(\"Attack Enemy (Function):\", attackEnemy, \"Type:\", typeof attackEnemy);\n", + "attackEnemy();" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Data Type Operations\n", + "\n", + "In JavaScript, we will be interacting with data and data types. Data types have operators that allow you to alter the data types.\n", + "\n", + "### Assignment Operators and Math Operators\n", + "\n", + "In this example height is being assigned the value of a calculation in relation to conventional screen sizes. These operators are straight forward (`=`, `+`, `-`, `*`, `/`)\n", + "\n", + "```js\n", + "let width = 1920;\n", + "let height = Math.round(width * 9 / 16);\n", + "```\n", + "\n", + "### Compound Assignment\n", + "\n", + "These are shorthand for common operations and are specified as follows. Here is an example of one compound assignment. Make a code cell and try some more (`+=`, `*=`, `-=`, `\\=`)\n", + "\n", + "```js\n", + "let number = 100;\n", + "number += 1; // short for number = number + 1;\n", + "```\n", + "\n", + "### Concatenation\n", + "\n", + "Concatenation is used to join two or more elements together. This is the same as the plus (`+`) operator. It looks like math, but once a string gets involved, it turns into concatenation.\n", + "\n", + "```js\n", + "// Simple concatenation\n", + "let blockSize = 50;\n", + "block.style.width = blockSize + \"px\";\n", + "```\n", + "\n", + "```js\n", + "/// Math at first and then concatenation following PEMDAS\n", + "block.style.height = blockSize * 9 / 16 + \"px\";\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Popcorn Hack 1\n", + "\n", + "Make a code cell that show usage of compound assignment in a Data Type Operations." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Scale a Block\n", + "\n", + "Scalling is an important Math operation that is used in Gaming. This example is considering HD formats to construct a block." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "

This example uses data types, operators, and functions to scale a block based on a user-defined width.

\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n", + "\n", + "\n", + "
\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html \n", + "\n", + "

This example uses data types, operators, and functions to scale a block based on a user-defined width.

\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n", + "\n", + "\n", + "
\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Popcorn Hack 2\n", + "\n", + "Make a code cell that changes block into a square, versus HD resolution" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Placing a Block\n", + "\n", + "Often in gaming you will want to position on element in relationship to another." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "

This example uses data types, operators, and functions to scale a block based on a user-defined width.

\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html \n", + "\n", + "

This example uses data types, operators, and functions to scale a block based on a user-defined width.

\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n", + "\n", + "\n", + "\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Popcorn Hack 3\n", + "\n", + "Try to place a square in every corner.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Turtle / Fish HW\n", + "\n", + "Make the Turtle and Fish start on screen in different locations (ie Fish Center/Left, Turtle Center/Right)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Foundation/Sprint1/sprint 2/2024-09-30-variables_IO.ipynb b/_notebooks/Foundation/Sprint1/sprint 2/2024-09-30-variables_IO.ipynb new file mode 100644 index 000000000..c86a05f7a --- /dev/null +++ b/_notebooks/Foundation/Sprint1/sprint 2/2024-09-30-variables_IO.ipynb @@ -0,0 +1,326 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "comments: true\n", + "layout: post\n", + "title: JavaScript Variables, Input, Output\n", + "description: An introduction to JavaScript variables, input, and output using the RPG game as an example.\n", + "permalink: /csse/javascript/fundamentals/variables\n", + "categories: [JavaScript Fundamentals]\n", + "courses: { csse: {week: 6} }\n", + "type: ccc\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Variables\n", + "\n", + "Variables are storage containers for data values used within a programming language. Variables can be useful when changing preferences, selecting a background, creating animations, and changing assets in game programming." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Variable Inputs\n", + "\n", + "To obtain data from user and save into a JavaScript variable requires the use of HTML. \n", + "\n", + "The `` HTML element is used to create interactive controls for web-based forms in order to receive data from the user.\n", + "\n", + "- Geeks for Geeks Referece on [input tag](https://www.geeksforgeeks.org/html-input-tag/)\n", + "- Remember in Jupyter Notebooks and in GitHub Pages we do not use `` and `` tags. \n", + "- Additionally, we prefer using SASS for `\n", + "\n", + "\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Display Frames in Sprite File\n", + "\n", + "The next code block contains logic to extract frames within the sprite sheet. This is a more practical game enhancement compared to the previous example.\n", + "\n", + "Here are terms to describe key elements in the code:\n", + "\n", + "- **MetaData**: Contains information about the sprite file, including its name, source URL, and orientation details.\n", + " - **orientation**: Describes the layout of the sprite in the PNG file.\n", + " - **header**: Size of the area of description above the sprite.\n", + " - **pad**: Size of the area between the sprites.\n", + " - **jagged**: Indicates that each row can contain a different number of sprites.\n", + "- **drawImage**: In the 9-property format, it provides the ability to scale the source into the destination.\n", + "- **class**: Continues using the constructor and draw methods for source and output; adds math to abstract each frame independently.\n", + "- **for-loops**: Demonstrates nested for loops to process each frame within the 2D sprite sheet." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "source": [ + "### Hack #2: Display Individual Sprites\n", + "\n", + "Create new code cell(s) to display individual sprites from a sprite sheet. This sprite sheet will potentially be used in your game.\n", + "\n", + "**Challenge**: Use the concepts of 2D arrays, nested loops, and sprite metadata to extract and display individual sprites. Think about how you can manage and display different frames or animations for your game characters or objects." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Foundation/sprint 2/fundamentals/2024-09-30-variables_IO.ipynb b/_notebooks/Foundation/sprint 2/fundamentals/2024-09-30-variables_IO.ipynb new file mode 100644 index 000000000..c86a05f7a --- /dev/null +++ b/_notebooks/Foundation/sprint 2/fundamentals/2024-09-30-variables_IO.ipynb @@ -0,0 +1,326 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "comments: true\n", + "layout: post\n", + "title: JavaScript Variables, Input, Output\n", + "description: An introduction to JavaScript variables, input, and output using the RPG game as an example.\n", + "permalink: /csse/javascript/fundamentals/variables\n", + "categories: [JavaScript Fundamentals]\n", + "courses: { csse: {week: 6} }\n", + "type: ccc\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Variables\n", + "\n", + "Variables are storage containers for data values used within a programming language. Variables can be useful when changing preferences, selecting a background, creating animations, and changing assets in game programming." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Variable Inputs\n", + "\n", + "To obtain data from user and save into a JavaScript variable requires the use of HTML. \n", + "\n", + "The `` HTML element is used to create interactive controls for web-based forms in order to receive data from the user.\n", + "\n", + "- Geeks for Geeks Referece on [input tag](https://www.geeksforgeeks.org/html-input-tag/)\n", + "- Remember in Jupyter Notebooks and in GitHub Pages we do not use `` and `` tags. \n", + "- Additionally, we prefer using SASS for `\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "source": [ + "\n", + "\n", + "\n", + "\n", + "

Lesson on If Statements in JavaScript

\n", + "\n", + "

1. Basic IF Statements

\n", + "\n", + "

What is an If Statement?

\n", + "

An if statement is a decision-making tool in programming that allows code to run only if a specific condition is true. It makes code responsive to changing inputs or situations.

\n", + "\n", + "
\n", + "Syntax:\n", + "
if (condition) {\n",
+    "// code to execute if condition is true\n",
+    "}
\n", + "
\n", + "\n", + "

Example of an IF Statement in JavaScript

\n", + "
\n", + "JavaScript Example:\n", + "
// Prompt the user for their favorite fruit\n",
+    "let fruit = prompt(\"What's your favorite fruit?\");\n",
+    "\n",
+    "// If the fruit is \"mango,\" respond with a specific message\n",
+    "if (fruit === \"mango\") {\n",
+    "console.log(\"That sounds super yummy!\");\n",
+    "}
\n", + "
\n", + "\n", + "

2. Basic If-Else and Else-If Statements

\n", + "\n", + "

What is an If-Else Statement?

\n", + "

An if-else statement expands on the if statement by adding an alternative code block that executes if the initial condition is false. This allows for more complex decision trees in code.

\n", + "\n", + "
\n", + "Syntax:\n", + "
if (condition) {\n",
+    "// code if condition is true\n",
+    "} else {\n",
+    "// code if condition is false\n",
+    "}
\n", + "
\n", + "\n", + "

Example of an IF-ELSE-IF Statement in JavaScript

\n", + "
\n", + "JavaScript Example:\n", + "
// Ask the user for their favorite fruit\n",
+    "let fruit = prompt(\"What's your favorite fruit?\");\n",
+    "\n",
+    "// Ensure case-insensitive comparison\n",
+    "if (fruit.toLowerCase() === \"mango\") {\n",
+    "console.log(\"That sounds super yummy!\");\n",
+    "} else if (fruit.toLowerCase() === \"banana\") {\n",
+    "console.log(\"Sounds great!\");\n",
+    "} else {\n",
+    "console.log(`Oh, ${fruit} is alright, but mangos are better!`);\n",
+    "}
\n", + "
\n", + "\n", + "

3. Booleans in If Statements

\n", + "\n", + "

Using Booleans with If Statements

\n", + "

Booleans allow for true/false checks. In this example, we determine if a user’s favorite fruit is available in stock and display a message accordingly.

\n", + "\n", + "
\n", + "Boolean Example:\n", + "
// Check if a fruit is available\n",
+    "let isAvailable = true;\n",
+    "\n",
+    "if (isAvailable) {\n",
+    "console.log(\"Your favorite fruit is available!\");\n",
+    "} else {\n",
+    "console.log(\"Sorry, your favorite fruit is out of stock.\");\n",
+    "}
\n", + "
\n", + "\n", + "

4. Using Random Values

\n", + "\n", + "

Using Random Values with If Statements

\n", + "

Random values create dynamic interactions in a program. In this example, we assign random popularity scores to two fruits and determine which one is more popular.

\n", + "\n", + "
\n", + "Random Example:\n", + "
// Generate random popularity scores for two fruits\n",
+    "let applePopularity = Math.floor(Math.random() * 100) + 1;\n",
+    "let orangePopularity = Math.floor(Math.random() * 100) + 1;\n",
+    "\n",
+    "console.log(\"Apple popularity score:\", applePopularity);\n",
+    "console.log(\"Orange popularity score:\", orangePopularity);\n",
+    "\n",
+    "if (applePopularity > orangePopularity) {\n",
+    "console.log(\"Apples are more popular than oranges!\");\n",
+    "} else if (applePopularity < orangePopularity) {\n",
+    "console.log(\"Oranges are more popular than apples!\");\n",
+    "} else {\n",
+    "console.log(\"Both fruits are equally popular!\");\n",
+    "}
\n", + "
\n", + "\n", + "

Summary Table of Conditional Statements

\n", + "\n", + "\n", + " \n", + " \n", + " \n", + "\n", + "\n", + " \n", + " \n", + " \n", + "\n", + "\n", + " \n", + " \n", + " \n", + "\n", + "\n", + " \n", + " \n", + " \n", + "\n", + "
Statement TypeDescriptionUse Case
If StatementExecutes a block of code if a specified condition is true.Used for simple condition checks, such as verifying if a fruit is \"mango\".
If-Else StatementExecutes one block if the condition is true, and another if it is false.Useful for two-way decision-making, like checking if a fruit is available.
Else-If StatementChecks additional conditions if the first condition is false.Used when comparing multiple values, like determining the more popular fruit.
\n", + "\n", + "

Summary

\n", + "

This lesson covers various ways to use conditional statements in JavaScript. Each structure serves a unique purpose in decision-making, from simple checks with if statements to multiple conditions with switch statements.

\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Data_Abstractions/2024-11-06-data_abstraction-homework.ipynb b/_notebooks/Sprint 2/Data_Abstractions/2024-11-06-data_abstraction-homework.ipynb new file mode 100644 index 000000000..5905025cf --- /dev/null +++ b/_notebooks/Sprint 2/Data_Abstractions/2024-11-06-data_abstraction-homework.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "yaml" + } + }, + "outputs": [], + "source": [ + "---\n", + "comments: True\n", + "layout: post\n", + "title: Data Abstraction Homework\n", + "description: An intro to data abstraction\n", + "permalink: /csse/javascript/fundamentals/data-abstraction-homework\n", + "categories: [CSSE JavaScript Fundamentals]\n", + "author: Akhil Kulkarni, Santhosh Karthik\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# JavaScript BankAccount Class - Required Homework\n", + "\n", + "Create a `BankAccount` class that returns an object. Inside this function, follow these steps:\n", + "\n", + "### 1. **Initialize Balance**:\n", + "- Create a `balance` variable and initialize it to `100`, or any balance you want (representing $100).\n", + "\n", + "### 2. **Methods**:\n", + "- `deposit(amount)`: Adds a specified amount to the balance.\n", + "- `withdraw(amount)`: Deducts a specified amount from the balance, but only if there is enough balance.\n", + "- `getBalance()`: Returns the current balance.\n", + "- `transfer(amount, targetAccount)`: Transfers a specified amount from this account to another account.\n", + "\n", + "### 3. **Encapsulation**:\n", + "- Only allow access to the `balance` variable through the `deposit`, `withdraw`, `getBalance`, and `transfer` methods.\n", + "- Make sure to avoid direct access to `balance` from outside the `BankAccount` function.\n", + "\n", + "### 4. **Validation**:\n", + "- A deposit can only add positive amounts.\n", + "- A withdrawal can only occur if the account has enough balance.\n", + "- Transfers should be allowed only if both accounts have sufficient balance to complete the transaction.\n", + "\n", + "### 5. **Testing**:\n", + "- Create a new `BankAccount` instance with a starting balance.\n", + "- Call each method (`deposit`, `withdraw`, `getBalance`, `transfer`) to verify functionality.\n", + "\n", + "### 6. **Inheritance**:\n", + "- Create a subclass of `BankAccount`, called `PremiumBankAccount`, which offers additional benefits like no transaction fees or higher transfer limits, or whatever you want.\n", + "\n", + "---\n", + "\n", + "### Example Scenario:\n", + "\n", + "1. **Create two BankAccount instances**:\n", + " - Account 1 has an initial balance of $500.\n", + " - Account 2 has an initial balance of $1000.\n", + "\n", + "2. **Test the following:**\n", + " - Deposit $200 into Account 1.\n", + " - Withdraw $50 from Account 1.\n", + " - Transfer $100 from Account 2 to Account 1.\n", + " - Print the balances of both accounts.\n", + "\n", + "Make sure to implement the `transfer` method so that it checks if both accounts have enough balance before transferring money.\n", + "\n", + "---\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": " class BankAccount {\n\n }\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + " class BankAccount {\n", + "\n", + " }" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "source": [ + "# JavaScript Car Class Code - Optional Homework (Extra Credit)\n", + "\n", + "Create a `Car` class that models a car with a few basic properties and methods. Follow these steps:\n", + "\n", + "### 1. **Initialize Properties**:\n", + "- Create properties for `make`, `model`, and `fuelLevel` (a number between 0 and 100 representing the amount of fuel in the car).\n", + " \n", + "### 2. **Methods**:\n", + "- `drive(distance)`: Decreases the `fuelLevel` by a certain percentage based on the distance traveled.\n", + "- `refuel(amount)`: Increases the `fuelLevel` by a specified amount, but make sure that it does not exceed 100 (the max fuel capacity).\n", + "- `getFuelLevel()`: Returns the current `fuelLevel`.\n", + "\n", + "### 3. **Encapsulation**:\n", + "- Keep the `fuelLevel` private, and only allow it to be modified or read via the `drive`, `refuel`, and `getFuelLevel` methods.\n", + "- Do not allow direct access to `fuelLevel` from outside the class.\n", + "\n", + "### 4. **Validation**:\n", + "- Ensure that when refueling, the `fuelLevel` does not exceed 100.\n", + "- When driving, ensure that the car does not drive without enough fuel (so if fuel is 0, they cant drive).\n", + "\n", + "### 5. **Testing**:\n", + "- Create a `Car` instance with an initial fuel level.\n", + "- Test the following:\n", + " - Drive the car and check how the fuel level changes.\n", + " - Refuel the car and check that the fuel level increases without exceeding 100.\n", + " - Try driving the car when the fuel level is 0 and ensure that it cannot drive.\n", + "\n", + "---\n", + "\n", + "### Example Scenario:\n", + "\n", + "1. **Create a Car instance**:\n", + " - The car has a `make` of `\"Toyota\"`, a `model` of `\"Corolla\"`, and a `fuelLevel` of 50%.\n", + "\n", + "2. **Test the following:**\n", + " - Drive the car for 100 km (decreases fuel level by 10%).\n", + " - Refuel the car with 30 units (increases fuel level, but should not exceed 100%).\n", + " - Try to drive the car with 0 fuel and verify it doesn’t drive.\n", + "\n", + "---\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "class Car{\n", + "\n", + "}" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Data_Abstractions/2024-11-06-data_abstraction-p1.ipynb b/_notebooks/Sprint 2/Data_Abstractions/2024-11-06-data_abstraction-p1.ipynb new file mode 100644 index 000000000..5cdc20696 --- /dev/null +++ b/_notebooks/Sprint 2/Data_Abstractions/2024-11-06-data_abstraction-p1.ipynb @@ -0,0 +1,509 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "yaml" + } + }, + "outputs": [], + "source": [ + "---\n", + "comments: True\n", + "layout: post\n", + "title: Data Abstraction\n", + "description: An intro to data abstraction\n", + "permalink: /csse/javascript/fundamentals/data-abstraction-p1\n", + "type: ccc\n", + "author: Santhosh Karthik\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# What is Data Abstraction?\n", + "Data Abstraction is hiding the complex inner workings of code, and only exposing the part that the user/coder needs to know.\n", + "## Real Life Examples\n", + "Some real life examples of Data Abstraction include cars, mobile apps, games, and even the computer that you are using!!\n", + "### Car example\n", + "Cars are a real life example of Data Abstraction with their steering wheel. The inner electronics of the system is hidden, and only the steering wheel, and the option of moving the car left and right are shown\n", + "### Mobile App example\n", + "Mobile App's are another great example for Data Abstraction. One example of this is the YouTube app. Youtube hides the complex hosting features that is use, and only shows you the actual video. Another example of Data abstraction would be the messages app on your phone. It hides the complex innerworkings of how it is being sent to someone elses phone, and only shows if it is sent or not.\n", + "### Games example\n", + "In games such as Minecraft as Pokemon Data abstraction is a necessary, as you need to hide how multiple things are being done in order to simplify the user experience\n", + "## Relevant examples in Javascript\n", + "Some examples of Data abstraction in Javascript include classes, function and objects. We will go more in depth into how these are examples" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Built in functions\n", + "Built in Javascript functions are a great example of Data Abstraction. The method to create them is already defined, the user simply has to call it. For example **Math.cos()** is a built in function that takes a number as an argument and returns the cosine of that number. The user does not need to know how the function works, they only need to know that it takes a number as an argument and returns the cosine of that number. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "let angleInDegrees = 57;\nlet angleInRadians = angleInDegrees * (Math.PI / 180);\n// 11 lines of code to calculate the cosine of an angle without using built in operators\n function factorial(n) {\n let result = 1;\n for (let i = 2; i <= n; i++) { // Start at 2, as multiplying by 1 is unnecessary\n result *= i;\n }\n return result;\n }\nfunction cosine(x) {\n return 1 - x**2 / factorial(2) + x**4 / factorial(4) - x**6 / factorial(6) + x**8 / factorial(8) + x**10 / factorial(10);\n}\nlet createdOutput = cosine(angleInRadians);\n\n// 1 line of code to calculate the cosine of an angle using built in operators\nlet inBuiltOutput = Math.cos(angleInRadians);\nconsole.log(\"My created function: \" + createdOutput);\nconsole.log(\"Original function: \" + inBuiltOutput);\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + "let angleInDegrees = 57;\n", + "let angleInRadians = angleInDegrees * (Math.PI / 180);\n", + "// 11 lines of code to calculate the cosine of an angle without using built in operators\n", + " function factorial(n) {\n", + " let result = 1;\n", + " for (let i = 2; i <= n; i++) { // Start at 2, as multiplying by 1 is unnecessary\n", + " result *= i;\n", + " }\n", + " return result;\n", + " }\n", + "function cosine(x) {\n", + " return 1 - x**2 / factorial(2) + x**4 / factorial(4) - x**6 / factorial(6) + x**8 / factorial(8) + x**10 / factorial(10);\n", + "}\n", + "let createdOutput = cosine(angleInRadians);\n", + "\n", + "// 1 line of code to calculate the cosine of an angle using built in operators\n", + "let inBuiltOutput = Math.cos(angleInRadians);\n", + "\n", + "console.log(\"My created function: \" + createdOutput);\n", + "console.log(\"Original function: \" + inBuiltOutput);\n", + "console.log(\"You can also see that my function is less accurate by a little bit\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Functions as Data Abstractions\n", + "\n", + "Functions are a great example of data abstraction because they help us simplify complex tasks. Here’s how they do that:\n", + "\n", + "1. **Simplification**: Functions take a set of instructions and bundle them together. This way, we don’t have to think about all the details every time we want to use them.\n", + "\n", + "2. **Reusability**: Once we create a function, we can use it multiple times throughout our code. This saves time and effort since we don't need to rewrite the same steps.\n", + "\n", + "3. **Clarity**: By giving functions clear names, we can easily understand what they do. This makes our code easier to read and follow.\n", + "\n", + "In short, functions allow us to focus on the bigger picture without getting lost in the details, making programming simpler and more organized.\n", + "\n", + "Below is an example of a reusable function that can add 2 numbers together" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "

Please put your first number here

\n", + " \n", + "

Please put your second number

\n", + " \n", + "
\n", + "
\n", + " \n", + "
\n", + "

\n", + "
\n", + "

Please put your first number here

\n", + " \n", + "

Please put your second number

\n", + " \n", + "
\n", + "
\n", + " \n", + "
\n", + "

\n", + " \n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html\n", + "
\n", + "

Please put your first number here

\n", + " \n", + "

Please put your second number

\n", + " \n", + "
\n", + "
\n", + " \n", + "
\n", + "

\n", + "
\n", + "

Please put your first number here

\n", + " \n", + "

Please put your second number

\n", + " \n", + "
\n", + "
\n", + " \n", + "
\n", + "

\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Classes as Data Abstractions\n", + "\n", + "Classes play a crucial role in data abstraction in programming. Here’s how they achieve this:\n", + "\n", + "1. **Reusability and Inheritance**: \n", + " Once a class is defined, it can be reused to create multiple instances (objects) without rewriting code. Through inheritance, new classes can inherit properties and methods from existing ones, promoting code reuse and reducing redundancy.\n", + "\n", + "2. **Polymorphism**: \n", + " This allows objects of different classes to be treated as objects of a common superclass. It enables more flexible and generic code that can operate on different types of objects, enhancing code extensibility.\n", + "\n", + "In summary, classes help create organized, reusable, and understandable code by encapsulating data and behavior, abstracting complexity, and supporting a robust inheritance structure.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What is inheritance?\n", + "Inheritance allows a new class to contain properties from another class using the word **extends**. Below is an example of 2 classes, one being a parent class and the other being a child class. The child class inherits the properties of the parent class such as its **parameters** and **functions**" + ] + }, + { + "cell_type": "code", + "execution_count": 83, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": " // Define the Phone class\n class Phone {\n constructor(model, specs) {\n this.model = model;\n this.specs = specs;\n }\n \n listSpecs(id) {\n document.getElementById(id).innerHTML = (\"The \" + this.model + \" weighs \" + this.specs.weight + \n \", has a display of \" + this.specs.display + \n \" and has a \" + this.specs.chip);\n console.log(\"The \" + this.model + \" weighs \" + this.specs.weight + \n \", has a display of \" + this.specs.display + \n \" and has a \" + this.specs.chip);\n }\n }\n\n // Define the iPhone16 class\n class iPhone16 extends Phone {\n constructor() {\n const model = \"iPhone 16\"; // Use const or let here\n const specs = {\n weight: \"170 grams\",\n display: \"6.1 inches\",\n chip: \"A18\"\n };\n super(model, specs); // Call the parent constructor\n }\n }\n let myiPhone;\n if (typeof myiPhone === 'undefined') {\n // Create an instance of iPhone16 and call the listSpecs method\n myiPhone = new iPhone16(); // Create an instance of iPhone16\n }\n myiPhone.listSpecs(\"iPhone\"); // Call the listSpecs method\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + " // Define the Phone class\n", + " class Phone {\n", + " constructor(model, specs) {\n", + " this.model = model;\n", + " this.specs = specs;\n", + " }\n", + " \n", + " listSpecs(id) {\n", + " document.getElementById(id).innerHTML = (\"The \" + this.model + \" weighs \" + this.specs.weight + \n", + " \", has a display of \" + this.specs.display + \n", + " \" and has a \" + this.specs.chip);\n", + " console.log(\"The \" + this.model + \" weighs \" + this.specs.weight + \n", + " \", has a display of \" + this.specs.display + \n", + " \" and has a \" + this.specs.chip);\n", + " }\n", + " }\n", + "\n", + " // Define the iPhone16 class\n", + " class iPhone16 extends Phone {\n", + " constructor() {\n", + " const model = \"iPhone 16\"; // Use const or let here\n", + " const specs = {\n", + " weight: \"170 grams\",\n", + " display: \"6.1 inches\",\n", + " chip: \"A18\"\n", + " };\n", + " super(model, specs); // Call the parent constructor\n", + " }\n", + " }\n", + " let myiPhone;\n", + " if (typeof myiPhone === 'undefined') {\n", + " // Create an instance of iPhone16 and call the listSpecs method\n", + " myiPhone = new iPhone16(); // Create an instance of iPhone16\n", + " }\n", + " myiPhone.listSpecs(\"iPhone\"); // Call the listSpecs method" + ] + }, + { + "cell_type": "code", + "execution_count": 84, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "

These are the specs of the iPhone 16:

\n", + "

\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html\n", + "

These are the specs of the iPhone 16:

\n", + "

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## How to Use `super` in Data Abstraction\n", + "\n", + "The `super` function is used to call methods or access variables from a **parent class** in a **child class**. Here’s how it works:\n", + "\n", + "- **Access Parent Variables**: You can use `super` to bring in variables or properties that are already defined in the parent class, so you don’t have to rewrite them.\n", + "- **Modify Parent Methods**: If the parent class has a method, you can use `super` to call that method and then build on it in the child class. For example, if the parent class has a `getPrice` method, you can use `super.getPrice()` in the child class to get the original price, then modify it—like multiplying it by a new factor.\n", + "\n", + "Using `super` is helpful when you know the parent method’s output but need to adjust it slightly without re-creating the whole function. This saves time and keeps the code simpler, especially for complex functions. \n", + "\n", + "---\n", + "\n", + "**Simple Summary**: \n", + "`super` lets a child class use parts of a parent class without redoing the work. It’s like copying the basics from a template and adding only the extra details you need." + ] + }, + { + "cell_type": "code", + "execution_count": 74, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": " class Product{\n constructor(price,size,taxRate) {\n this.price = price;\n this.size = size;\n this.taxRate = taxRate;\n } \n getPrice() {\n return this.price + this.taxRate * this.price;\n }\n product(){\n const className = this.constructor.name.toLowerCase();\n return \"You are ordering a \" + className + \" with a price of \" + this.getPrice() + \" dollars, a size of \" + this.size;\n }\n }\n class Bagel extends Product{\n constructor(price, size, taxRate, flavor) {\n super(price, size, taxRate);\n this.flavor = flavor;\n }\n getPrice(){\n return super.getPrice() * this.size;\n }\n product(){\n return super.product() + \" and a flavor of \" + this.flavor;\n }\n }\nvar sesameBagel = new Bagel(1.5, 2, 0.07, \"sesame\");\nconsole.log(sesameBagel.product());\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + " class Product{\n", + " constructor(price,size,taxRate) {\n", + " this.price = price;\n", + " this.size = size;\n", + " this.taxRate = taxRate;\n", + " } \n", + " getPrice() {\n", + " return this.price + this.taxRate * this.price;\n", + " }\n", + " product(){\n", + " const className = this.constructor.name.toLowerCase();\n", + " return \"You are ordering a \" + className + \" with a price of \" + this.getPrice() + \" dollars, a size of \" + this.size;\n", + " }\n", + " }\n", + " class Bagel extends Product{\n", + " constructor(price, size, taxRate, flavor) {\n", + " super(price, size, taxRate);\n", + " this.flavor = flavor;\n", + " }\n", + " getPrice(){\n", + " return super.getPrice() * this.size;\n", + " }\n", + " product(){\n", + " return super.product() + \" and a flavor of \" + this.flavor;\n", + " }\n", + " }\n", + "const sesameBagel = new Bagel(1.5, 2, 0.07, \"sesame\");\n", + "console.log(sesameBagel.product());" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Polymorphism\n", + "\n", + "Polymorphism is a fundamental concept in object-oriented programming that allows methods to do different things based on the object that is calling them. It enables objects of different classes to be treated as objects of a common superclass.\n", + "\n", + "### Example\n", + "\n", + "A base class `Shape` might have a method `area()`. Subclasses like `Circle` and `Square` provide their specific implementations. When `area()` is called, the correct version is executed based on the object type.\n", + "\n", + "## Benefits\n", + "\n", + "- **Code Reusability**: Use the same interface for different types.\n", + "- **Flexibility**: Easily extend and manage code.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 80, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": " class RegularShape {\n constructor(sideLength, apothem){\n this.sideLength = sideLength;\n this.apothem = apothem;\n }\n area(){\n throw new Error(\"This method must be overridden!\");\n }\n perimeter(){\n throw new Error(\"This method must be overridden!\");\n }\n }\n\n class Square extends RegularShape {\n constructor(sideLength){\n super(sideLength, sideLength/2);\n }\n area(){\n return this.sideLength ** 2;\n }\n perimeter(){\n return this.sideLength * 4;\n }\n }\n\n class RegularPentagon extends RegularShape{\n constructor(sideLength){\n super(sideLength, sideLength/2*Math.tan(Math.PI/5));\n }\n area(){\n return 5 * this.sideLength * this.apothem / 2;\n }\n perimeter(){\n return this.sideLength * 5;\n }\n }\n class Arc extends RegularShape{\n constructor(radius, degrees){\n // Using sideLength for the arc length of an arc in degrees\n super(radius, radius);\n this.radius = radius;\n this.arcLength = 2 * Math.PI * radius * degrees / 360;\n if(degrees >0 && degrees <= 360){\n this.degrees = degrees;\n }\n else{\n throw new Error(\"Degrees must be between 0 and 360\");\n }\n }\n area(){\n return Math.PI * this.radius ** 2 * this.degrees/360;\n }\n perimeter(){\n return this.arcLength + 2 * this.radius;\n }\n }\n\n let pentagon = new RegularPentagon(9);\n let square = new Square(5);\n let arc = new Arc(1,360 )\n console.log(\"Area of the pentagon: \" + pentagon.area());\n console.log(\"Perimeter of the pentagon: \" + pentagon.perimeter());\n console.log(\"Area of the Square: \"+ square.area());\n console.log(\"Perimeter of the Square: \"+ square.perimeter());\n console.log(\"Area of the arc: \" + arc.area());\n console.log(\"Perimeter of the arc: \" + arc.perimeter());\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + " class RegularShape {\n", + " constructor(sideLength, apothem){\n", + " this.sideLength = sideLength;\n", + " this.apothem = apothem;\n", + " }\n", + " area(){\n", + " throw new Error(\"This method must be overridden!\");\n", + " }\n", + " perimeter(){\n", + " throw new Error(\"This method must be overridden!\");\n", + " }\n", + " }\n", + "\n", + " class Square extends RegularShape {\n", + " constructor(sideLength){\n", + " super(sideLength, sideLength/2);\n", + " }\n", + " area(){\n", + " return this.sideLength ** 2;\n", + " }\n", + " perimeter(){\n", + " return this.sideLength * 4;\n", + " }\n", + " }\n", + "\n", + " class RegularPentagon extends RegularShape{\n", + " constructor(sideLength){\n", + " super(sideLength, sideLength/2*Math.tan(Math.PI/5));\n", + " }\n", + " area(){\n", + " return 5 * this.sideLength * this.apothem / 2;\n", + " }\n", + " perimeter(){\n", + " return this.sideLength * 5;\n", + " }\n", + " }\n", + " class Arc extends RegularShape{\n", + " constructor(radius, degrees){\n", + " // Using sideLength for the arc length of an arc in degrees\n", + " super(radius, radius);\n", + " this.radius = radius;\n", + " this.arcLength = 2 * Math.PI * radius * degrees / 360;\n", + " if(degrees >0 && degrees <= 360){\n", + " this.degrees = degrees;\n", + " }\n", + " else{\n", + " throw new Error(\"Degrees must be between 0 and 360\");\n", + " }\n", + " }\n", + " area(){\n", + " return Math.PI * this.radius ** 2 * this.degrees/360;\n", + " }\n", + " perimeter(){\n", + " return this.arcLength + 2 * this.radius;\n", + " }\n", + " }\n", + "\n", + " let pentagon = new RegularPentagon(9);\n", + " let square = new Square(5);\n", + " let arc = new Arc(1,360 )\n", + " console.log(\"Area of the pentagon: \" + pentagon.area());\n", + " console.log(\"Perimeter of the pentagon: \" + pentagon.perimeter());\n", + " console.log(\"Area of the Square: \"+ square.area());\n", + " console.log(\"Perimeter of the Square: \"+ square.perimeter());\n", + " console.log(\"Area of the arc: \" + arc.area());\n", + " console.log(\"Perimeter of the arc: \" + arc.perimeter());" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Data_Abstractions/2024-11-06-data_abstraction-popcornhacks.ipynb b/_notebooks/Sprint 2/Data_Abstractions/2024-11-06-data_abstraction-popcornhacks.ipynb new file mode 100644 index 000000000..927ea3df2 --- /dev/null +++ b/_notebooks/Sprint 2/Data_Abstractions/2024-11-06-data_abstraction-popcornhacks.ipynb @@ -0,0 +1,201 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "---\n", + "comments: True\n", + "layout: post \n", + "title: Data Abstraction Hacks\n", + "description: An intro to data abstraction\n", + "permalink: /csse/javascript/fundamentals/data-abstraction-hacks\n", + "type: ccc\n", + "author: Veera Kalakota, Santhosh Karthik, Akhil Kulkarni\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Popcorn Hack #1\n", + "Create a child class of the class **Appliance**, and call it's name() function" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": " class Appliance {\n constructor(fridge) {\n this.fridge = fridge;\n }\n name() {\n return \"I am a \" + this.constructor.name + \" and my model is \" + this.fridge;\n }\n }\n // Below this name the class and cause it to inherit from the Appliance class\n class XXXX{\n constructor(name) {\n super(name);\n }\n \n }\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + " class Appliance {\n", + " constructor(fridge) {\n", + " this.fridge = fridge;\n", + " }\n", + " name() {\n", + " return \"I am \" + this.constructor.name + \" and my model is \" + this.fridge;\n", + " }\n", + " }\n", + " // Below this name the class and cause it to inherit from the Appliance class\n", + " class XXXX{\n", + " constructor(name) {\n", + " super(name);\n", + " }\n", + " \n", + " }" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Popcorn Hack 1\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": " class Product{\n constructor(price,size,taxRate) {\n this.price = price;\n this.size = size;\n this.taxRate = taxRate;\n } \n getPrice() {\n return this.price + this.taxRate * this.price;\n }\n product(){\n const className = this.constructor.name.toLowerCase();\n // Does not use and assuming that more parameteres will be added\n return \"You are ordering a \" + className + \" with a price of \" + this.getPrice() + \" dollars, a size of \" + this.size;\n }\n }\n class Bagel extends Product{\n constructor(price, size, taxRate, flavor) {\n super(price, size, taxRate);\n this.flavor = flavor;\n }\n getPrice(){\n return super.getPrice() * this.size;\n }\n product(){\n return super.product() + \" and a flavor of \" + this.flavor;\n }\n }\nvar sesameBagel = new Bagel(1.5, 2, 0.07, \"sesame\");\nconsole.log(sesameBagel.product());\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + "\n", + " class Appliance {\n", + " constructor(name) {\n", + " this.name = name;\n", + " }\n", + " getName() {\n", + " return \"I am a \" + this.constructor.name + \" and my model is \" + this.name;\n", + " }\n", + " }\n", + " // Below this name the class and cause it to inherit from the Appliance class\n", + " class BooleanClearer extends Appliance{\n", + " constructor(name) {\n", + " super(name);\n", + " }\n", + " \n", + " }\n", + "\n", + " const BooleanClearer = new BooleanClearer(\"the one with the big Boolean\")\n", + " console.log(BooleanClearer.getName())\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Popcorn hack 2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + " class Product{\n", + " constructor(price,size,taxRate) {\n", + " this.price = price;\n", + " this.size = size;\n", + " this.taxRate = taxRate;\n", + " } \n", + " getPrice() {\n", + " return this.price + this.taxRate * this.price;\n", + " }\n", + " product(){\n", + " const className = this.constructor.name.toLowerCase();\n", + " return \"You are ordering a \" + className + \" with a price of \" + this.getPrice() + \" dollars, a size of \" + this.size;\n", + " }\n", + " }\n", + " class Bagel extends Product{\n", + " constructor(price, size, taxRate, flavor) {\n", + " super(price, size, taxRate);\n", + " this.flavor = flavor;\n", + " }\n", + " getPrice(){\n", + " return super.getPrice() * this.size;\n", + " }\n", + " product(){\n", + " return super.product() + \" and a flavor of \" + this.flavor;\n", + " }\n", + " }\n", + "\n", + " class Chair extends Product{\n", + " constructor(price, size, taxRate, throwability, comfort) {\n", + " super(price, size, taxRate);\n", + " this.comfort = comfort;\n", + " this.fire = comfort;\n", + " }\n", + " getPrice(){\n", + " return super.getPrice() * this.size;\n", + " }\n", + " product(){\n", + " return super.product() + \" and a fire that is \" + this.fire + \". \" + \"This table is also \" + this.comfort + \" :)\";\n", + " }\n", + " }\n", + "var firetable = new Chair(40, 10, 0.05, \"very spicy\", \"very hard\");\n", + "console.log(firetable.product());" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Iteration/2024-11-2-iteration-homework.ipynb b/_notebooks/Sprint 2/Iteration/2024-11-2-iteration-homework.ipynb new file mode 100644 index 000000000..d66643e09 --- /dev/null +++ b/_notebooks/Sprint 2/Iteration/2024-11-2-iteration-homework.ipynb @@ -0,0 +1,186 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "---\n", + "comments: True\n", + "layout: post\n", + "title: Iteration Homework\n", + "description: An intro to data abstraction\n", + "permalink: /csse/javascript/fundamentals/iteration/hw\n", + "categories: [CSSE JavaScript Fundamentals]\n", + "author: Kian Zhu, Michael Xu and Srinaga Pillutla\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Homework Assignment: for Loop Challenge\n", + "Task: Create a program that does the following:\n", + "\n", + "Initialize an array with the names of five of your favorite movies.\n", + "Use a for loop to iterate through the array and print each movie name to the console.\n", + "After printing all movie names, print a message indicating how many movies you listed." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# **Homework**\n", + "\n", + "Create a **3 by 3, 2D list** that represents a **tictactoe board**.\n", + "Use **\"X\"** for X, **\"O\"** for O, and **None** for empty tiles.\n", + "\n", + "Ex. board = [[\"X\",\"None\",\"O\"], \n", + "       [\"X\",\"O\",\"None\"], \n", + "       [\"O\",\"None\",\"X\"]]\n", + "\n", + "Iterate over the board and **identify whether it is player X's or player O's turn.**\n", + "\n", + "**Hint**: count the number of moves(non-None). (X goes first)\n", + "\n", + "**Optional**: use console.error() to report an error if the board is illegal (ex. 7 \"X\"s and 2 \"O\"s)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## H.W application of While Loops. \n", + "\n", + "Create the Outer Loop:\n", + "\n", + "Use a while loop that runs while outerFactor is less than or equal to 10.\n", + "Initialize the Inner Loop Variable:\n", + "\n", + "Inside the outer loop, create another variable called innerFactor and set it to 1.\n", + "Create the Inner Loop:\n", + "\n", + "Inside the outer loop, use another while loop that runs while innerFactor is less than or equal to 10.\n", + "Calculate the Product:\n", + "\n", + "Inside the inner loop, calculate the product of outerFactor and innerFactor.\n", + "Print the Product:\n", + "\n", + "Print the product using console.log(), formatting the output neatly.\n", + "Increment the Inner Loop Variable:\n", + "\n", + "After printing the product, increment innerFactor by 1.\n", + "Move to the Next Line:\n", + "\n", + "After the inner loop finishes, print a new line to separate rows.\n", + "Increment the Outer Loop Variable:\n", + "\n", + "Increment outerFactor by 1 to move to the next row in the table." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\n// Hw 2 (required)\n// Initialize the outer loop variable\nlet outerFactor = 1;\n\n// Outer loop: runs while outerFactor is less than or equal to 10\nwhile (outerFactor <= 10) {\n \n // Initialize the inner loop variable\n let innerFactor = 1;\n\n // Inner loop: runs while innerFactor is less than or equal to 10\n while (innerFactor <= 10) {\n \n // Calculate the product\n let product = outerFactor * innerFactor;\n \n // Print the product, formatted neatly\n console.log(outerFactor + \" x \" + innerFactor + \" = \" + product);\n \n // Increment the inner loop variable\n innerFactor++;\n }\n \n // Print a new line after each row to separate rows\n console.log(\"\\n\");\n \n // Increment the outer loop variable\n outerFactor++;\n}\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + "\n", + "// Hw 2 (required)\n", + "// Initialize the outer loop variable\n", + "let outerFactor = 1;\n", + "\n", + "// Outer loop: runs while outerFactor is less than or equal to 9\n", + "while (outerFactor <= 9) {\n", + " \n", + " // Initialize the inner loop variable\n", + " let innerFactor = 1;\n", + "\n", + " // Inner loop: runs while innerFactor is less than or equal to 10\n", + " while (innerFactor <= 9) {\n", + " \n", + " // Calculate the product\n", + " let product = outerFactor * innerFactor;\n", + " \n", + " // Print the product, formatted neatly\n", + " console.log(outerFactor + \" x \" + innerFactor + \" = \" + product);\n", + " \n", + " // Increment the inner loop variable\n", + " innerFactor++;\n", + " }\n", + " \n", + " // Print a new line after each row to separate rows\n", + " console.log(\"\\n\");\n", + " \n", + " // Increment the outer loop variable\n", + " outerFactor++;\n", + "}\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "\n", + "// Hw 1 (Extra Credit)\n", + "// Disclaimer these are not my favourite movies, they're random.\n", + "// Initialize an array with favorite movies\n", + "const favoriteMovies = [\"Coolio\", \"The Hatter\", \"Misto\", \"Nightio\", \"Calabin\"];\n", + "\n", + "// Use a for loop to iterate through the array and print each movie name\n", + "for (let i = 0; i < favoriteMovies.length; i++) {\n", + " console.log(favoriteMovies[i]);\n", + "}\n", + "\n", + "// Print a message indicating how many movies were listed\n", + "console.log(\"You listed \" + favoriteMovies.length + \" movies.\");\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Iteration/2024-11-2-iteration-p1.ipynb b/_notebooks/Sprint 2/Iteration/2024-11-2-iteration-p1.ipynb new file mode 100644 index 000000000..fa756cc21 --- /dev/null +++ b/_notebooks/Sprint 2/Iteration/2024-11-2-iteration-p1.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "---\n", + "comments: True\n", + "layout: post\n", + "title: Iteration For Loops\n", + "description: An intro to data abstraction\n", + "permalink: /csse/javascript/fundamentals/iteration/p1\n", + "categories: [CSSE JavaScript Fundamentals]\n", + "author: Kian Zhu\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# What is for loops" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A for loop is a control flow statement that allows you to execute a block of code a certain number of times. It's particularly useful when you know in advance how many times you want to iterate through a block of code." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Syntax of a for Loop\n", + "The syntax of a for loop consists of three main parts:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js \n", + "for (initialization; condition; increment) {\n", + " // Code to be executed on each iteration\n", + "}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Initialization: This sets up a counter variable and runs once at the beginning of the loop.\n", + "\n", + "Condition: Before each iteration, the loop checks this condition. If it's true, the loop continues; if false, the loop ends.\n", + "\n", + "Increment: This updates the counter variable after each iteration." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Example of a for Loop" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js \n", + "for (let i = 1; i <= 5; i++) {\n", + " console.log(i);\n", + "}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Explanation:\n", + "\n", + "Initialization: let i = 1 sets the counter variable i to 1.\n", + "\n", + "Condition: i <= 5 checks if i is less than or equal to 5.\n", + "\n", + "Increment: i++ increases i by 1 after each iteration." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Output\n", + "1\n", + "\n", + "2\n", + "\n", + "3\n", + "\n", + "4\n", + "\n", + "5\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Advanced Usage: Looping Through Arrays\n", + "You can use a for loop to iterate over elements in an array. Here’s an example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js \n", + "let fruits = [\"apple\", \"banana\", \"cherry\"];\n", + "\n", + "for (let i = 0; i < fruits.length; i++) {\n", + " console.log(fruits[i]);\n", + "}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### output\n", + "apple\n", + "\n", + "banana\n", + "\n", + "cherry\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## popcorn 1\n", + "Calculate the Sum\n", + " Write a for loop that calculates the sum of all even numbers from 1 to 20. Output the result to the console.\n", + "\n", + "**Hint**: Any number divided by two results in a remainder of 1 for odd numbers and 0 for even numbers. The modulo operator (`%`) helps you determine this condition. The statement `if (n % 2 == 0)` would be true when `n` is even." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Iteration/2024-11-5-iteration-p2.ipynb b/_notebooks/Sprint 2/Iteration/2024-11-5-iteration-p2.ipynb new file mode 100644 index 000000000..13b7fc3b1 --- /dev/null +++ b/_notebooks/Sprint 2/Iteration/2024-11-5-iteration-p2.ipynb @@ -0,0 +1,253 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "---\n", + "comments: True\n", + "layout: post\n", + "title: Iteration Nested Loops \n", + "description: An intro to data abstraction\n", + "permalink: /csse/javascript/fundamentals/iteration/p2\n", + "categories: [CSSE JavaScript Fundamentals]\n", + "author: Michael Xu\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "plaintext" + } + }, + "source": [ + "# **For loops**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For loops can also be used to iterate through **arrays** and **objects**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Recall using for loops" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "\n", + "const fruits = ['apple','bananas','cherries','durian'];\n", + "\n", + "for (let i = 0; i < fruits.length; i++){\n", + " console.log(i); // print the indices\n", + " console.log(fruits[i]); // print the elements\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "**output:**\n", + "\n", + "0 \n", + "apple \n", + "1 \n", + "bananas \n", + "2 \n", + "cherries \n", + "3 \n", + "durian" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can achieve the same result using the keyword **of** to iterate over arrays" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "\n", + "const fruits = ['apple','bananas','cherries','durian'];\n", + "\n", + "for (let fruit of fruits) { //iterates through each element in the fruits array\n", + " console.log(fruit); //prints each element seperately\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**output:**\n", + "\n", + "apple \n", + "bananas \n", + "cherries \n", + "durian" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Objects\n", + "\n", + "for loops can also be used to iterate **objects** over each **key** and its **value**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js \n", + "\n", + "const personInfo = { // Define an object\n", + " name: \"Alex\",\n", + " age: 30,\n", + " city: \"San Diego\",\n", + " occupation: \"Software Engineer\"\n", + "};\n", + "\n", + "for (let key in personInfo) { // Notice we are using for... in... instead of for... of...\n", + " console.log(key + \": \" + personInfo[key]);\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### **in**:\n", + "Checks for property existence in objects and is used in **for...in** loops to iterate over property keys.\n", + "#### **of**:\n", + "Iterates over iterable objects (like arrays) and is used in **for...of** loops to access values directly." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# **Nested Loops**\n", + "\n", + "Nested loops are similar to nested conditions with for loops within other for loops\n", + "\n", + "#### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "\n", + "const matrix = [ // A 2D array\n", + " [1, 2, 3],\n", + " [4, 5, 6],\n", + " [7, 8, 9]\n", + "];\n", + "for (let row of matrix) { \n", + " for (let column of row) { \n", + " console.log(column); // Output: 1 to 9\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### We can also do mix conditions with for loops" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "\n", + "const numbers = [1,2,3,4,5,6,7,8,9];\n", + "let evenCount = 0;\n", + "\n", + "for (let number of numbers){\n", + " if (number % 2 === 0){ // check if the number is even\n", + " evenCount++ // increment by 1 \n", + " }\n", + "}\n", + "console.log(evenCount) // Output: 4" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Iteration/2024-11-7-Iteration-P3.ipynb b/_notebooks/Sprint 2/Iteration/2024-11-7-Iteration-P3.ipynb new file mode 100644 index 000000000..2771c97f1 --- /dev/null +++ b/_notebooks/Sprint 2/Iteration/2024-11-7-Iteration-P3.ipynb @@ -0,0 +1,204 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "layout: post\n", + "title: 3.8.1/3.8.2 While loops/Nested loops\n", + "author: Srinaga Pillutla \n", + "description: Basic concept for while loops\n", + "permalink: /csp/big-idea/p4/3-8-1\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "source": [ + "## Basic Overview\n", + "\n", + "Condition is always true if the condition is true you have seen it in math have you? 🙃\n", + "An example is x<8 or X>y or x>8\n", + "\n", + "In inside the code you can run any code you want anything you want but it has to be true to statement\n", + "\n", + "## What happens inside the code \n", + "If you run the code it will run for infinate times unless, the statement is false then it will stop and continue to next line or stop oif it is last code \n", + "\n", + "an example can be s`een down here \n", + "The counter which is number set is = 0 and 0<10\n", + "and then it prints each number by +1 \n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Counter is: 0\n", + "Counter after incrementing: 1\n", + "Counter is: 1\n", + "Counter after incrementing: 2\n", + "Counter is: 2\n", + "Counter after incrementing: 3\n", + "Counter is: 3\n", + "Counter after incrementing: 4\n", + "Counter is: 4\n", + "Counter after incrementing: 5\n", + "Counter is: 5\n", + "Counter after incrementing: 6\n", + "Counter is: 6\n", + "Counter after incrementing: 7\n", + "Counter is: 7\n", + "Counter after incrementing: 8\n", + "Counter is: 8\n", + "Counter after incrementing: 9\n", + "Counter is: 9\n", + "Counter after incrementing: 10\n", + "Counter is: 10\n", + "Counter after incrementing: 11\n" + ] + } + ], + "source": [ + "counter = 0\n", + "while counter <= 10:\n", + " print(\"Counter is:\", counter)\n", + " counter += 1\n", + " print(\"Counter after incrementing:\", counter)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "// Initialize a variable\nlet counter = 0;\n\n// While loop starts\nwhile (counter <= 10) {\n console.log(\"Counter is: \" + counter);\n counter++;\n}\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "// Initialize a variable\n", + "let counter = 0;\n", + "\n", + "// While loop starts\n", + "while (counter <= 10) {\n", + " console.log(\"Counter is: \" + counter);\n", + " counter++;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##Popcorn Hack 1\n", + "\n", + "For this one ou have to find an error in the code to demonstrate the knowlege and correct the mistake ion new code cell here is code to find mistake and pls run it in console.log to check if it is right. good luck nd have fun lemem know about questions comemnts and concerns :D. // Initialize the counter\n", + "let counter = 0;\n", + "\n", + "// Loop while counter is less than 5\n", + "while (counter <= 5) { // Mistake: should be < 5\n", + " console.log(\"Counter is: \" + counter); // Print the current counter value\n", + " \n", + " // Increment the counter\n", + " counter = counter + 1; // This is correct but could be simplified to counter++\n", + "}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "source": [ + "##Popcorn Hack 2 Create the Outer Loop:\n", + "\n", + "Use a while loop that runs while outerFactor is less than or equal to 10.\n", + "Initialize the Inner Loop Variable:\n", + "\n", + "Inside the outer loop, create another variable called innerFactor and set it to 1.\n", + "Create the Inner Loop:\n", + "\n", + "Inside the outer loop, use another while loop that runs while innerFactor is less than or equal to 10.\n", + "Calculate the Product:\n", + "\n", + "Inside the inner loop, calculate the product of outerFactor and innerFactor.\n", + "Print the Product:\n", + "\n", + "Print the product using console.log(), formatting the output neatly.\n", + "Increment the Inner Loop Variable:\n", + "\n", + "After printing the product, increment innerFactor by 1.\n", + "Move to the Next Line:\n", + "\n", + "After the inner loop finishes, print a new line to separate rows.\n", + "Increment the Outer Loop Variable:\n", + "\n", + "Increment outerFactor by 1 to move to the next row in the table." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "source": [ + "##Popcorn Hack " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Nested_Conditionals/2024-10-26-nested_conditionals.ipynb b/_notebooks/Sprint 2/Nested_Conditionals/2024-10-26-nested_conditionals.ipynb new file mode 100644 index 000000000..903485e97 --- /dev/null +++ b/_notebooks/Sprint 2/Nested_Conditionals/2024-10-26-nested_conditionals.ipynb @@ -0,0 +1,288 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "comments: true\n", + "layout: post\n", + "title: Nested Conditionals with booleans Javascript Lesson\n", + "description: Nested conditionals with booleans in Javascript are condition statements placed inside condition statements, allowing multiple layers of decision making.\n", + "type: ccc\n", + "author: Anika Marathe\n", + "\n", + "\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "

Booleans with Nested Conditionals

\n", + "\n", + "\n", + "

A boolean is a data type that represents one of two possible values: true or false. Booleans are useful for decision-making in code, as they let us determine if specific conditions are met. For example, if we want to check if someone meets the age requirement for a concert or has a ticket, we might represent these conditions as booleans.

\n", + "\n", + "

A nested boolean is simply a boolean condition used inside another condition. When using nested conditionals (conditions inside other conditions), we can build complex decision-making logic. For example, we might check first if the person is old enough, and if they are, then check if they have a ticket. This kind of logic allows us to handle multiple conditions in a structured way.

\n", + "\n", + "

Here’s an example:

\n", + "\n", + "```javascript\n", + "let isOldEnough = true; // Boolean indicating if the person meets the age requirement\n", + "let hasTicket = false; // Boolean indicating if the person has a ticket\n", + "\n", + "if (isOldEnough) { // Check if the person meets the age requirement\n", + " if (hasTicket) { // Nested condition to check if they have a ticket\n", + " console.log(\"You can attend the concert.\");\n", + " } else {\n", + " console.log(\"You need a ticket to attend the concert.\");\n", + " }\n", + "} else {\n", + " console.log(\"You do not meet the age requirement for this concert.\");\n", + "}\n", + "```\n", + "\n", + "---\n", + "\n", + "1. The code below checks if you can cook a meal at home. \n", + "2. It uses the presence of hunger, and ingredients, to determine if cooking a meal is possible at home.\n", + "3. It uses booleans in the code\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "
\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html\n", + "\n", + "
\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "

Popcorn Hack 2

\n", + "\n", + "1. Open two new code cells and set them to javascript\n", + "2. Copy the code example from above javascript cell into both the new code cells \n", + "3. Change the first new code cell to print \"You aren't hungry. Maybe meal-prep for later if you had ingredients.\" \n", + "4. Change the second new code cell to print \"You can make a cheese sandwich at home.\" " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "let isHungry = true;\n\n// Define ingredients as a JSON object\nconst ingredients = {\n \"bread\": true,\n \"cheese\": true,\n \"tomato\": false\n};\n\nfunction displayMessage(message) {\n console.log(message); // Log to console\n}\n\n// Check if essential ingredients are available\nif (isHungry) {\n if (ingredients.bread && ingredients.cheese) {\n displayMessage(\"You can make a cheese sandwich at home.\");\n } else if (ingredients.bread) {\n displayMessage(\"You only have bread, maybe make toast.\");\n } else {\n displayMessage(\"You should order food since you don't have enough ingredients.\");\n }\n} else {\n displayMessage(\"You aren't hungry. Maybe meal-prep for later if you had ingredients.\");\n}\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "let isHungry = true;\n", + "\n", + "// Define ingredients as a JSON object\n", + "const ingredients = {\n", + " \"bread\": true,\n", + " \"cheese\": true,\n", + " \"tomato\": false\n", + "};\n", + "\n", + "function displayMessage(message) {\n", + " console.log(message); // Log to console\n", + "}\n", + "\n", + "// Check if essential ingredients are available\n", + "if (isHungry) {\n", + " if (ingredients.bread && ingredients.cheese) {\n", + " displayMessage(\"You can make a cheese sandwich at home.\");\n", + " } else if (ingredients.bread) {\n", + " displayMessage(\"You only have bread, maybe make toast.\");\n", + " } else {\n", + " displayMessage(\"You should order food since you don't have enough ingredients.\");\n", + " }\n", + "} else {\n", + " displayMessage(\"You aren't hungry. Maybe meal-prep for later if you had ingredients.\");\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [], + "source": [ + "%%js\n", + "let isHungry = false;\n", + "\n", + "// Define ingredients as a JSON object\n", + "const ingredients = {\n", + " \"bread\": true,\n", + " \"cheese\": false,\n", + " \"tomato\": false\n", + "};\n", + "\n", + "function displayMessage(message) {\n", + " console.log(message); // Log to console\n", + "}\n", + "\n", + "// Check if essential ingredients are available\n", + "if (isHungry) {\n", + " if (ingredients.bread && ingredients.cheese) {\n", + " displayMessage(\"You can make a cheese sandwich at home.\");\n", + " } else if (ingredients.bread) {\n", + " displayMessage(\"You only have bread, maybe make toast.\");\n", + " } else {\n", + " displayMessage(\"You should order food since you don't have enough ingredients.\");\n", + " }\n", + "} else {\n", + " displayMessage(\"You aren't hungry. Maybe meal-prep for later if you had ingredients.\");\n", + "}" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Nested_Conditionals/intoduction_to_nested_conditionals.ipynb b/_notebooks/Sprint 2/Nested_Conditionals/intoduction_to_nested_conditionals.ipynb new file mode 100644 index 000000000..8e46f2f8b --- /dev/null +++ b/_notebooks/Sprint 2/Nested_Conditionals/intoduction_to_nested_conditionals.ipynb @@ -0,0 +1,332 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "comments: true\n", + "layout: post\n", + "title: The basics of Nested Condiotionals\n", + "description: Nested conditionals in JavaScript allow for more complex decision-making by placing one conditional statement inside another. This structure enables a program to check additional conditions only if the previous condition is true, creating a layered decision process. In this lesson, students will learn how to implement nested if, else if, and else statements to create more specific control flows in their programs. Through examples and exercises, they will gain a deeper understanding of how to manage multiple conditions effectively, enhancing the logic of their code.\n", + "type: ccc\n", + "author: Lara Banjac\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "

\n", + " Nested Conditionals Basics (Part 1)\n", + "

\n", + "\n", + "\n", + "\n", + "
To gain a better understanding about Nested Conditionals and how they work, first we need to understand what condtionals are; Conditionals in general are \"if-then\" statements. They allow your program to make decisions based on certain conditions. If the condition is true, the program will do one thing; if it’s false, the program will do something else (or nothing at all). Here's an example. \n", + "Think of it as asking a question and then deciding what to do based on the answer:\n", + "\n", + " Question: \"How are you doing?\"\n", + "\n", + " Answer/Input: \"Good!\"\n", + " Result/Output: \"Glad to hear that!^^\"\n", + "\n", + " Alternative Answer/Input: \"Not that well\"\n", + " Alternative Result: \"Sorry to hear that, I hope it isn't that bad.\"\n", + "\n", + "On the other hand, Nested Conditionals are conditionals within other conditionals. Let's use the previous example and extend it to an example with nested conditionals:\n", + "\n", + " Question: \"How are you doing?\"\n", + "\n", + " Answer/Input: \"Good!\"\n", + "\n", + " Result/Output: \"Oooh~! Did something fun happen?\"\n", + "\n", + " Answer/Input # 2: \"Actually, yes, I got an A for an assignment in my CSSE class ^^\"\n", + "\n", + " Result/Output # 2: \"Ooh nice job! ^^\"\n", + "\n", + " Alternative Answer/Input: \"Not that well\"\n", + "\n", + " Alternative Result: \"Sorry to hear that, what happend?\"\n", + "\n", + " Answer/Input #2: \"I threw up in front of my entire class.\"\n", + " \n", + " result/output #2: \"Oh... That probably sucks...\"
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "

\n", + " Popcorn Hack #1\n", + "

\n", + "\n", + "\n", + "\n", + "
This code gives the player the option to pick between a red and green apple and decide whether or not to eat it.\n", + "1.Try changing the values of appleColour to \"green\" and eatApple to \"no\".\n", + "2.Try adding a scenario for what would happen if the player found a yellow apple as well. Remember to change to the value of appleColor to \"yellow\" to get a different result." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "
\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html\n", + "\n", + "
\n", + "\n", + "" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [], + "source": [ + "// popcron 1\n", + "%%html\n", + "\n", + "
\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "

\n", + " How You Can Utilize this in your RPG\n", + "

\n", + "\n", + "\n", + "\n", + "
There are several things you can use nested conditionals in your RPG for. For example, you can create interactions (like the apple example shown above) or more complex dialogue with other NPC's, that could impact the outcomes and endings of the plot.And since you guys love fighting so much, you could also try to create a combat system in which the player can choose between different actions such as, attacking, defending, fleeing using an item, etc. and depending on the players decision there could be different outcomes. :)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Nested_Conditionals/nested_conditionalshw.ipynb b/_notebooks/Sprint 2/Nested_Conditionals/nested_conditionalshw.ipynb new file mode 100644 index 000000000..49c71f8bd --- /dev/null +++ b/_notebooks/Sprint 2/Nested_Conditionals/nested_conditionalshw.ipynb @@ -0,0 +1,132 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "comments: true\n", + "layout: post\n", + "title: CSP Period 4 Unit 3.7.2 Nested Conditionals Javascript Lesson\n", + "description: Nested conditionals in JavaScript allow for more complex decision-making by placing one conditional statement inside another. This structure enables a program to check additional conditions only if the previous condition is true, creating a layered decision process. In this lesson, students will learn how to implement nested if, else if, and else statements to create more specific control flows in their programs. Through examples and exercises, they will gain a deeper understanding of how to manage multiple conditions effectively, enhancing the logic of their code.\n", + "permalink: /csp/big-idea/p4/3-7-2\n", + "type: ccc\n", + "author: Avantika Chittari\n", + "menu: nav/csp_units/csp_unit3_p4_fundamentals.html\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "source": [ + "

Homework - Integers, Booleans, AND Random

\n", + "\n", + "Objective:\n", + "Write a JavaScript program that randomly assigns a student grade level (from 0 to 12) and outputs the school level the student would be in (kindergarten, elementary, middle, or high school). The program also identifies if the student is in their last year at their current school level.\n", + "\n", + "Instructions:\n", + "\n", + "Open a JavaScript file (e.g., schoolLevel.js).\n", + "\n", + "Generate a Random Grade:\n", + "\n", + "Use Math.random() to generate a random number between 0 to 1 and multiply it by 12, which will represent the student’s grade.\n", + "Round the number to the nearest whole number using Math.round().\n", + "Store this number in a variable called grade.\n", + "Print the grade to the console with a message such as, \"You are in ___ grade.\"\n", + "Determine the School Level:\n", + "\n", + "Use if statements to check the value of grade and print which school level the student is in:\n", + "Kindergarten for grade 0\n", + "Elementary School for grades 1–5\n", + "Middle School for grades 6–8\n", + "High School for grades 9–12\n", + "For each school level, add an additional check to see if the student is in their final year. If all is done correctly, it will print a message like this, “You will graduate this year from _____.”\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "source": [ + "- Booleans are a data type that can only have two different values True or Flase. \n", + "- Random generates random values with unpredictable results, usually within a specified range such as 0-1" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "const grade = Math.round(Math.random()*12)\n//console.log(\"Student is in the \" + grade + \" grade\")\n \nfunction findSchool(studentGrade){\n console.log(studentGrade)\n if (studentGrade == 0){\n return \"Kindergarten School\"\n }else if(studentGrade == 1 || studentGrade == 2 || studentGrade == 3 || studentGrade == 4 || studentGrade == 5){ // grades 1 -5\n return \"Elementry School\"\n }else if(studentGrade == 6 ||studentGrade == 7 ||studentGrade == 8 ){ // grades 6 - 8\n return \"Middle School\"\n }else if(studentGrade > 8){ // grades 9 - 12\n return \"High School\"\n }\n}\n\nconsole.log(findSchool(grade))\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "const grade = Math.round(Math.random()*12)\n", + "//console.log(\"Student is in the \" + grade + \" grade\")\n", + " \n", + "function findSchool(studentGrade){\n", + " console.log(studentGrade)\n", + " if (studentGrade == 0){\n", + " return \"Kindergarten School\"\n", + " }else if(studentGrade == 1 || studentGrade == 2 || studentGrade == 3 || studentGrade == 4 || studentGrade == 5){ // grades 1 -5\n", + " return \"Elementry School\"\n", + " }else if(studentGrade == 6 ||studentGrade == 7 ||studentGrade == 8 ){ // grades 6 - 8\n", + " return \"Middle School\"\n", + " }else if(studentGrade > 8){ // grades 9 - 12\n", + " return \"High School\"\n", + " }\n", + "}\n", + "\n", + "console.log(findSchool(grade))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Strings/2024-10-30-strings-lesson-4-1.ipynb b/_notebooks/Sprint 2/Strings/2024-10-30-strings-lesson-4-1.ipynb new file mode 100644 index 000000000..53ed2c60e --- /dev/null +++ b/_notebooks/Sprint 2/Strings/2024-10-30-strings-lesson-4-1.ipynb @@ -0,0 +1,310 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lesson 4.1: Strings\n", + "\n", + "### Exploring strings in JavaScript\n", + "In this lesson, we'll explore how to use and manipulate strings in JavaScript." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Printing Strings\n", + "You can print strings directly or using variables. Here's an example of both:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "dog\n", + "cat\n", + "caribou\n" + ] + } + ], + "source": [ + "%%js\n", + "// Directly printing a string\n", + "console.log(\"dog\");\n", + "\n", + "// Using Variables\n", + "const animal = \"cat\";\n", + "const favoriteAnimal = \"caribou\";\n", + "\n", + "console.log(animal); // Output: cat\n", + "console.log(favoriteAnimal); // Output: caribou\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Handling Apostrophes\n", + "If your string contains an apostrophe, make sure to escape it when using single quotes." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm eating pizza\n", + "I'm eating lasagna\n" + ] + } + ], + "source": [ + "%%js\n", + "// Escaping apostrophes in strings\n", + "const food2 = 'I\\'m eating pizza';\n", + "const food3 = \"I'm eating lasagna\";\n", + "\n", + "console.log(food2); // Output: I'm eating pizza\n", + "console.log(food3); // Output: I'm eating lasagna\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Strings with Multiple Lines\n", + "You can create multi-line strings using template literals (backticks). Here's an example:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "my favorite animal\n", + "is associated with winter\n", + "and Christmas\n" + ] + } + ], + "source": [ + "%%js\n", + "// Multi-line string using template literals\n", + "const riddle = `my favorite animal\n", + "is associated with winter\n", + "and Christmas`;\n", + "\n", + "console.log(riddle);\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Length of a String\n", + "You can find the length of a string using the `.length` property." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "11\n" + ] + } + ], + "source": [ + "%%js\n", + "// Find the length of a string\n", + "console.log(\"earthmovers\".length); // Output: 11\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Printing Specific Parts of a String\n", + "You can extract specific parts of a string using indexing and slicing. Here are some examples:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "c\n", + "chucks do n\n", + "woodchucks do not act\n", + "dirt more often than not\n" + ] + } + ], + "source": [ + "%%js\n", + "// Extracting specific parts of a string\n", + "const funFact = \"woodchucks do not actually chuck wood, they chuck dirt more often than not\";\n", + "\n", + "// Specific character:\n", + "console.log(funFact[10]); // Output: 'c'\n", + "\n", + "// Range (substring):\n", + "console.log(funFact.slice(5, 15)); // Output: 'chucks do n'\n", + "\n", + "// Slicing:\n", + "console.log(funFact.slice(0, 25)); // Output: 'woodchucks do not act'\n", + "console.log(funFact.slice(35)); // Output: 'dirt more often than not'\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Popcorn Hack - Palindromes\n", + "A palindrome is a word or phrase that reads the same backward as forward. You can create a function to check for palindromes. Here's a function that does that:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "// Function to check if a string is a palindrome\nfunction palindrome(inputStr) {\n // Remove spaces and convert the string to lowercase\n const cleanStr = inputStr.replace(/\\s+/g, '').toLowerCase();\n // Check if the cleaned string is equal to its reverse\n return cleanStr === cleanStr.split('').reverse().join('');\n}\n\nconsole.log(palindrome(\"racecar\")); // Output: false\nconsole.log(palindrome(\"hi\")); // Output: false\n```\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "// Function to check if a string is a palindrome\n", + "function palindrome(inputStr) {\n", + " // Remove spaces and convert the string to lowercase\n", + " const cleanStr = inputStr.replace(/\\s+/g, '').toLowerCase();\n", + " // Check if the cleaned string is equal to its reverse\n", + " return cleanStr === cleanStr.split('').reverse().join('');\n", + "}\n", + "\n", + "console.log(palindrome(\"racecar\")); // Output: false\n", + "console.log(palindrome(\"dog\")); // Output: false\n", + "```\n" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "function isPalindrome(str) {\n\n str = str.toLowerCase().replace(/[^a-z0-9]/g, '');\n\n\n let reversedStr = str.split('').reverse().join('');\n\n\n return str === reversedStr;\n}\n\n\nconsole.log(isPalindrome(\"aibohphobia\"));\nconsole.log(isPalindrome(\"hello\")); \nconsole.log(isPalindrome(\"A man, a plan, a canal Panama\")); \n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "function isPalindrome(str) {\n", + "\n", + " str = str.toLowerCase().replace(/[^a-z0-9]/g, '');\n", + "\n", + "\n", + " let reversedStr = str.split('').reverse().join('');\n", + "\n", + "\n", + " return str === reversedStr;\n", + "}\n", + "\n", + "\n", + "console.log(isPalindrome(\"aibohphobia\"));\n", + "console.log(isPalindrome(\"bug\")); \n", + "console.log(isPalindrome(\"A can, a dan, a laughing cow\")); \n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Sprint 2/Strings/2024-10-30-strings-lesson-4-2.ipynb b/_notebooks/Sprint 2/Strings/2024-10-30-strings-lesson-4-2.ipynb new file mode 100644 index 000000000..b8d069e28 --- /dev/null +++ b/_notebooks/Sprint 2/Strings/2024-10-30-strings-lesson-4-2.ipynb @@ -0,0 +1,266 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "901babb1", + "metadata": { + "vscode": { + "languageId": "Javascript" + } + }, + "outputs": [], + "source": [ + "---\n", + "comments: true\n", + "layout: post\n", + "title: Strings and functions\n", + "description: Strings and functions\n", + "author: Matthew Borg\n", + "permalink: /csse/lessons/strings/2024-10-30-strings-lesson-4-2.ipynb/\n", + "categories: [Strings and Functions]\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "1062f58b", + "metadata": {}, + "source": [ + "## Strings and Functions\n", + "\n", + "Some strings below can help find the instances of a certain word to replacing a word in a sentence at random\n" + ] + }, + { + "cell_type": "markdown", + "id": "13ec6077", + "metadata": {}, + "source": [ + "* const lionFact = sets the value for lionFact\n", + "* toLowerCase and toUpperCase makes the given sentence in lionFact entirely lowercase or Uppercase" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2e7fe24f", + "metadata": {}, + "outputs": [], + "source": [ + "// String Example and Case Conversion\n", + "const lionFact = \"lions are the only cats that live in groups\";\n", + "\n", + "// Convert to lowercase and uppercase\n", + "console.log(lionFact.toLowerCase()); // Lowercase\n", + "console.log(lionFact.toUpperCase()); // Uppercase" + ] + }, + { + "cell_type": "markdown", + "id": "465fc2e8", + "metadata": {}, + "source": [ + "lions are the only cats that live in groups\n", + "\n", + "LIONS ARE THE ONLY CATS THAT LIVE IN GROUPS" + ] + }, + { + "cell_type": "markdown", + "id": "26214145", + "metadata": {}, + "source": [ + "## Occurrences\n", + "* The .match() method returns all matches of the string \"the\" in tiger_fact using a regular expression (/the/g).\n", + "\n", + "* The g flag ensures that the following code finds all occurrences in the string, not just the first one." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4db746f6", + "metadata": {}, + "outputs": [], + "source": [ + "// Count occurrences of the word 'groups'\n", + "let count = (lionFact.match(/the/g) || []).length;\n", + "console.log(count); " + ] + }, + { + "cell_type": "markdown", + "id": "4604c864", + "metadata": {}, + "source": [ + "## Finding Index\n", + "* index is finding the first letter of a given word in a given const" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f5bd3d88", + "metadata": {}, + "outputs": [], + "source": [ + "// Example finding Index of a Substring\n", + "console.log(lionFact.indexOf(\"group\")); // Find the index of the word 'group'" + ] + }, + { + "cell_type": "markdown", + "id": "54ab8575", + "metadata": {}, + "source": [ + "38" + ] + }, + { + "cell_type": "markdown", + "id": "3dfca524", + "metadata": {}, + "source": [ + "The g in group was the 38th character in the lionFact " + ] + }, + { + "cell_type": "markdown", + "id": "094711ee", + "metadata": {}, + "source": [ + "## Replacing Substrings\n", + "\n", + "* .replace can replace a word in a given const to another word as shown below" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a12f44be", + "metadata": {}, + "outputs": [], + "source": [ + "// Replacing Substrings\n", + "let newLionFact = lionFact.replace('lions', 'giraffes');\n", + "console.log(newLionFact); // Replaced string\n", + "\n", + "// Or replace it directly\n", + "lionFact = lionFact.replace('lions', 'giraffes');\n", + "console.log(lionFact); // Replaced string directly" + ] + }, + { + "cell_type": "markdown", + "id": "d9fa4289", + "metadata": {}, + "source": [ + "giraffes are the only cats that live in groups" + ] + }, + { + "cell_type": "markdown", + "id": "2d8c20dc", + "metadata": {}, + "source": [ + "## Concatenation\n", + "* Used to join together multiple variables\n", + "* can get messy at times as shown below if not in good format" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7d04eb30", + "metadata": {}, + "outputs": [], + "source": [ + "// Concatenation\n", + "let fish = \"fish\";\n", + "let fish1 = \"angel\";\n", + "let fish2 = \"cat\";\n", + "let fish3 = \"puffer\";\n", + "\n", + "// Bad format\n", + "let badFormatSpecies = fish1 + fish + fish2 + fish + fish3 + fish;\n", + "console.log(badFormatSpecies);\n", + "\n", + "// Good format with commas\n", + "let goodFormatSpecies = `${fish1}${fish}, ${fish2}${fish}, and ${fish3}${fish}`;\n", + "console.log(goodFormatSpecies);" + ] + }, + { + "cell_type": "markdown", + "id": "616c7ba2", + "metadata": {}, + "source": [ + "angelfishcatfishpufferfish\n", + "\n", + "angelfish, catfish, pufferfish" + ] + }, + { + "cell_type": "markdown", + "id": "464372d0", + "metadata": {}, + "source": [ + "## Explanation for \"Good\" and \"Bad\" formatting\n", + "\n", + "* fish1 + fish: Concatenates the value of fish1 with fish. This is equivalent to what you can do in Python with fish1 + fish.\n", + "\n", + "* , ' ': The comma and space are explicitly added in between fish1 + fish and fish2 + fish to ensure proper formatting and cleaning output.\n", + "\n", + "* ${} Templateliteral.The ${} syntax is used to embed expressions inside the string. Each ${fish1}${fish} inserts the value of fish1 followed by fish into the string." + ] + }, + { + "cell_type": "markdown", + "id": "95e57c7b", + "metadata": {}, + "source": [ + "## Formatted Strings\n", + "\n", + "* The variable betterFormatSpecies is defined using a template literal (denoted by backticks `).\n", + "\n", + "* Inside the template literal, the values of the variables fish1, fish2, fish3, and fish are embedded using ${} syntax from before.\n", + "\n", + "* This string uses commas to separate the fish types and includes the word \"and\" before the last fish." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "389ccd53", + "metadata": {}, + "outputs": [], + "source": [ + "// Formatted Strings\n", + "let betterFormatSpecies = `${fish1}${fish}, ${fish2}${fish}, and ${fish3}${fish} are my favorite fish!`;\n", + "console.log(betterFormatSpecies);" + ] + }, + { + "cell_type": "markdown", + "id": "950f1ade", + "metadata": {}, + "source": [ + "angelfish, catfish, pufferfish are my favorite fish!" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "JavaScript", + "language": "javascript", + "name": "javascript" + }, + "language_info": { + "name": "javascript", + "version": "latest" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/_notebooks/Sprint 2/Strings/2024-10-30-strings-lesson-4-3.ipynb b/_notebooks/Sprint 2/Strings/2024-10-30-strings-lesson-4-3.ipynb new file mode 100644 index 000000000..f371b4c00 --- /dev/null +++ b/_notebooks/Sprint 2/Strings/2024-10-30-strings-lesson-4-3.ipynb @@ -0,0 +1,58 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Introduction to Strings in JavaScript\n", + "\n", + "Strings are one of the most commonly used data types in JavaScript. They are immutable, which means their values cannot be changed once they are created.\n", + "\n", + "## Defining Strings\n", + "In JavaScript, you can define a string using either single (`'`) or double (`\"`) quotes. String indexing starts at `0`.\n", + "\n", + "### Key Examples:\n", + "\n", + "1. **Displaying a String**\n", + " ```javascript\n", + " console.log('This is a simple string');\n", + " ```\n", + "2. **String Stored in a Variable**\n", + " ```javascript\n", + " let message = 'This is stored in a variable';\n", + " console.log(message);\n", + " ```\n", + "3. **Including Quotes Inside Strings**\n", + " ```javascript\n", + " console.log('The cat said \\\"Hello!\\\" as it jumped onto the table');\n", + " ```\n", + "4. **Concatenating Two Strings**\n", + " ```javascript\n", + " let firstWord = 'good';\n", + " let secondWord = 'morning';\n", + " console.log(firstWord + ' ' + secondWord); // good morning\n", + " ```\n", + "5. **Concatenating Variables and Text**\n", + " ```javascript\n", + " let animal = 'elephant';\n", + " let habitat = 'the savanna';\n", + " console.log('The ' + animal + ' lives in ' + habitat + '.');\n", + " ```\n", + "6. **Template Literals for Easier Concatenation**\n", + " ```javascript\n", + " let location = 'the jungle';\n", + " let animalTwo = 'tiger';\n", + " console.log(`The ${animalTwo} prowls through ${location}.`);\n", + " ```\n", + "7. **Using Line Breaks in Template Literals**\n", + " ```javascript\n", + " let poem = `The moonlight shines\non the calm sea.\nA quiet night.`;\n", + " console.log(poem);\n", + " ```\n" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/_notebooks/Sprint 2/images/mario.png b/_notebooks/Sprint 2/images/mario.png new file mode 100644 index 000000000..9d5c469c6 Binary files /dev/null and b/_notebooks/Sprint 2/images/mario.png differ diff --git a/_notebooks/Sprint 2/images/test b/_notebooks/Sprint 2/images/test new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/_notebooks/Sprint 2/images/test @@ -0,0 +1 @@ + diff --git a/_notebooks/Sprint 2/mari b/_notebooks/Sprint 2/mari new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/_notebooks/Sprint 2/mari @@ -0,0 +1 @@ + diff --git a/_notebooks/Variables/2024-10-25-variables.ipynb b/_notebooks/Variables/2024-10-25-variables.ipynb new file mode 100644 index 000000000..38a28042c --- /dev/null +++ b/_notebooks/Variables/2024-10-25-variables.ipynb @@ -0,0 +1,496 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "layout: post\n", + "title: JavaScript Variables\n", + "description: JavaScript Variables\n", + "categories: [JavaScript]\n", + "comments: True\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Variables in JavaScript\n", + "\n", + " Taught by Aria, Cason, and Ethan\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What are variables in JavaScript?\n", + "Variables in JavaScript are used to store data that can be referenced and manipulated in a program. They act as containers for values and can hold different types of data, such as numbers, strings, objects, and more.\n", + "\n", + "- Variables are used to simplify code\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The three types of keywords for a variable declaration in JavaScript are\n", + " var, let, and const. \n", + " \n", + " **NOTE:** Var is an outdated keyword in Javascript. \n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Creating variables\n", + "\n", + "Variables can be created and assigned values by using the assignment operator \"=\"\n", + "\n", + "\n", + "### Variable naming\n", + "\n", + "- **Camel Case (camelCase):** Commonly used in JavaScript, Java, and C#. Example: `myVariableName`\n", + "\n", + "- **Pascal Case (PascalCase):** Often used in C#, and for class names in many languages. Example: `MyVariableName`\n", + "\n", + "- **Snake Case (snake_case):** Frequently used in Python and Ruby. Example: `my_variable_name`\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nconst userName = \"Mario\"; \nlet favFood = \"spaghetti\";\nconst favSport = \"kart racing\";\n\nconsole.log(\"Hello! You can call me \" + userName); //This will print \"Hello! You can call me Mario\"\nconsole.log(\"I LOVE eating \" + favFood); //This will print \"I LOVE eating Spaghetti\"\nconsole.log(\"My favorite sport is \" + favSport); //This will print \"My favorite sport is kart racing\"\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%javascript\n", + "\n", + "const userName = \"Mario\"; \n", + "let favFood = \"spaghetti\";\n", + "const favSport = \"kart racing\";\n", + "\n", + "console.log(\"Hello! You can call me \" + userName); //This will print \"Hello! You can call me Mario\"\n", + "console.log(\"I LOVE eating \" + favFood); //This will print \"I LOVE eating Spaghetti\"\n", + "console.log(\"My favorite sport is \" + favSport); //This will print \"My favorite sport is kart racing\"" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- As you can see, because this is in javascript, camelCase is being used\n", + "\n", + "- Once a variable is created, it may be used throughout the entire program\n", + "\n", + "*Here it is in use, open your console to see the output!*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Variable Types\n", + "\n", + "### Data Types in JavaScript:\n", + "- Primitive Data Types:\n", + " - `Number` \n", + " - `String`\n", + " - `Boolean`\n", + " - `Null`\n", + " - `Undefined`\n", + " - `Symbol`\n", + "- Non-primitive Data Types:\n", + " - `Object`\n", + " - `Array`\n", + " - `Function`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "### Integer Variables in JavaScript\n", + "\n", + "Integer variables in JavaScript are used to store whole numbers without any decimal points. They can be positive, negative, or zero. In JavaScript, integers are typically represented using the `number` data type.\n", + "\n", + "### Example:\n" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nconst a = 25; //This is a number variable\nlet b = 10; //This is a number variable\nlet sum = a + b; //This is a number variable\n\nconsole.log(a); //This will print 25\nconsole.log(b); //This will print 10\nconsole.log(sum); //This will print 35\nconsole.log(a * b); //This will print 250\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "\n", + "const a = 25; //This is a number variable\n", + "let b = 10; //This is a number variable\n", + "let sum = a + b; //This is a number variable\n", + "\n", + "console.log(a); //This will print 25\n", + "console.log(b); //This will print 10\n", + "console.log(sum); //This will print 35\n", + "console.log(a * b); //This will print 250" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Strings\n", + "\n", + "When phrases or sentences are assigned a variable name, they can be referenced later.\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "\n", + "\n", + "let question = \"How much do you like this lesson?\"; //This is a string variable\n", + "let answer = \"a lot!\"; //This is a string variable\n", + "\n", + "console.log(question); //This will print \"How much do you like this lesson?\"\n", + "console.log(answer); //This will print \"a lot!\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Popcorn Hack #1\n", + "\n", + "### Open the notebook with the Hacks in it, \"2024-10-29-variables_popcorn_hax.ipynb\", and complete the first popcorn hack\n", + "\n", + "### Booleans\n", + "\n", + "Booleans in JavaScript are a fundamental data type that can hold one of two values: true or false. They are often used in conditional statements to control the flow of a program.\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nconst isCoder = true; //This is a boolean variable\nconst isDesigner = false; //This is a boolean variable\n\nconsole.log(isCoder); //This will print true\nconsole.log(isDesigner); //This will print false\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "\n", + "const isCoder = true; //This is a boolean variable\n", + "const isDesigner = false; //This is a boolean variable\n", + "\n", + "console.log(isCoder); //This will print true\n", + "console.log(isDesigner); //This will print false" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Nulls" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `null` value signifies the deliberate absence of any object value. It is commonly used to indicate that a variable should not hold any value.\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nlet myBankBalance = null; //This is a null variable\n\nconsole.log(myBankBalance); //This will print null \n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + "\n", + "let myBankBalance = null; //This is a null variable\n", + "\n", + "console.log(myBankBalance); //This will print null " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Undefined\n", + "\n", + "A variable in JavaScript that has been declared but not assigned a value will have the value `undefined`.\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nlet myHeight; //This is an undefined variable\n\nconsole.log(myHeight); //This will print undefined\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "\n", + "let myHeight; //This is an undefined variable\n", + "\n", + "console.log(myHeight); //This will print undefined" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Symbol\n", + "\n", + "Symbols are unique and immutable data types primarily used as object property keys.\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\nlet myRPG = Symbol(\"Pokemon\"); //This is a symbol variable\n\nconsole.log(myRPG); //This will print Symbol(Pokemon)\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + "\n", + "let myRPG = Symbol(\"Pokemon\"); //This is a symbol variable\n", + "\n", + "console.log(myRPG); //This will print Symbol(Pokemon)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Popcorn Hack #2\n", + "\n", + "### Open the notebook with the Hacks in it, \"2024-10-29-variables_popcorn_hax.ipynb\", and complete the second popcorn hack" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Arrays and Objects\n", + "\n", + "**Arrays**\n", + "\n", + "Arrays are data structures that allow you to store multiple values in a single variable. Each value in an array is called an element, and arrays can hold values of any data type.\n", + "\n", + "**Objects**\n", + "\n", + "Objects are collections of key-value pairs, where each key (also known as a property) is associated with a value. Objects are a fundamental data type in JavaScript and are similar to dictionaries in Python. They are also referred to as **JSON Objects**.\n", + "\n", + "**Functions**\n", + "\n", + " a block of code designed to perform a particular task. Functions are fundamental building blocks in JavaScript and allow you to encapsulate code for reuse, modularity, and organization\n", + "\n", + "### Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "//This is an array variable\nlet characterPosition = [\"1 fish\", \"2 fish\", \"red fish\", \"blue fish\"]; //This is an array variable\n console.log(characterPosition); //This will print [\"1 fish\", \"2 fish\", \"red fish\", \"blue fish\"]\n\n //This is an object variable\n let character = \n {name: \"Mario\", \n age: 35, \n height: 1.55, \n weight: 70\n }; //This is an object variable\n console.log(character); //This will print {name: \"Mario\", age: 35, height: 1.55, weight: 70}\n\n //This is a function variable\n function request(song) {\n return \"Now playing \" + songName + \" by \" + artistName;\n }\n\nlet songName = \"Despacito\"; //This is a string variable\nlet artistName = \"Luis Fonsi\"; //This is a string variable\n\n console.log(request(\"Despacito\")); //This will print \"Now playing Despacito by Luis Fonsi\"\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js \n", + "//This is an array variable\n", + "let characterPosition = [\"1 fish\", \"2 fish\", \"red fish\", \"blue fish\"]; //This is an array variable\n", + " console.log(characterPosition); //This will print [\"1 fish\", \"2 fish\", \"red fish\", \"blue fish\"]\n", + "\n", + " //This is an object variable\n", + " let character = \n", + " {name: \"Mario\", \n", + " age: 35, \n", + " height: 1.55, \n", + " weight: 70\n", + " }; //This is an object variable\n", + " console.log(character); //This will print {name: \"Mario\", age: 35, height: 1.55, weight: 70}\n", + "\n", + " //This is a function variable\n", + " function request(song) {\n", + " return \"Now playing \" + songName + \" by \" + artistName;\n", + " }\n", + "\n", + "let songName = \"She\"; //This is a string variable\n", + "let artistName = \"Tyler the Creator and Frank Ocean\"; //This is a string variable\n", + "\n", + " console.log(request(\"Despacito\")); //This will print \"Now playing Despacito by Luis Fonsi\"" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/_notebooks/Variables/2024-10-28-variables_hw.ipynb b/_notebooks/Variables/2024-10-28-variables_hw.ipynb new file mode 100644 index 000000000..bd279ec27 --- /dev/null +++ b/_notebooks/Variables/2024-10-28-variables_hw.ipynb @@ -0,0 +1,61 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Variables Homework (Show what you know!) \n", + "\n", + "### Homework Problem: Understanding JavaScript Variables \n", + "\n", + "### Creating Variables\n", + "\n", + "\n", + "1. **Create three variables as an object variable**:\n", + " - A variable called `studentName` that stores your name as a string.\n", + " - A variable called `age` that stores your age as a number.\n", + " - A variable called `isStudent` that stores a boolean value indicating whether you are a student (use `true` or `false`).\n", + "\n", + " 2. **Create a function variable that displays that your favorite song is playing**:\n", + " \n", + " - A variable called `favoriteSong` that stores the name of your favorite song.\n", + " - A variable called `songArtist` that stores the song's artist.\n", + " - A function called `playFavoriteSong` that logs a message saying \"Now playing [favoriteSong] by [songArtist]\".\n", + "\n", + "\n", + "\n", + "3. **Using the variables you created**, write a sentence using `console.log()` to display:\n", + " - Your name.\n", + " - Your age.\n", + " - Whether you are a student.\n", + " - An output that states that your favorite song is now playing\n", + "\n", + "\n", + " Example output:\n", + "My name is [Your Name], I am [Your Age] years old, and it is [true/false] that I am a student. \n", + "Now playing Champion by Kanye West" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/Variables/2024-10-29-variables_popcorn_hax.ipynb b/_notebooks/Variables/2024-10-29-variables_popcorn_hax.ipynb new file mode 100644 index 000000000..bf5a52667 --- /dev/null +++ b/_notebooks/Variables/2024-10-29-variables_popcorn_hax.ipynb @@ -0,0 +1,107 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Variables Hacks \n", + "\n", + " Taught by Aria, Cason, and Ethan" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "plaintext" + } + }, + "source": [ + "\n", + "### Popcorn Hack 1: Variable Naming, and Strings in JavaScript \n", + "\n", + "#### Instructions:\n", + "1. Open a new cell and set its type to `Code`.\n", + "\n", + "2. Using the correct `variable naming case` for JavaScript \n", + "\n", + "3. Create a string variable for `\"gameQuestion\"` and let it equal: `\"My favorite video game is \"`\n", + "\n", + "4. create a variable for `\"gameAnswer\"` and let it equal: your favorite game\n", + "\n", + "5. output your `gameQuestion` and `gameAnswer` to the console `[EX: console.log(gameQuestion + gameAnswer);]`\n", + "\n", + "6. Open your console and see if it displayed the correct message \n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "data": { + "application/javascript": "let favorite-game==school\nlet gameanswer ==favorite-game\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "let favoritegame==school\n", + "let gameanswer" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "source": [ + "\n", + "### Popcorn Hack 2: Null, Undefined, Symbol, in JavaScript \n", + "\n", + "#### Instructions:\n", + "\n", + "1. Open a new cell and set its type to `Code`.\n", + "\n", + "2. Create a variable `nullVar` and set it to `null`.\n", + "\n", + "3. Create a variable `undefinedVar` and leave it uninitialized.\n", + "\n", + "4. Create a variable `symbolVar` and set it to a new Symbol with a description of your choice. `[EX: let myRPG = Symbol(\"Pokemon\");]`\n", + "\n", + "5. Output all three variables to the console using `console.log()`." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_notebooks/booleans/2024-11-12-HomeworkBoolean.ipynb b/_notebooks/booleans/2024-11-12-HomeworkBoolean.ipynb new file mode 100644 index 000000000..246d13e1e --- /dev/null +++ b/_notebooks/booleans/2024-11-12-HomeworkBoolean.ipynb @@ -0,0 +1,60 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "vscode": { + "languageId": "plaintext" + } + }, + "source": [ + "# Popcorn HW Booleans\n", + "Boolean values represent true/false conditions. By creating Boolean variables, you can store these simple \"yes or no\" states and check them as you code.\n", + "\n", + "In this example, you’ll create Boolean variables to represent various conditions and display them using console.log().\n", + "\n", + "Steps:\n", + "Create Boolean Variables: Define some Boolean variables representing different scenarios.\n", + "Display the Variables: Use console.log() to print out each condition along with a message.Make sure after the stament is true or false, there is a dialogue for ex: if level=rihgt, congratulations, you have complete the level and recived the holy grail\n", + "Example Variables\n", + "Here's an expanded list of Boolean variables representing different conditions in daily life:\n", + "\n", + "isQuestcomplete: Is the quest complete?\n", + "\n", + "completedChores: Have you completed all your quest?\n", + "\n", + "LevelCheck: ARe you the right level?\n", + "\n", + "MobCount: Did you kill the right amount of mobs?\n", + "\n", + "ItemCrafting: Do you have the items required to craft this?\n", + "\n", + "isLoggedIn: Are you logged into your account?\n", + "\n", + "GoldCoins: Do you have enough coins?\n", + "isNight: Is it daylight?\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/_posts/Foundation/A-pair_programming/2023-08-16-pair_programming.md b/_posts/Foundation/A-pair_programming/2023-08-16-pair_programming.md index f1e84a6b0..5ec9e887f 100644 --- a/_posts/Foundation/A-pair_programming/2023-08-16-pair_programming.md +++ b/_posts/Foundation/A-pair_programming/2023-08-16-pair_programming.md @@ -1,4 +1,4 @@ ---- +--- layout: post title: Pair Programming description: Pair Programming allows you to have secondary thinking as you work, not just a reflection after you are done, but real-time support. @@ -44,6 +44,6 @@ toc: true - A High "A" is very tough to achieve, something beyond the given requirements. Something that exhibits an unforced desire to learn and Code/Code/Code beyond. A series of these types of grades is required to earn a Teacher recommendation for College. - Low "A" is consistency in producing tangibles toward Team Project and Individual GH Page according to Issues and Scrum Board plans. Plans must be consistent with key objectives and technicals. - "B" is having flaws in consistency or tangible shortcomings, but mostly on track. A flaw would be mostly working code, and attempts, but an incomplete assignment. - - "C" is a lack of consistent effort, lacking tangibles. Lack of producing running Code. + - "C." is a lack of consistent effort, lacking tangibles. Lack of producing running Code. - Below "C" is composed of Slash/Slash/Slash offenses. Lack of attendance, disruptive behaviors, using phone inappropriately, doing work from other classes during CompSci class time, paper visible in class, and turning in "tangibles" that you can't represent in live review. - Zero is a result of plagiarism. The Teachers will likely miss the first few offenses of plagiarism, thus any offense will result in an inquiry on previous work. Remember this is an effort-based class. diff --git a/_sass/minima/custom-styles.scss b/_sass/minima/custom-styles.scss index ac555a85b..260853dac 100644 --- a/_sass/minima/custom-styles.scss +++ b/_sass/minima/custom-styles.scss @@ -6,8 +6,8 @@ //@import "minima/dracula/_dracula"; // Light themes -@import "minima/hamilton/main"; //Hamilton theme -//@import "minima/monophase/main"; //Monophase theme +//@import "minima/hamilton/main"; //Hamilton theme +@import "minima/monophase/main"; //Monophase theme //@import "minima/minimal-mistakes/__minimal-mistakes"; //Minimal Mistakes theme // Mix Light themes with this if your eyes are bleeding @import "minima/dracula/dark-mode"; diff --git a/_sass/minima/dracula/dark-mode.scss b/_sass/minima/dracula/dark-mode.scss index cc48cd24a..46f1d3c75 100644 --- a/_sass/minima/dracula/dark-mode.scss +++ b/_sass/minima/dracula/dark-mode.scss @@ -1,5 +1,5 @@ :root { - --default-canvas-filter: invert(100%); + --default-canvas-filter: invert(0%); } $high-emph: rgba(white, 0.87); diff --git a/_sass/minima/dracula/styles.scss b/_sass/minima/dracula/styles.scss index eb17190ea..b206b403f 100755 --- a/_sass/minima/dracula/styles.scss +++ b/_sass/minima/dracula/styles.scss @@ -181,7 +181,7 @@ color: #d9230f; .search-results-list-item a:hover .search-result-title {text-decoration: underline;} .search-result-rel-date { -color: rgb(109, 120, 138); +color: rgb(6, 89, 223); font-size: 14px; } @@ -241,7 +241,7 @@ white-space: pre-wrap; // /* for mobile phone and tablet devices */ .output_wrapper{ overflow: auto; -} +}/ // } .svg-icon.orange{ @@ -273,4 +273,4 @@ top: 0; left: 0; width: 100%; height: 100%; -} +} \ No newline at end of file diff --git a/_sass/minima/dracula/theme.scss b/_sass/minima/dracula/theme.scss index 4fbda5259..4648ea6f2 100755 --- a/_sass/minima/dracula/theme.scss +++ b/_sass/minima/dracula/theme.scss @@ -2,14 +2,14 @@ // If you wish to override any of this CSS, do so in _sass/minima/custom-styles.css $dt-gray-dark: #282a36; // Background -$dt-code-cell-background: #323443; -$dt-gray: #44475a; // Current Line & Selection -$dt-gray-light: #f8f8f2; // Foreground -$dt-blue: #6272a4; // Comment +$dt-code-cell-background: #c8e61f; +$dt-gray: #445a51; // Current Line & Selection +$dt-gray-light: #f8f2f2; // Foreground +$dt-blue: #62a478; // Comment $dt-cyan: #8be9fd; $dt-green: #50fa7b; $dt-orange: #ffb86c; -$dt-pink: #ff79c6; +$dt-pink: #7b79ff; $dt-purple: #bd93f9; $dt-red: #ff5555; $dt-yellow: #f1fa8c; diff --git a/assets/js/api/config.js b/assets/js/api/config.js new file mode 100644 index 000000000..1373c7768 --- /dev/null +++ b/assets/js/api/config.js @@ -0,0 +1,60 @@ +export var pythonURI; +if (location.hostname === "localhost") { + pythonURI = "http://localhost:8087"; +} else if (location.hostname === "127.0.0.1") { + pythonURI = "http://127.0.0.1:8087"; +} else { + pythonURI = "https://flask2025.nighthawkcodingsociety.com"; +} +export var javaURI; +if (location.hostname === "localhost") { + javaURI = "http://localhost:8085"; +} else if (location.hostname === "127.0.0.1") { + javaURI = "http://127.0.0.1:8085"; //rey +} else { + javaURI = "https://spring.nighthawkcodingsociety.com"; +} + +export const fetchOptions = { + method: 'GET', // *GET, POST, PUT, DELETE, etc. + mode: 'cors', // no-cors, *cors, same-origin + cache: 'default', // *default, no-cache, reload, force-cache, only-if-cached + credentials: 'include', // include, same-origin, omit + headers: { + 'Content-Type': 'application/json', + 'X-Origin': 'client' // New custom header to identify source + }, +}; +// User Login Function +export function login(options) { + // Modify the options to use the POST method and include the request body. + const requestOptions = { + ...fetchOptions, // This will copy all properties from options + method: options.method, // Override the method property + cache: options.cache, // Set the cache property + body: JSON.stringify(options.body) + }; + + // Clear the message area + document.getElementById(options.message).textContent = ""; + + // Fetch JWT + fetch(options.URL, requestOptions) + .then(response => { + // Trap error response from Web API + if (!response.ok) { + const errorMsg = 'Login error: ' + response.status; + console.log(errorMsg); + document.getElementById(options.message).textContent = errorMsg; + return; + } + // Success!!! + // Redirect to the Database location + options.callback(); + }) + .catch(error => { + // Handle network errors + console.log('Possible CORS or Service Down error: ' + error); + document.getElementById(options.message).textContent = 'Possible CORS or service down error: ' + error; + }); +} diff --git a/assets/js/rpg/Background.js b/assets/js/rpg/Background.js new file mode 100644 index 000000000..b663a193d --- /dev/null +++ b/assets/js/rpg/Background.js @@ -0,0 +1,33 @@ +import GameEnv from './GameEnv.js'; + +export class Background { + constructor(imageSrc = null) { + if (imageSrc) { + this.image = new Image(); + this.image.src = imageSrc.src; + } else { + this.image = null; + } + } + + /* To draws are used to capture primary frame and wrap around to next frame + * x to y is primary draw + * x + width to y is wrap around draw + */ + draw() { + const ctx = GameEnv.ctx; + const width = GameEnv.innerWidth; + const height = GameEnv.innerHeight; + + if (this.image) { + // Draw the background image scaled to the canvas size + ctx.drawImage(this.image, 0, 0, width, height); + } else { + // Fill the canvas with white if no background image is provided + ctx.fillStyle = '#87CEEB'; + ctx.fillRect(0, 0, width, height); + } + } +} + +export default Background; diff --git a/assets/js/rpg/GameControl.js b/assets/js/rpg/GameControl.js new file mode 100644 index 000000000..e108346b5 --- /dev/null +++ b/assets/js/rpg/GameControl.js @@ -0,0 +1,46 @@ +import GameEnv from './GameEnv.js'; +import Background from './Background.js'; +import Player from './Player.js'; + +/** + * The GameControl object manages the game. + * + * This code uses the JavaScript "object literal pattern" which is nice for centralizing control logic. + * + * The object literal pattern is a simple way to create singleton objects in JavaScript. + * It allows for easy grouping of related functions and properties, making the code more organized and readable. + * In the context of GameControl, this pattern helps centralize the game's control logic, + * making it easier to manage game states, handle events, and maintain the overall flow of the game. + * + * @type {Object} + * @property {Player} player - The player object. + * @property {function} start - Initialize game assets and start the game loop. + * @property {function} gameLoop - The game loop. + * @property {function} resize - Resize the canvas and player object when the window is resized. + */ +const GameControl = { + + start: function(assets = {}) { + GameEnv.create(); // Create the Game World, this is pre-requisite for all game objects. + this.background = new Background(assets.image || null); + this.player = new Player(assets.sprite || null); + this.gameLoop(); + }, + + gameLoop: function() { + GameEnv.clear(); // Clear the canvas + this.background.draw(); + this.player.update(); + requestAnimationFrame(this.gameLoop.bind(this)); + }, + + resize: function() { + GameEnv.resize(); // Adapts the canvas to the new window size, ie a new Game World. + this.player.resize(); + } +}; + +// Detect window resize events and call the resize function. +window.addEventListener('resize', GameControl.resize.bind(GameControl)); + +export default GameControl; diff --git a/assets/js/rpg/GameEnv.js b/assets/js/rpg/GameEnv.js new file mode 100644 index 000000000..ce6999f81 --- /dev/null +++ b/assets/js/rpg/GameEnv.js @@ -0,0 +1,123 @@ +/** + * GameEnv is a static class that manages the game environment. + * + * The focus of the file is the canvas management and the calculation of the game area dimensions. + * All calculations are based on the window size, header, and footer. + * + * This code uses a classic Java static class pattern, which is nice for managing centralized data. + * + * The static class pattern ensures that there is only one instance of the game environment, + * providing a single point of reference for all game objects. This approach helps maintain + * consistency and simplifies the management of shared resources like the canvas and its dimensions. + * + * @class GameEnv + * @property {Object} canvas - The canvas element. + * @property {Object} ctx - The 2D rendering context of the canvas. + * @property {number} innerWidth - The inner width of the game area. + * @property {number} innerHeight - The inner height of the game area. + * @property {number} top - The top offset of the game area. + * @property {number} bottom - The bottom offset of the game area. + */ +class GameEnv { + static canvas; + static ctx; + static innerWidth; + static innerHeight; + static top; + static bottom; + + /** + * Private constructor to prevent instantiation. + * + * @constructor + * @throws {Error} Throws an error if an attempt is made to instantiate the class. + */ + constructor() { + throw new Error('GameEnv is a static class and cannot be instantiated.'); + } + + /** + * Create the game environment by setting up the canvas and calculating dimensions. + * + * This method sets the canvas element, calculates the top and bottom offsets, + * and determines the inner width and height of the game area. It then sizes the canvas + * to fit within the calculated dimensions. + * + * @static + */ + static create() { + this.setCanvas(); + this.setTop(); + this.setBottom(); + this.innerWidth = window.innerWidth; + this.innerHeight = window.innerHeight - this.top - this.bottom; + this.size(); + } + + /** + * Sets the canvas element and its 2D rendering context. + * + * @static + */ + static setCanvas() { + this.canvas = document.getElementById('gameCanvas'); + this.ctx = this.canvas.getContext('2d'); + } + + /** + * Sets the top offset based on the height of the header element. + * + * @static + */ + static setTop() { + const header = document.querySelector('header'); + this.top = header ? header.offsetHeight : 0; + } + + /** + * Sets the bottom offset based on the height of the footer element. + * + * @static + */ + static setBottom() { + const footer = document.querySelector('footer'); + this.bottom = footer ? footer.offsetHeight : 0; + } + + /** + * Sizes the canvas to fit within the calculated dimensions. + * + * @static + */ + static size() { + this.canvas.width = this.innerWidth; + this.canvas.height = this.innerHeight; + this.canvas.style.width = `${this.innerWidth}px`; + this.canvas.style.height = `${this.innerHeight}px`; + this.canvas.style.position = 'absolute'; + this.canvas.style.left = '0px'; + this.canvas.style.top = `${this.top}px`; + } + + /** + * Resizes the game environment by re-creating it. + * + * @static + */ + static resize() { + this.create(); + } + + /** + * Clears the canvas. + * + * This method clears the entire canvas, making it ready for the next frame. + * + * @static + */ + static clear() { + this.ctx.clearRect(0, 0, this.innerWidth, this.innerHeight); + } +} + +export default GameEnv; diff --git a/assets/js/rpg/Player.js b/assets/js/rpg/Player.js new file mode 100644 index 000000000..cd566681d --- /dev/null +++ b/assets/js/rpg/Player.js @@ -0,0 +1,170 @@ +import GameEnv from './GameEnv.js'; + +// 🚀 Default constants to control the magic +const SCALE_FACTOR = 25; // Player size, 1/nth of canvas height (small but mighty!) +const STEP_FACTOR = 100; // Speed control, player takes 1/nth steps (fast but not too fast) +const ANIMATION_RATE = 1; // Frames per second (FPS) for sprite animations, 'cause smooth is cool + +/** + * Player class brings your character to life! 🕹️ + * Handles all things player-related: state, rendering, movement events, and more. + * Can either be animated with a sprite sheet, or show up as a legendary red square. + * + * @class Player + */ +class Player { + /** + * Sets up your player! Time to play! 🎮 + * @param {Object|null} sprite - Optional sprite data. If null, we rock the red square look. + */ + constructor(sprite = null) { + // Step 1: Get the game environment dimensions + this.scale = { width: GameEnv.innerWidth, height: GameEnv.innerHeight }; + + // Step 2: Set player properties (either from sprite data or default values) + const { SCALE_FACTOR: sf = SCALE_FACTOR, STEP_FACTOR: stf = STEP_FACTOR, ANIMATION_RATE: ar = ANIMATION_RATE } = sprite?.data || {}; + this.scaleFactor = sf; + this.stepFactor = stf; + this.animationRate = ar; + + // Step 3: Load up the sprite sheet (or don’t, and be a red square superstar) + this.spriteSheet = sprite ? this.loadSprite(sprite.src) : null; + this.spriteData = sprite?.data || {}; + this.frameIndex = 0; // Start animation from the first frame + this.frameCounter = 0; // Slow down animation based on rate + this.direction = 'down'; // Player’s starting direction (headin' south, partner! 🤠) + + // Step 4: Size matters! Adjust player size relative to the canvas + this.size = GameEnv.innerHeight / this.scaleFactor; + + // Step 5: Set initial player position and velocity (static until you start moving!) + this.position = { x: 0, y: GameEnv.innerHeight - this.size }; // 🏃‍♂️ Spawn at the bottom left + this.velocity = { x: 0, y: 0 }; // Not moving… *yet* + + // Step 6: Let’s resize our player, and hook up some event listeners (move that player!) + this.resize(); + this.bindEventListeners(); + } + + /** + * Resizes the player when the window size changes. Adapt or perish! 🖼️ + */ + resize() { + const newScale = { width: GameEnv.innerWidth, height: GameEnv.innerHeight }; + + // Resize player position based on old and new scale—stay proportional, no weird stretching! + this.position.x = (this.position.x / this.scale.width) * newScale.width; + this.position.y = (this.position.y / this.scale.height) * newScale.height; + + this.scale = newScale; + + // Time to adjust size and movement based on the new canvas size! + this.size = this.scale.height / this.scaleFactor; // Shrink/grow player relative to height + this.xVelocity = this.scale.width / this.stepFactor; // Player speed on x-axis + this.yVelocity = this.scale.height / this.stepFactor; // Player speed on y-axis + + // Keep the player nice and square-shaped + this.width = this.size; + this.height = this.size; + } + + /** + * Draw the player on the canvas! Will it be a pixel-perfect sprite? Or a fearless red square? 🎨 + */ + draw() { + if (this.spriteSheet) { + // Calculate sprite frame dimensions—each frame is a piece of the puzzle! + const frameWidth = this.spriteData.pixels.width / this.spriteData.orientation.columns; + const frameHeight = this.spriteData.pixels.height / this.spriteData.orientation.rows; + + // Get the right sprite frame based on direction and frame index + const directionData = this.spriteData[this.direction]; + const frameX = (directionData.start + this.frameIndex) * frameWidth; + const frameY = directionData.row * frameHeight; + + // Finally, draw the right frame of the sprite sheet onto the canvas! + GameEnv.ctx.drawImage( + this.spriteSheet, + frameX, frameY, frameWidth, frameHeight, // Which part of the sprite sheet are we grabbing? + this.position.x, this.position.y, this.width, this.height // Where are we putting it? + ); + + // Update the frame index for that sweet animation, but only if it's time to move! + this.frameCounter++; + if (this.frameCounter % this.animationRate === 0) { + this.frameIndex = (this.frameIndex + 1) % directionData.columns; + } + } else { + // No sprite sheet? No problem! You're a stylish red square now! + GameEnv.ctx.fillStyle = 'red'; + GameEnv.ctx.fillRect(this.position.x, this.position.y, this.width, this.height); + } + } + + /** + * Update the player’s position and keep them within the game world (no sneaking off-screen!). 🛑 + */ + update() { + // Step 1: Draw the player in their new spot + this.draw(); + + // Step 2: Move the player based on velocity + this.position.x += this.velocity.x; + this.position.y += this.velocity.y; + + // Step 3: Keep the player inside the canvas bounds (no running off into the void!) + this.position.x = Math.max(0, Math.min(this.position.x, GameEnv.innerWidth - this.width)); + this.position.y = Math.max(0, Math.min(this.position.y, GameEnv.innerHeight - this.height)); + } + + /** + * Bind event listeners to make your player move with arrow keys or WASD. Ready to run? 🏃‍♂️💨 + */ + bindEventListeners() { + addEventListener('keydown', this.handleKeyDown.bind(this)); + addEventListener('keyup', this.handleKeyUp.bind(this)); + } + + /** + * Handle key presses to set the player's velocity. WASD or arrows: Choose your destiny! 🎮 + * @param {Object} event - The keydown event (aka, which button you just pressed) + */ + handleKeyDown({ keyCode }) { + // Velocity settings mapped to WASD/arrow keys + const directions = { + 87: { y: -this.yVelocity, direction: 'up' }, // 'W' key -> Go up! + 65: { x: -this.xVelocity, direction: 'left' }, // 'A' key -> Go left! + 83: { y: this.yVelocity, direction: 'down' }, // 'S' key -> Go down! + 68: { x: this.xVelocity, direction: 'right' }, // 'D' key -> Go right! + }; + + // Update velocity and direction if a valid key is pressed + if (directions[keyCode]) { + this.velocity = { ...this.velocity, ...directions[keyCode] }; + this.direction = directions[keyCode].direction; + } + } + + /** + * Handle key releases to stop the player when you let go of a movement key. 🛑 + * @param {Object} event - The keyup event (aka, which button you just released) + */ + handleKeyUp({ keyCode }) { + // Stop player movement when the corresponding key is released + if ([87, 83].includes(keyCode)) this.velocity.y = 0; // 'W' or 'S' key -> Stop vertical movement + if ([65, 68].includes(keyCode)) this.velocity.x = 0; // 'A' or 'D' key -> Stop horizontal movement + } + + /** + * Helper method to load the sprite sheet for the player. + * @param {string} src - Path to the sprite sheet image + * @returns {HTMLImageElement} Loaded image element + */ + loadSprite(src) { + const img = new Image(); + img.src = src; + return img; + } +} + +export default Player; diff --git a/assets/js/rpg2x/Background.js b/assets/js/rpg2x/Background.js new file mode 100644 index 000000000..990f9baac --- /dev/null +++ b/assets/js/rpg2x/Background.js @@ -0,0 +1,45 @@ +import GameEnv from './GameEnv.js'; + +/* Background class for primary background +*/ +export class Background { + constructor(data = null) { + if (data.src) { + this.image = new Image(); + this.image.src = data.src; + } else { + this.image = null; + } + } + + /* This method draws to GameEnv context, primary background + */ + draw() { + const ctx = GameEnv.ctx; + const width = GameEnv.innerWidth; + const height = GameEnv.innerHeight; + + if (this.image) { + // Draw the background image scaled to the canvas size + ctx.drawImage(this.image, 0, 0, width, height); + } else { + // Fill the canvas with fillstyle color if no image is provided + ctx.fillStyle = '#87CEEB'; + ctx.fillRect(0, 0, width, height); + } + } + + /* For primary background, update is the same as draw + */ + update() { + this.draw(); + } + + /* For primary background, resize is the same as draw + */ + resize() { + this.draw(); + } +} + +export default Background; diff --git a/assets/js/rpg2x/GameControl.js b/assets/js/rpg2x/GameControl.js new file mode 100644 index 000000000..5dc090702 --- /dev/null +++ b/assets/js/rpg2x/GameControl.js @@ -0,0 +1,62 @@ +import GameEnv from './GameEnv.js'; +import GameLevelSquares from './GameLevelSquares.js'; +import GameLevelWater from './GameLevelWater.js'; + +/** + * The GameControl object manages the game. + * + * This code uses the JavaScript "object literal pattern" which is nice for centralizing control logic. + * + * The object literal pattern is a simple way to create singleton objects in JavaScript. + * It allows for easy grouping of related functions and properties, making the code more organized and readable. + * In the context of GameControl, this pattern helps centralize the game's control logic, + * making it easier to manage game states, handle events, and maintain the overall flow of the game. + * + * @type {Object} + * @property {Player} turtle - The player object. + * @property {Player} fish + * @property {function} start - Initialize game assets and start the game loop. + * @property {function} gameLoop - The game loop. + * @property {function} resize - Resize the canvas and player object when the window is resized. + */ +const GameControl = { + + start: function(path) { + // Create the game environment + GameEnv.create(); + // Load the game level + const gameLevel = new GameLevelWater(path); + // Prepare game objects for the level + for (let object of gameLevel.objects) { + if (!object.data) object.data = {}; + GameEnv.gameObjects.push(new object.class(object.data)); + } + // Start the game loop + this.gameLoop(); + }, + + gameLoop: function() { + // Clear the canvas + GameEnv.clear(); + // Update the game objects + for (let object of GameEnv.gameObjects) { + object.update(); // Update the game objects + } + // Recursively call the game loop + requestAnimationFrame(this.gameLoop.bind(this)); + }, + + resize: function() { + // Resize the game environment + GameEnv.resize(); + // Resize the game objects + for (let object of GameEnv.gameObjects) { + object.resize(); // Resize the game objects + } + } +}; + +// Detect window resize events and call the resize function. +window.addEventListener('resize', GameControl.resize.bind(GameControl)); + +export default GameControl; diff --git a/assets/js/rpg2x/GameEnv.js b/assets/js/rpg2x/GameEnv.js new file mode 100644 index 000000000..edd1eab05 --- /dev/null +++ b/assets/js/rpg2x/GameEnv.js @@ -0,0 +1,124 @@ +/** + * GameEnv is a static class that manages the game environment. + * + * The focus of the file is the canvas management and the calculation of the game area dimensions. + * All calculations are based on the window size, header, and footer. + * + * This code uses a classic Java static class pattern, which is nice for managing centralized data. + * + * The static class pattern ensures that there is only one instance of the game environment, + * providing a single point of reference for all game objects. This approach helps maintain + * consistency and simplifies the management of shared resources like the canvas and its dimensions. + * + * @class GameEnv + * @property {Object} canvas - The canvas element. + * @property {Object} ctx - The 2D rendering context of the canvas. + * @property {number} innerWidth - The inner width of the game area. + * @property {number} innerHeight - The inner height of the game area. + * @property {number} top - The top offset of the game area. + * @property {number} bottom - The bottom offset of the game area. + */ +class GameEnv { + static gameObjects = []; + static canvas; + static ctx; + static innerWidth; + static innerHeight; + static top; + static bottom; + + /** + * Private constructor to prevent instantiation. + * + * @constructor + * @throws {Error} Throws an error if an attempt is made to instantiate the class. + */ + constructor() { + throw new Error('GameEnv is a static class and cannot be instantiated.'); + } + + /** + * Create the game environment by setting up the canvas and calculating dimensions. + * + * This method sets the canvas element, calculates the top and bottom offsets, + * and determines the inner width and height of the game area. It then sizes the canvas + * to fit within the calculated dimensions. + * + * @static + */ + static create() { + this.setCanvas(); + this.setTop(); + this.setBottom(); + this.innerWidth = window.innerWidth; + this.innerHeight = window.innerHeight - this.top - this.bottom; + this.size(); + } + + /** + * Sets the canvas element and its 2D rendering context. + * + * @static + */ + static setCanvas() { + this.canvas = document.getElementById('gameCanvas'); + this.ctx = this.canvas.getContext('2d'); + } + + /** + * Sets the top offset based on the height of the header element. + * + * @static + */ + static setTop() { + const header = document.querySelector('header'); + this.top = header ? header.offsetHeight : 0; + } + + /** + * Sets the bottom offset based on the height of the footer element. + * + * @static + */ + static setBottom() { + const footer = document.querySelector('footer'); + this.bottom = footer ? footer.offsetHeight : 0; + } + + /** + * Sizes the canvas to fit within the calculated dimensions. + * + * @static + */ + static size() { + this.canvas.width = this.innerWidth; + this.canvas.height = this.innerHeight; + this.canvas.style.width = `${this.innerWidth}px`; + this.canvas.style.height = `${this.innerHeight}px`; + this.canvas.style.position = 'absolute'; + this.canvas.style.left = '0px'; + this.canvas.style.top = `${this.top}px`; + } + + /** + * Resizes the game environment by re-creating it. + * + * @static + */ + static resize() { + this.create(); + } + + /** + * Clears the canvas. + * + * This method clears the entire canvas, making it ready for the next frame. + * + * @static + */ + static clear() { + this.ctx.clearRect(0, 0, this.innerWidth, this.innerHeight); + } +} + +export default GameEnv; diff --git a/assets/js/rpg2x/GameLevelSquares.js b/assets/js/rpg2x/GameLevelSquares.js new file mode 100644 index 000000000..cdddd5b67 --- /dev/null +++ b/assets/js/rpg2x/GameLevelSquares.js @@ -0,0 +1,17 @@ +// To build GameLevels, each contains GameObjects from below imports +import Background from './Background.js'; +import PlayerOne from './PlayerOne.js'; +import PlayerTwo from './PlayerTwo.js'; + +// Minimal Definition +class GameLevelSquares { + constructor(path) { + this.objects = [ + { class: Background, data: {} }, + { class: PlayerOne }, + { class: PlayerTwo }, + ]; + } +} + +export default GameLevelSquares; diff --git a/assets/js/rpg2x/GameLevelWater.js b/assets/js/rpg2x/GameLevelWater.js new file mode 100644 index 000000000..f5aedab11 --- /dev/null +++ b/assets/js/rpg2x/GameLevelWater.js @@ -0,0 +1,87 @@ +// To build GameLevels, each contains GameObjects from below imports +import GameEnv from './GameEnv.js'; +import Background from './Background.js'; +import PlayerOne from './PlayerOne.js'; +import PlayerTwo from './PlayerTwo.js'; +import NPC from './NPC.js'; +//import Goomba from './EnemyGoomba.js'; +//import Coin from './Coin.js'; + + +class GameLevelWater { + constructor(path) { + const header = document.querySelector('header'); + const footer = document.querySelector('footer'); + + // Values dependent on GameEnv.create() + let width = GameEnv.innerWidth; + let height = GameEnv.innerHeight; + + // Background data + const image_src_water = path + "/images/rpg/cloud.jpg"; + const image_data_water = { + name: 'water', + src: image_src_water, + pixels: {height: 580, width: 1038} + }; + + // Player 1 sprite data (turtle) + const TURTLE_SCALE_FACTOR = 10; + const sprite_src_turtle = path + "/images/rpg/rightnowman.png"; + const sprite_data_turtle = { + name: 'turtle', + src: sprite_src_turtle, + SCALE_FACTOR: TURTLE_SCALE_FACTOR, + STEP_FACTOR: 1000, + ANIMATION_RATE: 50, + INIT_POSITION: { x: 0, y: height - (height/TURTLE_SCALE_FACTOR) }, + pixels: {height: 183, width: 275}, + orientation: {rows: 4, columns: 6 }, + down: {row: 0, start: 0, columns: 6 }, + left: {row: 1, start: 0, columns: 6 }, + right: {row: 2, start: 0, columns: 6 }, + up: {row: 3, start: 0, columns: 6 }, + }; + + // Player 2 sprite data (fish) + const sprite_src_fish = path + "/images/rpg/fishies.png"; + const sprite_data_fish = { + name: 'fish', + src: sprite_src_fish, + SCALE_FACTOR: 16, + STEP_FACTOR: 400, + ANIMATION_RATE: 50, + pixels: {height: 256, width: 384}, + INIT_POSITION: { x: 0, y: 0 }, + orientation: {rows: 8, columns: 12 }, + down: {row: 0, start: 0, columns: 3 }, // 1st row + left: {row: 1, start: 0, columns: 3 }, // 2nd row + right: {row: 2, start: 0, columns: 3 }, // 3rd row + up: {row: 3, start: 0, columns: 3 }, // 4th row + }; + + // NPC sprite data (frog) + const sprite_src_frog = path + "/images/rpg/fishies.png"; + const sprite_data_frog = { + name: 'npc', + src: sprite_src_frog, + SCALE_FACTOR: 16, // Adjust this based on your scaling needs + ANIMATION_RATE: 50, + pixels: {height: 256, width: 384}, + INIT_POSITION: { x: (width / 2), y: (height / 2)}, + orientation: {rows: 8, columns: 12 }, + down: {row: 0, start: 9, columns: 3 }, // This is the stationary npc, down is default + }; + + // List of objects defnitions for this level + this.objects = [ + { class: Background, data: image_data_water }, + { class: PlayerOne, data: sprite_data_turtle }, + { class: PlayerTwo, data: sprite_data_fish }, + { class: NPC, data: sprite_data_frog } + ]; + } + +} + +export default GameLevelWater; diff --git a/assets/js/rpg2x/GameObject.js b/assets/js/rpg2x/GameObject.js new file mode 100644 index 000000000..a95f0b97f --- /dev/null +++ b/assets/js/rpg2x/GameObject.js @@ -0,0 +1,139 @@ +import GameEnv from './GameEnv.js'; +import Socket from './Multiplayer.js'; + +class GameObject { + // container for all game objects in game + constructor(canvas, image, data) { + this.canvas = canvas; + this.ctx = canvas.getContext('2d'); + this.x = 0; + this.y = 0; + this.frame = 0; + this.image = image; + this.width = image.width; // from Image() width + this.height = image.height; // from Image() height + this.collisionWidth = 0; + this.collisionHeight = 0; + this.aspect_ratio = this.width / this.height; + this.collisionData = {}; + this.hitbox = data?.hitbox || {}; + // Add this object to the game object array so collision can be detected + // among other things + GameEnv.gameObjects.push(this); + } + + setX(x) { + if (x < 0) { + x = 0; + } + this.x = x; + } + + setY(y) { + if (y < GameEnv.top) { + y = GameEnv.top; + } + if (y > GameEnv.bottom) { + y = GameEnv.bottom; + } + this.y = y; + } + + /* Destroy Game Object + * remove canvas element of object + * remove object from GameObject array + */ + destroy() { + const index = GameEnv.gameObjects.indexOf(this); + if (index !== -1) { + // Remove the canvas from the DOM + this.canvas.parentNode.removeChild(this.canvas); + GameEnv.gameObjects.splice(index, 1); + } + } + + /* Default collision action is no action + * override when you extend for custom action + */ + collisionAction(){ + // no action + } + + /* Collision checks + * uses GameObject isCollision to detect hit + * calls collisionAction on hit + */ + collisionChecks() { + for (var gameObj of GameEnv.gameObjects){ + if (this != gameObj ) { + this.isCollision(gameObj); + if (this.collisionData.hit){ + this.collisionAction(); + } + } + } + } + + /* Collision detection method + * usage: if (player.isCollision(platform)) { // action } + */ + isCollision(other) { + // Bounding rectangles from Canvas + const thisRect = this.canvas.getBoundingClientRect(); + const otherRect = other.canvas.getBoundingClientRect(); + + // Calculate center points of rectangles + const thisCenterX = (thisRect.left + thisRect.right) / 2; + const otherCenterX = (otherRect.left + otherRect.right) / 2; + + // Calculate new center points of rectangles + const thisRectWidth = thisRect.right - thisRect.left; + const thisRectLeftNew = otherCenterX - thisRectWidth / 2; + + // Calculate hitbox constants + var widthPercentage = this.hitbox?.widthPercentage || 0.0; + var heightPercentage = this.hitbox?.heightPercentage || 0.0; + + // Calculate hitbox reductions from the width and height + const widthReduction = thisRect.width * widthPercentage; + const heightReduction = thisRect.height * heightPercentage; + + // Build hitbox by subtracting reductions from the left, right, top, and bottom + const thisLeft = thisRect.left + widthReduction; + const thisTop = thisRect.top + heightReduction; + const thisRight = thisRect.right - widthReduction; + const thisBottom = thisRect.bottom; + const tolerance = 10; // Adjust as needed + + // Determine hit and touch points of hit + this.collisionData = { + hit: ( + thisLeft < otherRect.right && + thisRight > otherRect.left && + thisTop < otherRect.bottom && + thisBottom > otherRect.top + ), + touchPoints: { + this: { + id: this.canvas.id, + top: thisRect.bottom > otherRect.top, + bottom: (thisRect.bottom <= otherRect.top) && !(Math.abs(thisRect.bottom - otherRect.bottom) <= GameEnv.gravity), + left: thisCenterX > otherCenterX, + right: thisCenterX < otherCenterX, + onTopofOther: onTopofOther + }, + other: { + id: other.canvas.id, + top: thisRect.bottom < otherRect.top, + bottom: (thisRect.bottom >= otherRect.top) && !(Math.abs(thisRect.bottom - otherRect.bottom) <= GameEnv.gravity), + left: thisCenterX < otherCenterX, + right: thisCenterX > otherCenterX, + }, + }, + }; + + } + +} + +export default GameObject; diff --git a/assets/js/rpg2x/NPC.js b/assets/js/rpg2x/NPC.js new file mode 100644 index 000000000..a97fe88eb --- /dev/null +++ b/assets/js/rpg2x/NPC.js @@ -0,0 +1,130 @@ +import Player from "./Player.js"; +import GameEnv from "./GameEnv.js"; + +class NPC extends Player { + constructor(data = null) { + super(data); + this.alertTimeout = null; + } + + /** + * Override the update method to draw the NPC. + * This NPC is stationary, so the update method only calls the draw method. + * + * @override + */ + update() { + this.draw(); + } + + /** + * Handles keydown events for proximity interaction. + * This method is triggered when a key is pressed and checks for proximity interactions. + * + * @param {Object} event - The event object containing the key that was pressed. + * @param {string} event.key - The key that was pressed. + * + * Keys handled: + * - 'e': Proximity interaction for Player 1 + * - 'u': Proximity interaction for Player 2 + * + * This method calls checkProximityToNPC() if either 'e' or 'u' is pressed. + */ + handleKeyDown({ key }) { + switch (key) { + case 'e': // Player 1 + case 'u': // Player 2 + this.checkProximityToNPC(); + break; + } + } + + /** + * Handles key up events to stop the player's velocity. + * + * This method stops the player's velocity based on the key released. + * It also clears the alert timeout if the 'e' or 'u' key is released. + * + * @param {Object} event - The keyup event object. + * @param {string} event.key - The key that was released. + */ + handleKeyUp({ key }) { + // Check if the released key is 'e' or 'u' + if (key === 'e' || key === 'u') { + // Clear the alert timeout to cancel the alert + if (this.alertTimeout) { + clearTimeout(this.alertTimeout); + this.alertTimeout = null; + closeCustomAlert(); + } + } + } + + /** + * Custom alert mechanism to handle responses. + * + * @param {string} message - The message to be displayed in the alert. + */ + handleResponse(message) { + // Clear any existing alert timeout + if (this.alertTimeout) { + clearTimeout(this.alertTimeout); + } + + // Set a new alert timeout + this.alertTimeout = setTimeout(() => { + showCustomAlert(message); + }, 0); + } + + /** + * Check for proximity of objects. + * This method checks if any players are within a certain distance of the NPC. + * If players are within the specified distance, their names are collected and a response is generated. + */ + checkProximityToNPC() { + // Filter all Player objects from the game environment + var players = GameEnv.gameObjects.filter(obj => obj instanceof Player); + var npc = this; + var names = []; + + if (players.length > 0 && npc) { + players.forEach(player => { + // The Euclidean distance between two points in a 2D space + var distance = Math.sqrt( + Math.pow(player.position.x - npc.position.x, 2) + Math.pow(player.position.y - npc.position.y, 2) + ); + // The distance is less than 1000 pixels + if (player != npc && distance <= 1000) { + names.push(player.spriteData.name); + } + }); + // Join all player names inside the proximity + if (names.length > 0) { + this.handleResponse(`wuts-good, ${names.join(', ')}`); + } + } + } +} + +export default NPC; + +/** + * Show the custom alert with the given message. + * + * @param {string} message - The message to be displayed in the alert. + */ +function showCustomAlert(message) { + const alertBox = document.getElementById('custom-alert'); + const alertMessage = document.getElementById('custom-alert-message'); + alertMessage.textContent = message; + alertBox.style.display = 'block'; +} + +/** + * Close the custom alert. + */ +function closeCustomAlert() { + const alertBox = document.getElementById('custom-alert'); + alertBox.style.display = 'none'; +} diff --git a/assets/js/rpg2x/Player.js b/assets/js/rpg2x/Player.js new file mode 100644 index 000000000..f182d12b9 --- /dev/null +++ b/assets/js/rpg2x/Player.js @@ -0,0 +1,232 @@ +import GameEnv from './GameEnv.js'; + +// Define non-mutable constants as defaults +const SCALE_FACTOR = 25; // 1/nth of the height of the canvas +const STEP_FACTOR = 100; // 1/nth, or N steps up and across the canvas +const ANIMATION_RATE = 1; // 1/nth of the frame rate +const INIT_POSITION = { x: 0, y: 0 }; + +/** + * Player is a dynamic class that manages the data and events for a player object. + * + * The focus of this class is to handle the player's state, rendering, and key events. + * + * This class uses a classic Java class pattern which is nice for managing object data and events. + * + * The classic Java class pattern provides a structured way to define the properties and methods + * associated with the player. This approach helps encapsulate the player's state and behavior, + * making the code more modular and easier to maintain. By using this pattern, we can create + * multiple instances of the Player class, each with its own state and behavior. + * + * @abstract Player + * @property {Object} position - The current position of the player. + * @property {Object} velocity - The current velocity of the player. + * @property {Object} scale - The scale of the player based on the game environment. + * @property {number} size - The size of the player. + * @property {number} width - The width of the player. + * @property {number} height - The height of the player. + * @property {number} xVelocity - The velocity of the player along the x-axis. + * @property {number} yVelocity - The velocity of the player along the y-axis. + * @property {Image} spriteSheet - The sprite sheet image for the player. + * @property {number} frameIndex - The current frame index for animation. + * @property {number} frameCount - The total number of frames for each direction. + * @property {Object} spriteData - The data for the sprite sheet. + * @property {number} frameCounter - Counter to control the animation rate. + * @method resize - Resizes the player based on the game environment. + * @method draw - Draws the player on the canvas. + * @method update - Updates the player's position and ensures it stays within the canvas boundaries. + * @method bindEventListeners - Binds key event listeners to handle player movement. + * @method handleKeyDown - Handles key down events to change the player's velocity. + * @method handleKeyUp - Handles key up events to stop the player's velocity. + */ +class Player { + /** + * The constructor method is called when a new Player object is created. + * + * @param {Object|null} data - The sprite data for the player. If null, a default red square is used. + */ + constructor(data = null) { + // Initialize the player's scale based on the game environment + this.scale = { width: GameEnv.innerWidth, height: GameEnv.innerHeight }; + + // Check if sprite data is provided + if (data && data.src) { + this.scaleFactor = data.SCALE_FACTOR || SCALE_FACTOR; + this.stepFactor = data.STEP_FACTOR || STEP_FACTOR; + this.animationRate = data.ANIMATION_RATE || ANIMATION_RATE; + this.position = data.INIT_POSITION || INIT_POSITION; + + // Load the sprite sheet + this.spriteSheet = new Image(); + this.spriteSheet.src = data.src; + + // Initialize animation properties + this.frameIndex = 0; // index reference to current frame + this.frameCounter = 0; // count each frame rate refresh + this.direction = 'down'; // Initial direction + this.spriteData = data; + } else { + // Default to red square + this.scaleFactor = SCALE_FACTOR; + this.stepFactor = STEP_FACTOR; + this.animationRate = ANIMATION_RATE; + this.position = INIT_POSITION; + + // No sprite sheet for default + this.spriteSheet = null; + } + + // Initialize the player's position and velocity + this.velocity = { x: 0, y: 0 }; + + // Set the initial size and velocity of the player + this.resize(); + + // Bind event listeners to allow object movement + this.bindEventListeners(); + } + + /** + * Resizes the player based on the game environment. + * + * This method adjusts the player's size and velocity based on the scale of the game environment. + * It also adjusts the player's position proportionally based on the previous and current scale. + */ + resize() { + // Calculate the new scale resulting from the window resize + const newScale = { width: GameEnv.innerWidth, height: GameEnv.innerHeight }; + + // Adjust the player's position proportionally + this.position.x = (this.position.x / this.scale.width) * newScale.width; + this.position.y = (this.position.y / this.scale.height) * newScale.height; + + // Update the player's scale to the new scale + this.scale = newScale; + + // Recalculate the player's size based on the new scale + this.size = this.scale.height / this.scaleFactor; + + // Recalculate the player's velocity steps based on the new scale + this.xVelocity = this.scale.width / this.stepFactor; + this.yVelocity = this.scale.height / this.stepFactor; + + // Set the player's width and height to the new size (object is a square) + this.width = this.size; + this.height = this.size; + } + + /** + * Draws the player on the canvas. + * + * This method renders the player using the sprite sheet if provided, otherwise a red square. + */ + draw() { + if (this.spriteSheet) { + // Sprite Sheet frame size: pixels = total pixels / total frames + const frameWidth = this.spriteData.pixels.width / this.spriteData.orientation.columns; + const frameHeight = this.spriteData.pixels.height / this.spriteData.orientation.rows; + + // Sprite Sheet direction data source (e.g., front, left, right, back) + const directionData = this.spriteData[this.direction]; + + // Sprite Sheet x and y declarations to store coordinates of current frame + let frameX, frameY; + // Sprite Sheet x and y current frame: coordinate = (index) * (pixels) + frameX = (directionData.start + this.frameIndex) * frameWidth; + frameY = directionData.row * frameHeight; + + // Draw the current frame of the sprite sheet + GameEnv.ctx.drawImage( + this.spriteSheet, + frameX, frameY, frameWidth, frameHeight, // Source rectangle + this.position.x, this.position.y, this.width, this.height // Destination rectangle + ); + + // Update the frame index for animation at a slower rate + this.frameCounter++; + if (this.frameCounter % this.animationRate === 0) { + this.frameIndex = (this.frameIndex + 1) % directionData.columns; + } + } else { + // Draw default red square + GameEnv.ctx.fillStyle = 'red'; + GameEnv.ctx.fillRect(this.position.x, this.position.y, this.width, this.height); + } + } + + /** + * Updates the player's position and ensures it stays within the canvas boundaries. + * + * This method updates the player's position based on its velocity and ensures that the player + * stays within the boundaries of the canvas. + */ + update() { + // Update begins by drawing the player object + this.draw(); + + // Update or change position according to velocity events + this.position.x += this.velocity.x; + this.position.y += this.velocity.y; + + // Ensure the player stays within the canvas boundaries + // Bottom of the canvas + if (this.position.y + this.height > GameEnv.innerHeight) { + this.position.y = GameEnv.innerHeight - this.height; + this.velocity.y = 0; + } + // Top of the canvas + if (this.position.y < 0) { + this.position.y = 0; + this.velocity.y = 0; + } + // Right of the canvas + if (this.position.x + this.width > GameEnv.innerWidth) { + this.position.x = GameEnv.innerWidth - this.width; + this.velocity.x = 0; + } + // Left of the canvas + if (this.position.x < 0) { + this.position.x = 0; + this.velocity.x = 0; + } + } + + /** + * Binds key event listeners to handle player movement. + * + * This method binds keydown and keyup event listeners to handle player movement. + * The .bind(this) method ensures that 'this' refers to the player object. + */ + bindEventListeners() { + addEventListener('keydown', this.handleKeyDown.bind(this)); + addEventListener('keyup', this.handleKeyUp.bind(this)); + } + + /** + * Handles key down events to change the player's velocity. + * + * This method updates the player's velocity based on the key pressed. + * + * @param {Object} event - The keydown event object. + * @abstract + */ + handleKeyDown({ keyCode }) { + throw new Error('Method "handleKeyDown()" must be implemented'); + } + + /** + * Handles key up events to stop the player's velocity. + * + * This method stops the player's velocity based on the key released. + * + * @param {Object} event - The keyup event object. + * @abstract + */ + handleKeyUp({ keyCode }) { + throw new Error('Method "handleKeyUp()" must be implemented'); + } + + +} + +export default Player; diff --git a/assets/js/rpg2x/PlayerOne.js b/assets/js/rpg2x/PlayerOne.js new file mode 100644 index 000000000..2a0e80ccf --- /dev/null +++ b/assets/js/rpg2x/PlayerOne.js @@ -0,0 +1,55 @@ +import Player from './Player.js'; + +class PlayerOne extends Player { + constructor(data = null) { + super(data); + } + + handleKeyDown({ keyCode }) { + switch (keyCode) { + case 87: // 'W' key + this.velocity.y -= this.yVelocity; + this.direction = 'up'; + break; + case 65: // 'A' key + this.velocity.x -= this.xVelocity; + this.direction = 'left'; + break; + case 83: // 'S' key + this.velocity.y += this.yVelocity; + this.direction = 'down'; + break; + case 68: // 'D' key + this.velocity.x += this.xVelocity; + this.direction = 'right'; + break; + } + } + + /** + * Handles key up events to stop the player's velocity. + * + * This method stops the player's velocity based on the key released. + * + * @param {Object} event - The keyup event object. + */ + handleKeyUp({ keyCode }) { + switch (keyCode) { + case 87: // 'W' key + this.velocity.y = 0; + break; + case 65: // 'A' key + this.velocity.x = 0; + break; + case 83: // 'S' key + this.velocity.y = 0; + break; + case 68: // 'D' key + this.velocity.x = 0; + break; + } + } + +} + +export default PlayerOne; diff --git a/assets/js/rpg2x/PlayerTwo.js b/assets/js/rpg2x/PlayerTwo.js new file mode 100644 index 000000000..5f54b0a99 --- /dev/null +++ b/assets/js/rpg2x/PlayerTwo.js @@ -0,0 +1,48 @@ +import Player from "./Player.js"; + +class PlayerTwo extends Player { + constructor(imageSrc = null) { + super(imageSrc); + } + + handleKeyDown({ keyCode }) { + switch (keyCode) { + case 73: // 'I' key + this.velocity.y -= this.yVelocity; + this.direction = 'up'; + break; + case 74: // 'J' key + this.velocity.x -= this.xVelocity; + this.direction = 'left'; + break; + case 75: // 'K' key + this.velocity.y += this.yVelocity; + this.direction = 'down'; + break; + case 76: // 'L' key + this.velocity.x += this.xVelocity; + this.direction = 'right'; + break; + } + } + + handleKeyUp({ keyCode }) { + switch (keyCode) { + case 73: // 'I' key + this.velocity.y = 0; + break; + case 74: // 'J' key + this.velocity.x = 0; + break; + case 75: // 'K' key + this.velocity.y = 0; + break; + case 76: // 'L' key + this.velocity.x = 0; + break; + } + } + +} + +export default PlayerTwo; diff --git a/images/mario_animation.png b/images/mario_animation.png new file mode 100644 index 000000000..9d5c469c6 Binary files /dev/null and b/images/mario_animation.png differ diff --git a/images/rpg/248259.png b/images/rpg/248259.png new file mode 100644 index 000000000..c0ac10ba5 Binary files /dev/null and b/images/rpg/248259.png differ diff --git a/images/rpg/360_F_580780653_anlTL1Gq6IZRyanXjxsiMeUbEScXoqC7.jpg b/images/rpg/360_F_580780653_anlTL1Gq6IZRyanXjxsiMeUbEScXoqC7.jpg new file mode 100644 index 000000000..893ce8aae Binary files /dev/null and b/images/rpg/360_F_580780653_anlTL1Gq6IZRyanXjxsiMeUbEScXoqC7.jpg differ diff --git a/images/rpg/8-bits-characters-gaming-assets_23-2151143769.jpg b/images/rpg/8-bits-characters-gaming-assets_23-2151143769.jpg new file mode 100644 index 000000000..ef9dbf4d0 Binary files /dev/null and b/images/rpg/8-bits-characters-gaming-assets_23-2151143769.jpg differ diff --git a/images/rpg/Free-Ninja-Sprite-Sheets-Pixel-Art2.jpg b/images/rpg/Free-Ninja-Sprite-Sheets-Pixel-Art2.jpg new file mode 100644 index 000000000..c6b7da623 Binary files /dev/null and b/images/rpg/Free-Ninja-Sprite-Sheets-Pixel-Art2.jpg differ diff --git a/images/rpg/Run.png b/images/rpg/Run.png new file mode 100644 index 000000000..7d713ea9a Binary files /dev/null and b/images/rpg/Run.png differ diff --git a/images/rpg/cloud.jpg b/images/rpg/cloud.jpg new file mode 100644 index 000000000..0bc26079d Binary files /dev/null and b/images/rpg/cloud.jpg differ diff --git a/images/rpg/coolman.png b/images/rpg/coolman.png new file mode 100644 index 000000000..db90acdbf Binary files /dev/null and b/images/rpg/coolman.png differ diff --git a/images/rpg/craftpix-net-123681-free-samurai-pixel-art-sprite-sheets.jpg b/images/rpg/craftpix-net-123681-free-samurai-pixel-art-sprite-sheets.jpg new file mode 100644 index 000000000..0bdacf81a Binary files /dev/null and b/images/rpg/craftpix-net-123681-free-samurai-pixel-art-sprite-sheets.jpg differ diff --git a/images/rpg/fire.jpg b/images/rpg/fire.jpg new file mode 100644 index 000000000..51e04a8c1 Binary files /dev/null and b/images/rpg/fire.jpg differ diff --git a/images/rpg/fishies (1).png b/images/rpg/fishies (1).png new file mode 100644 index 000000000..54412df36 Binary files /dev/null and b/images/rpg/fishies (1).png differ diff --git a/images/rpg/fishies.png b/images/rpg/fishies.png new file mode 100644 index 000000000..54412df36 Binary files /dev/null and b/images/rpg/fishies.png differ diff --git a/images/rpg/good.jpg b/images/rpg/good.jpg new file mode 100644 index 000000000..c6617dd2b Binary files /dev/null and b/images/rpg/good.jpg differ diff --git a/images/rpg/ninja.png b/images/rpg/ninja.png new file mode 100644 index 000000000..73a0a3e24 Binary files /dev/null and b/images/rpg/ninja.png differ diff --git a/images/rpg/rightnowman.png b/images/rpg/rightnowman.png new file mode 100644 index 000000000..558082e94 Binary files /dev/null and b/images/rpg/rightnowman.png differ diff --git a/images/rpg/turtle.png b/images/rpg/turtle.png new file mode 100644 index 000000000..9dc5aa8d7 Binary files /dev/null and b/images/rpg/turtle.png differ diff --git a/images/rpg/water.png b/images/rpg/water.png new file mode 100644 index 000000000..af532c801 Binary files /dev/null and b/images/rpg/water.png differ diff --git a/index.md b/index.md index c5006b98c..91757aadb 100644 --- a/index.md +++ b/index.md @@ -1,8 +1,121 @@ --- layout: base -title: Student Home -description: Home Page -hide: true +title: Amalś Github site +description: My index +author: Amal Jinan +image: /images/turtle.png +hide: false --- -My journey starts here. + + + +{% include nav/home.html %} + +{% assign sprite_file = site.baseurl | append: page.image %} + +{% assign hash = site.data.mario_metadata %} + +{% assign pixels = 256 %} + + + +## Investing in Your Technical Futures + +> CSSE 1,2 prepares students for the AP Computer Science pathway. This course focuses on teaching the JavaScript programming language, object-oriented programming and inheritance, and developing algorithmic thinking skills. Through game development projects, students will engage in engineering skills, learn fundamentals of programming, work with data structures, and foster collaboration skills with their peers. Tech talks will be conducted by teachers to introduce concepts, provide guidance on tools, and support ideas to establish development requirements. By performing development and exploration, this course aims to raise students' awareness of the tremendous capabilities of computers and software engineering skills across various fields. + +#### Home page Hack +blogs hack + +> Here is my progress through game coding, click to see these online + + + + + +
+ +### College Articulation + +> Here is my preparation for college topics, click to review my blogs +
+ +
+ Loops Hack +
+
+
+ +
+ Classes +
+
+ + + +
+ diff --git a/navigation/Home-Page.md b/navigation/Home-Page.md new file mode 100644 index 000000000..ac7525a2e --- /dev/null +++ b/navigation/Home-Page.md @@ -0,0 +1,35 @@ +--- +layout: base +title: home page +permalink: /home/ +--- + + + + + + + Go Home Button + + + +
Home
+ + + + diff --git a/navigation/about.md b/navigation/about.md index a8d98630a..9c17ecfb7 100644 --- a/navigation/about.md +++ b/navigation/about.md @@ -1,7 +1,144 @@ --- -layout: page -title: About -permalink: /about/ +layout: base +title: About Me +description: Information about Amal Jinan +author: Amal Jinan +image: /images/mario_animation.png +hide: false --- -Creator of Student 2025 +## Investing in Your Technical Futures + +> CSSE 1,2 prepares students for the AP Computer Science pathway... + +## About Me - CSSE + +> Class of 2028 + +## About Me +**Amal Jinan, Class of 2028** + +- Lived in: + - San Diego + - Silicon Valley + - Canada +- Has attended about 6 different schools, 1 sibling +- Hobbies: + - Soccer + - Reading + - Videogaming + ## TRAITS + LOYALTY + HONESTY + CURIOSITY + ## Achievments + + + + + ![image](https://github.com/user-attachments/assets/3f69d0e0-44e6-4c32-8d22-dbeac0c359d3) + + Built one of the most succesful search engines in the world + + + + + + + ![image](https://github.com/user-attachments/assets/7a466fa1-5494-4fe9-a620-d70aed9bb569) + + Extensive Islamic Knowledge + + + + + + + + ![image](https://github.com/user-attachments/assets/e54a18f1-7ebc-44b8-9ac1-aabd001d8964)6 + 3rd in Spanda spelling bee 2016 + + +Screen Shot 2024-09-23 at 10 39 25 PM + + + Over 70+ games in Scratch + 600+followers + + + + + + + + + +Screen Shot 2024-09-23 at 10 34 31 PM + + Vice President of Oak Valley Coding Club + Knows a deep level of Python + + + + + ## Role Models + + +![image](https://github.com/user-attachments/assets/1662b9a3-1a02-4045-98ff-128067667f46) + + Extensive Research into Astrophysics + + + + +![image1](https://github.com/user-attachments/assets/8e7e0410-0850-4c60-ad49-dcbdbdcdb64e) +![image2](https://github.com/user-attachments/assets/fe63f52c-9044-4e0d-ba56-3dd01eb2e307) +![image3](https://github.com/user-attachments/assets/04037765-8b57-449f-91bf-08ca64c67c22) + + + + + + + + + + Horizontal Scroll + + + +
+ Image 1 + Image 2 + Image 3 +
+ + +# remote_theme: pages-themes/midnight@v0.2.0 +#remote_theme: pages-themes/cayman@v0.2.0 +remote_theme: pages-themes/dinky@v0.2.0 +# remote_theme: pages-themes/time-machine@v0.2.0 +# remote_theme: pages-themes/architect@v0.2.0 + +plugins: + - jekyll-remote-theme + + + + diff --git a/navigation/blog.md b/navigation/blog.md deleted file mode 100644 index 0ce56306d..000000000 --- a/navigation/blog.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -layout: blogs -title: Blogs -search_exclude: true -permalink: /blogs/ ---- diff --git a/navigation/blogs.md b/navigation/blogs.md new file mode 100644 index 000000000..6969dcad0 --- /dev/null +++ b/navigation/blogs.md @@ -0,0 +1,173 @@ +--- +layout: base +title: Blogs/Hack +description: Blogs +author: Amal Jinan +hide: false +--- + + + + + + +

Click the button to play and pause the audio.

+ + + + + +

ESSENTIALS OF DEVELOPMENT TOOLS

+

ACTIVATE TOOLS SETUP TUTORIAL

+

+Understanding and utilizing the right development tools is crucial for a successful coding journey. This section highlights the core components and additional tools that will enhance your learning experience and collaboration.

+ +Laptop Requirement: Ensure you have a laptop with development tools installed. MacOS and Windows are preferred. Chromebooks are supported by using a KASM cloud workspace.
+Version Control: GitHub will store your coding projects and serve as a collaboration hub with others.
+Code Editor: This course will use Visual Studio Code for its extensive support for programming languages and helpful coding features. +Interactive Coding: In this course, coding will be interactive and instantaneous. Visual Studio Code, with support for Jupyter Notebooks and GitHub Pages, is ideal for coding, data analysis, capturing notes, and creating documentation.
+Web Hosting: Throughout this course, students and teachers will publish their projects and notes using GitHub pages. Students will showcase their projects and chronicle their development journey.
+ +

Install Developer Tools

+cd
+mkdir nighthawk
+cd nighthawk
+git clone https://github.com/nighthawkcoders/portfolio_2025.git
+cd
+make a clone of your student repository
+# move to project directory
+cd student_2025
+ +

# make virtual environment by script

+scripts/venv.sh
+ +

# activate virtual environment, observe prompt change after running it

+source venv/bin/activate + +

# install python packages for project

+pip install -r requirements.txt
+ +

# show Kernels, python3 needs must be in the list

+jupyter kernelspec list
+ +

# install gems (Ruby packages), required for Jekyll requirements in GitHub Pages

+bundle install
+ +

# open VSCode

+type code .
+

# Most tools have been pre-installed. Run shell command to automatically finish tool setup.

+ +cd
+cd nighthawk/portfolio_2025/scripts
+ +./activate.sh
+ +

Git identification

+ + Setup personal GitHub variables: Change youremail@gmail.com and yourGHID to match your credentials. This is required prior to syncing code to GitHub. These configurations ensure that your commits are associated with your GitHub account, which is important for tracking contributions and collaboration.
+ +Set your email address: This email should be the same one associated with your GitHub account.
+ +git config --global user.email youremail@gmail.com
+ +Set your GitHub user.name: This should be your GitHub ID.
+ +git config --global user.name yourGHID
+ +After running these commands, you can verify the configurations by running:
+ +git config --global --list
+

+

Files in Project

+ +

+ + + + +

Integration Issue

+

RPG EXAMPLE CODE

+

+ + Scale Factor - It defines the player size and the height and width and also defies the canvas height
+ + + Step Factor-Speed control, player takes 1/nth steps (fast but not too fast)
+ + + const ANIMATION_RATE- Frames per second (FPS) for sprite animations, 'cause smooth is cool
+

+

Player.js Explanation

+ +

+ + + +

+ Step 1: Get the game environment dimensions
+ + Step 2: Set player properties (either from sprite data or default values)
+ + + Step 3: Load up the sprite sheet (or don’t, and be a red square superstar)
+

Sample Turtle Sprite sheet


+ + + + Step 4: Size matters! Adjust player size relative to the canvas
+ EX: this.size = GameEnv.innerHeight / this.scaleFactor;
+ + + + Step 5: Set initial player position and velocity (static until you start moving!)
+ EX: this.position = { x: 0, y: GameEnv.innerHeight - this.size }; // 🏃‍♂️ Spawn at the bottom left + this.velocity = { x: 0, y: 0 }; // Not moving… *yet*
+ + + + Step 6: Let’s resize our player, and hook up some event listeners (move that player!)
+ resize()
+ Resizes the player when the window size changes. Adapt or perish!
+ bindEventListeners()
+ + +

+

+ Personalization +

+

+ Screen Shot 2024-10-06 at 7 00 08 PM + +

+ + + + diff --git a/navigation/calculator.md b/navigation/calculator.md new file mode 100644 index 000000000..9f841202c --- /dev/null +++ b/navigation/calculator.md @@ -0,0 +1,232 @@ +--- +layout: base +title: calculator +permalink: /calculator/ +--- + + + + + + Advanced Calculator + + + +
+
0
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + diff --git a/navigation/codenite.md b/navigation/codenite.md new file mode 100644 index 000000000..76ef7b6b4 --- /dev/null +++ b/navigation/codenite.md @@ -0,0 +1,170 @@ +--- +layout: base +title: CodeFree +permalink: /Codenite/ +--- + + + + + + + Shooter Game + + + + + + + + + diff --git a/navigation/ideas.md b/navigation/ideas.md new file mode 100644 index 000000000..b82022392 --- /dev/null +++ b/navigation/ideas.md @@ -0,0 +1,42 @@ +--- +layout: base +title: Ideas/Hack +description: Ideas +author: Amal Jinan +image: /images/mario_animation.png +hide: false +--- + +rpg.md: The JavaScript object literal pattern helps organize and manage the important parts of a program in one place. It makes things easier to understand and control, like putting all your tools in one toolbox, so you know where everything is when you need it. +GameControl.js: Defines data for assets in the game and starts the game. +GameEnv.js: Uses a classic Java static class pattern that manages the game environment. +Background.js: Creates the background. +Player.js: Creates the player. + + + +### Ideation hack + +### concept +The player is stranded on a deserted cloud and must gather resources (like water, food, and needs to safely get to land) to survive. +## Add an NPC- Add an interactable npc that can give you quests for loot and helps you navigate around the map +### Add weapons- +You can use Weapons to fight NPCs for loot and also add sheilds that can protect you from being damaged. +### Add mobs + +### Add Levels- +Every time you kill a certain number of NPCS you level up, and level up increases your max health +### Health +everytime you get hit by an npc, you lose a certain number of health and when it drops to 0, you lose everything and have to start over +### Story line +Add an interactive storyline where each part has different maps and npcs. +### Difficulties +The game will get more difficult as i goes by +### Scrolling maps +Everytime you finish a level, you automatically change the background. +### Music +Add a button where you can change the music +### Avatars +A customizable menu where you can change your avatar, hats/clothes/hair etc.. +### Fruits +Fruits can heal you and there are also thorns and moving blocks to give it a parkour like feeling diff --git a/navigation/popcornhack.ipynb b/navigation/popcornhack.ipynb new file mode 100644 index 000000000..664a69df2 --- /dev/null +++ b/navigation/popcornhack.ipynb @@ -0,0 +1,437 @@ + +{ + "cells": [ + { + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "comments: true\n", + "layout: post\n", + "title: JavaScript Data Types and Operators\n", + "description:Compound assingment.\n", + "permalink: /popcornhack/\n", + "categories: []\n", + "courses: { csse: {week: 6} }\n", + "type: ccc\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Compound Assignment\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "vscode": { + "languageId": "javascript" + } + }, + "outputs": [ + { + "data": { + "application/javascript": "\n/* Primitive Data Types\nThese are data types that store a single value.\n*/\n\n// Number: Represents numerical values, such as health and speed\nlet health = 100; // Integer\nlet playerSpeed = 5.75; // Float representing the player's speed\n\nconsole.log(\"Health (Number):\", health, \"Type:\", typeof health);\nconsole.log(\"Player Speed (Number):\", playerSpeed, \"Type:\", typeof playerSpeed);\n\n// String: Represents text, such as the user's name or keypress\nlet userName = \"Hero123\"; // User name\nlet keyPress = 'a'; // Keypress\n\nconsole.log(\"User Name (String):\", userName, \"Type:\", typeof userName);\nconsole.log(\"Key Press (String):\", keyPress, \"Type:\", typeof keyPress);\n\n// Compare single character to its ASCII value\nlet asciiValue = keyPress.charCodeAt(0);\nconsole.log(\"ASCII Value of Key Press:\", asciiValue, \"Type:\", typeof asciiValue);\nconsole.log(\"Is Key Press 'a' (ASCII 97)?\", asciiValue === 97);\n\n// Boolean: Represents true/false values, such as isAlive\nlet isAlive = true;\n\nconsole.log(\"Is Alive (Boolean):\", isAlive, \"Type:\", typeof isAlive);\n\n// Undefined: Represents a variable that has been declared but not yet assigned a value\nlet questReward;\n\nconsole.log(\"Quest Reward (Undefined):\", questReward, \"Type:\", typeof questReward);\n\n// Null: Represents the intentional absence of any object value, such as an empty inventory slot\nlet inventorySlot = null;\n\nconsole.log(\"Inventory Slot (Null):\", inventorySlot, \"Type:\", typeof inventorySlot);\n\n// Symbol: Represents a unique and immutable value, often used as unique identifiers for game objects\nlet uniqueID = Symbol('playerID');\n\nconsole.log(\"Unique ID (Symbol):\", uniqueID, \"Type:\", typeof uniqueID);\n\n// BigInt: Represents very large integers, such as the total time played in milliseconds\nlet totalTimePlayed = 1234567890123456789012345678901234567890n;\n\nconsole.log(\"Total Time Played (BigInt):\", totalTimePlayed, \"Type:\", typeof totalTimePlayed);\n\n/* Reference Data Types\nThese are data types that store references to memory locations.\n*/\n\n// Object: Represents a collection of key-value pairs, such as player attributes or game settings\nlet playerAttributes = {\n name: \"Hero123\",\n health: 100,\n mana: 50\n};\n\nconsole.log(\"Player Attributes (Object):\", playerAttributes, \"Type:\", typeof playerAttributes);\n\n// Array: Represents an ordered collection of values, such as a list of high scores or inventory items\nlet highScores = [1500, 1200, 900, 600, 300];\n\nconsole.log(\"High Scores (Array):\", highScores, \"Type:\", typeof highScores);\n\n// Function: Represents a block of code designed to perform a specific task, such as attacking an enemy or saving the game\nfunction attackEnemy() {\n console.log(\"Enemy attacked!\");\n}\n\nconsole.log(\"Attack Enemy (Function):\", attackEnemy, \"Type:\", typeof attackEnemy);\nattackEnemy();\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%js\n", + "\n", + "/* Primitive Data Types\n", + "These are data types that store a single value.\n", + "*/\n", + "\n", + "// Operation: += \n", + "let number =100 \n", + "number += 1 \n", + "\n", + "// Operation: -= \n", + "let number =100 \n", + "number -= 1 \n", + "\n", + "// Operation: *= \n", + "let number =100 \n", + "number *= 1 \n", + "\n", + "// Operation: /= \n", + "let number =100 \n", + "number /= 1 \n", + "\n" + ] + }, +{ + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Popcorn Hack 1\n", + "\n", + "Make a code cell that show usage of compound assignment in a Data Type Operations." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Scale a Block\n", + "\n", + "Scalling is an important Math operation that is used in Gaming. This example is considering HD formats to construct a block." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "

This example uses data types, operators, and functions to scale a block based on a user-defined width.

\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n", + "\n", + "\n", + "
\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html \n", + "\n", + "

This example uses data types, operators, and functions to scale a block based on a user-defined width.

\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n", + "\n", + "\n", + "
\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Popcorn Hack 2\n", + "\n", + "Make a code cell that changes block into a square, versus HD resolution" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Placing a Block\n", + "\n", + "Often in gaming you will want to position on element in relationship to another." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "vscode": { + "languageId": "html" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "

This example uses data types, operators, and functions to scale a block based on a user-defined width.

\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "%%html \n", + "\n", + "

This example uses data types, operators, and functions to scale a block based on a user-defined width.

\n", + "\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n", + "\n", + "\n", + "\n", + "\n", + "" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.5" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/navigation/rpg2x.md b/navigation/rpg2x.md new file mode 100644 index 000000000..6c478df33 --- /dev/null +++ b/navigation/rpg2x.md @@ -0,0 +1,41 @@ +--- +layout: base +title: RPG +permalink: /rpg/ +--- + + + + +
+ +
+ + diff --git a/navigation/search.md b/navigation/search.md deleted file mode 100644 index 2cf2ae8e1..000000000 --- a/navigation/search.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -layout: search -title: Search -search_exclude: true -permalink: /search/ ---- diff --git a/navigation/snake.md b/navigation/snake.md new file mode 100644 index 000000000..6e415fb7c --- /dev/null +++ b/navigation/snake.md @@ -0,0 +1,374 @@ +--- +layout: base +title: Snake +permalink: /snake/ +--- + + + +{% include nav/home.html %} + + + +

Snake

+
+
+

Score: 0

+
+
+ + + +
+

Game Over, press space to try again

+ new game + settings +
+ + + +
+

Settings Screen, press space to go back to playing

+ new game +
+

Speed: + + + + + + +

+

Wall: + + + + +

+
+
+
+ + diff --git a/navigation/typing-game.md b/navigation/typing-game.md new file mode 100644 index 000000000..68b1dfc54 --- /dev/null +++ b/navigation/typing-game.md @@ -0,0 +1,138 @@ +--- +layout: base +title: Typing Game +permalink: /Typing Game/ +--- + + + + + + + + Typing Game + + + + + + + + + + + diff --git a/scripts/activation.sh b/scripts/activation.sh new file mode 100644 index 000000000..cb26587b1 --- /dev/null +++ b/scripts/activation.sh @@ -0,0 +1,64 @@ +export GIT_USER_NAME="AmalJinan" +export GIT_USER_EMAIL="amalji1022@gmail.com" + +# Function to check if a line exists in run commands +line_exists_in_rc() { + grep -Fxq "$1" ~/.bashrc +} + +# Function to add line to run commands +add_to_rc() { + if ! line_exists_in_rc "$1"; then + echo "$1" >> ~/.bashrc + fi +} + +add_to_rc 'alias code="code --no-sandbox"' +add_to_rc 'alias venv="source venv/bin/activate"' +add_to_rc "git config --global user.name $AmalJinan" +add_to_rc "git config --global user.email $amalji1022@gmail.com" + +#### Github Pages Local Build support +echo "=== GitHub pages build tools ===" +add_to_rc "# Ruby Gem Path" +add_to_rc 'export GEM_HOME="$HOME/gems"' +add_to_rc 'export PATH="$HOME/gems/bin:$PATH"' +# Source the .bashrc file to apply changes immediately +source ~/.bashrc + +echo "=== Gem install starting, thinking... ===" +gem install jekyll bundler + +# GitHub VSCode extensions +code --install-extension github.vscode-github-actions +code --install-extension eamodio.gitlens + +# Python VSCode Extensions +code --install-extension ms-python.python --pre-release + +# Jupyter VSCode Extension +code --install-extension ms-toolsai.jupyter --pre-release + +# GitHub Copilot Extension +code --install-extension GitHub.copilot + +# Verify the installation and check the Python version +python --version +bundle --version + +# Create a virtual environment if it doesn't exist +if [ -d "venv" ]; then + rm -rf venv +fi +python -m venv venv + +# Activate the virtual environment +source ./venv/bin/activate + +# Install the required Python packages +pip install -r requirements.txt +bundle install + +# Activate session +echo "source ~/.bashrc" +echo "source venv/bin/activate" diff --git a/starts b/starts new file mode 100644 index 000000000..facf7d85a --- /dev/null +++ b/starts @@ -0,0 +1 @@ +###code