CompSci Blogs

August 2023 to June 2024

View the Project on GitHub IshanCornick/new_student

6 November 2023

Individual review

My commits on the passion project

Uses information from API

Frog-quiz

Frog game, go across

Frog-game

Frog searcher, search up your favorite frog to see a image of it

Frog-image-searcher

Image matcher with different reptiles

Image-matching-game

Flash cards to study your frogs!

Frog-flash-cards

# Image searcher
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    
    <form id="search-form">
        <input type="text" id="query" placeholder="Enter your search query">
        <button type="submit">Search</button>
    </form>
    <div id="image-results"></div>

    <script>
        const searchForm = document.getElementById('search-form');
        const queryInput = document.getElementById('query');
        const imageResults = document.getElementById('image-results');

        searchForm.addEventListener('submit', function (e) {
            e.preventDefault();
            const query = queryInput.value;
            if (query) {
                // Replace 'YOUR_API_KEY' with your actual Unsplash API key
                const apiKey = 'n9U-OR3Ylnh7at-fl7b7dFETxYrtLaB3CAzvUc6GRCY';
                const apiUrl = `https://api.unsplash.com/search/photos?query=${query}&per_page=10&client_id=${apiKey}`;

                fetch(apiUrl)
                    .then(response => response.json())
                    .then(data => {
                        displayImageResults(data.results);
                    })
                    .catch(error => {
                        console.error('Error fetching data:', error);
                    });
            }
        });

        function displayImageResults(results) {
            imageResults.innerHTML = '';

            results.forEach(result => {
                const imgElement = document.createElement('img');
                imgElement.src = result.urls.small;
                imgElement.alt = result.description;
                imageResults.appendChild(imgElement);
            });
        }
    </script>
</body>
</html>

# Quiz about frogs
<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f2f2f2;
        }

        #quiz-container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }

        h1 {
            text-align: center;
            color: #009688;
        }

        #question {
            font-size: 18px;
            margin-bottom: 15px;
            color: #333;
        }

        .option {
            display: block;
            width: 100%;
            padding: 10px;
            margin: 5px 0;
            background-color: #009688;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }

        .option:hover {
            background-color: #00716d;
        }

        #result {
            font-size: 18px;
            text-align: center;
            margin-top: 20px;
            color: #333;
        }

        #score-container {
            text-align: center;
            margin-top: 20px;
        }

        #score-bar {
            background-color: #4CAF50;
            height: 20px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div id="quiz-container">
        <h1>Frog Quiz</h1>
        <div id="question-container">
            <p id="question"></p>
        </div>
        <div id="options-container">
            <button class="option" onclick="checkAnswer(this.textContent)">Option 1</button>
            <button class="option" onclick="checkAnswer(this.textContent)">Option 2</button>
            <button class="option" onclick="checkAnswer(this.textContent)">Option 3</button>
            <button class="option" onclick="checkAnswer(this.textContent)">Option 4</button>
        </div>
        <p id="result"></p>
        <div id="score-container">
            <p>Your Score:</p>
            <div id="score-bar" style="width: 100%; background-color: #4CAF50;"></div>
        </div>
    </div>

    <script>
    const questions = [
        {
            question: "What is the scientific name for the American Bullfrog?",
            options: ["Lithobates catesbeianus", "Rana sylvatica", "Atelopus zeteki", "Dendrobatidae family"],
            correctAnswer: "Lithobates catesbeianus"
        },
        {
            question: "What is the scientific name for the Red-eyed Tree Frog?",
            options: ["Agalychnis callidryas", "Rana aurora", "Hyperolius marmoratus", "Hyla gratiosa"],
            correctAnswer: "Agalychnis callidryas"
        },
        {
            question: "What is the scientific name for the Poison Dart Frog?",
            options: ["Dendrobatidae family", "Trachycephalus resinifictrix", "Phyllobates terribilis", "Duellmanohyla soralia"],
            correctAnswer: "Dendrobatidae family"
        },
        {
            question: "Where does the Red-eyed Tree Frog primarily live?",
            options: ["Rainforests of Central America", "Deserts of North America", "Mountains of Asia", "Savannahs of Africa"],
            correctAnswer: "Rainforests of Central America"
        },
        {
            question: "What is the primary predator of the Poison Dart Frog?",
            options: ["Snakes", "Eagles", "Crocodiles", "Cats"],
            correctAnswer: "Snakes"
        },
        {
            question: "What is the main prey of the Goliath Frog?",
            options: ["Insects", "Small Fish", "Birds", "Plants"],
            correctAnswer: "Insects"
        },
        {
            question: "Where can you find the Tomato Frog?",
            options: ["Madagascar", "Australia", "Amazon Rainforest", "North America"],
            correctAnswer: "Madagascar"
        },
        {
            question: "What is the primary habitat of the Glass Frog?",
            options: ["Tropical Rainforests", "Deserts", "Swamps", "Grasslands"],
            correctAnswer: "Tropical Rainforests"
        },
        {
            question: "What is the primary predator of the Barking Tree Frog?",
            options: ["Owls", "Foxes", "Alligators", "Wolves"],
            correctAnswer: "Owls"
        },
        {
            question: "What type of habitat does the White's Tree Frog prefer?",
            options: ["Woodlands and Rainforests", "Deserts", "Mountains", "Swamps"],
            correctAnswer: "Woodlands and Rainforests"
        },
        {
            question: "What is the primary prey of the Painted Reed Frog?",
            options: ["Insects", "Small Fish", "Birds", "Amphibians"],
            correctAnswer: "Insects"
        },
        {
            question: "Where is the Eastern Spadefoot Toad commonly found?",
            options: ["North America", "Asia", "Africa", "Australia"],
            correctAnswer: "North America"
        },
        {
            question: "What type of habitat does the Plains Leopard Frog prefer?",
            options: ["Ponds, Lakes, and Marshes", "Mountains", "Deserts", "Tundra"],
            correctAnswer: "Ponds, Lakes, and Marshes"
        },
        {
            question: "What type of habitat does the American Bullfrog prefer?",
            options: ["Ponds, Lakes, and Rivers", "Deserts", "Rainforests", "Mountains"],
            correctAnswer: "Ponds, Lakes, and Rivers"
        },
        {
            question: "What is the primary predator of the Red-eyed Tree Frog?",
            options: ["Snakes", "Owls", "Jaguars", "Caimans"],
            correctAnswer: "Snakes"
        },
        {
            question: "What is the main prey of the Poison Dart Frog?",
            options: ["Ants", "Beetles", "Mosquitoes", "Flies"],
            correctAnswer: "Ants"
        },
        {
            question: "Where does the Wood Frog hibernate during winter?",
            options: ["Underground", "In Trees", "In Rivers", "In Caves"],
            correctAnswer: "Underground"
        },
        {
            question: "What is the unique feature of the Goliath Frog?",
            options: ["Largest Frog in the World", "Bioluminescent Skin", "Mimics the Color of Leaves", "Translucent Skin"],
            correctAnswer: "Largest Frog in the World"
        },
        {
            question: "What is the Tomato Frog's warning coloration?",
            options: ["Bright Red", "Green", "Yellow", "Brown"],
            correctAnswer: "Bright Red"
        },
        {
            question: "How do Glass Frogs get their name?",
            options: ["Translucent Belly", "Glass-Like Skin", "Reflective Eyes", "Glassy Croaking Sound"],
            correctAnswer: "Translucent Belly"
        },
        {
            question: "What is the primary habitat of the African Clawed Frog?",
            options: ["African Lakes and Rivers", "Deserts", "Arctic Tundra", "Caves"],
            correctAnswer: "African Lakes and Rivers"
        },
        {
            question: "What is the most toxic frog in the world?",
            options: ["Golden Poison Dart Frog", "Blue Poison Dart Frog", "Green Tree Frog", "Fire-bellied Toad"],
            correctAnswer: "Golden Poison Dart Frog"
        },
        {
            question: "Where is the Panamanian Golden Frog endemic to?",
            options: ["Panama", "Madagascar", "Australia", "Amazon Rainforest"],
            correctAnswer: "Panama"
        }
    ];

        let currentQuestionIndex = 0;
        const questionElement = document.getElementById("question");
        const options = document.querySelectorAll(".option");
        const resultElement = document.getElementById("result");
        const scoreBar = document.getElementById("score-bar");
        let score = 0;

        function shuffleArray(array) {
            for (let i = array.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [array[i], array[j]] = [array[j], array[i]];
            }
        }

        function displayQuestion() {
            const currentQuestion = questions[currentQuestionIndex];
            questionElement.textContent = currentQuestion.question;
            shuffleArray(currentQuestion.options);
            options.forEach((option, index) => {
                option.textContent = currentQuestion.options[index];
            });
        }

        function checkAnswer(selectedAnswer) {
            const correctAnswer = questions[currentQuestionIndex].correctAnswer;

            if (selectedAnswer === correctAnswer) {
                resultElement.textContent = "Correct!";
                score++;
            } else {
                resultElement.textContent = "Incorrect. The correct answer is " + correctAnswer;
            }

            currentQuestionIndex++;

            if (currentQuestionIndex < questions.length) {
                displayQuestion();
            } else {
                questionElement.textContent = "Quiz complete!";
                document.getElementById("options-container").style.display = "none";
                const percentage = (score / questions.length) * 100;
                scoreBar.style.width = percentage + "%";
                resultElement.textContent = `You scored ${score} out of ${questions.length} questions (${percentage}%)`;
            }
        }

        displayQuestion();
    </script>
</body>
</html>



# Crossy road game
<!DOCTYPE html>
<html>
<head>
  <title>Basic Frogger HTML Game</title>
  <meta charset="UTF-8">
  <style>
  html, body {
    height: 100%;
    margin: 0;
  }

  body {
    background: black;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  </style>
</head>
<body>
<canvas width="624" height="720" id="game"></canvas>
<script>
const canvas = document.getElementById('game');
const context = canvas.getContext('2d');

const grid = 48;
const gridGap = 10;

// a simple sprite prototype function
function Sprite(props) {
  // shortcut for assigning all object properties to the sprite
  Object.assign(this, props);
}
Sprite.prototype.render = function() {
  context.fillStyle = this.color;

  // draw a rectangle sprite
  if (this.shape === 'rect') {
    // by using a size less than the grid we can ensure there is a visual space
    // between each row
    context.fillRect(this.x, this.y + gridGap / 2, this.size, grid - gridGap);
  }
  // draw a circle sprite. since size is the diameter we need to divide by 2
  // to get the radius. also the x/y position needs to be centered instead of
  // the top-left corner of the sprite
  else {
    context.beginPath();
    context.arc(
      this.x + this.size / 2, this.y + this.size / 2,
      this.size / 2 - gridGap / 2, 0, 2 * Math.PI
    );
    context.fill();
  }
}

const frogger = new Sprite({
  x: grid * 6,
  y: grid * 13,
  color: 'greenyellow',
  size: grid,
  shape: 'circle'
});
const scoredFroggers = [];

// a pattern describes each obstacle in the row
const patterns = [
  // end bank is safe
  null,

  // log
  {
    spacing: [2],      // how many grid spaces between each obstacle
    color: '#c55843',  // color of the obstacle
    size: grid * 4,    // width (rect) / diameter (circle) of the obstacle
    shape: 'rect',     // shape of the obstacle (rect or circle)
    speed: 0.75        // how fast the obstacle moves and which direction
  },

  // turtle
  {
    spacing: [0,2,0,2,0,2,0,4],
    color: '#de0004',
    size: grid,
    shape: 'circle',
    speed: -1
  },

  // long log
  {
    spacing: [2],
    color: '#c55843',
    size: grid * 7,
    shape: 'rect',
    speed: 1.5
  },

  // log
  {
    spacing: [3],
    color: '#c55843',
    size: grid * 3,
    shape: 'rect',
    speed: 0.5
  },

  // turtle
  {
    spacing: [0,0,1],
    color: '#de0004',
    size: grid,
    shape: 'circle',
    speed: -1
  },

  // beach is safe
  null,

  // truck
  {
    spacing: [3,8],
    color: '#c2c4da',
    size: grid * 2,
    shape: 'rect',
    speed: -1
  },

  // fast car
  {
    spacing: [14],
    color: '#c2c4da',
    size: grid,
    shape: 'rect',
    speed: 0.75
  },

  // car
  {
    spacing: [3,3,7],
    color: '#de3cdd',
    size: grid,
    shape: 'rect',
    speed: -0.75
  },

  // bulldozer
  {
    spacing: [3,3,7],
    color: '#0bcb00',
    size: grid,
    shape: 'rect',
    speed: 0.5
  },

  // car
  {
    spacing: [4],
    color: '#e5e401',
    size: grid,
    shape: 'rect',
    speed: -0.5
  },

  // start zone is safe
  null
];

// rows holds all the sprites for that row
const rows = [];
for (let i = 0; i < patterns.length; i++) {
  rows[i] = [];

  let x = 0;
  let index = 0;
  const pattern = patterns[i];

  // skip empty patterns (safe zones)
  if (!pattern) {
    continue;
  }

  // allow there to be 1 extra pattern offscreen so the loop is seamless
  // (especially for the long log)
  let totalPatternWidth =
    pattern.spacing.reduce((acc, space) => acc + space, 0) * grid +
    pattern.spacing.length * pattern.size;
  let endX = 0;
  while (endX < canvas.width) {
    endX += totalPatternWidth;
  }
  endX += totalPatternWidth;

  // populate the row with sprites
  while (x < endX) {
    rows[i].push(new Sprite({
      x,
      y: grid * (i + 1),
      index,
      ...pattern
    }));

    // move the next sprite over according to the spacing
    const spacing = pattern.spacing;
    x += pattern.size + spacing[index] * grid;
    index = (index + 1) % spacing.length;
  }
}

// game loop
function loop() {
  requestAnimationFrame(loop);
  context.clearRect(0,0,canvas.width,canvas.height);

  // draw the game background
  // water
  context.fillStyle = '#000047';
  context.fillRect(0, grid, canvas.width, grid * 6);

  // end bank
  context.fillStyle = '#1ac300';
  context.fillRect(0, grid, canvas.width, 5);
  context.fillRect(0, grid, 5, grid);
  context.fillRect(canvas.width - 5, grid, 5, grid);
  for (let i = 0; i < 4; i++) {
    context.fillRect(grid + grid * 3 * i, grid, grid * 2, grid);
  }

  // beach
  context.fillStyle = '#8500da';
  context.fillRect(0, 7 * grid, canvas.width, grid);

  // start zone
  context.fillRect(0, canvas.height - grid * 2, canvas.width, grid);

  // update and draw obstacles
  for (let r = 0; r < rows.length; r++) {
    const row = rows[r];

    for (let i = 0; i < row.length; i++) {
      const sprite = row[i]
      sprite.x += sprite.speed;
      sprite.render();

      // loop sprite around the screen
      // sprite is moving to the left and goes offscreen
      if (sprite.speed < 0 && sprite.x < 0 - sprite.size) {

        // find the rightmost sprite
        let rightMostSprite = sprite;
        for (let j = 0; j < row.length; j++) {
          if (row[j].x > rightMostSprite.x) {
            rightMostSprite = row[j];
          }
        }

        // move the sprite to the next spot in the pattern so it continues
        const spacing = patterns[r].spacing;
        sprite.x =
          rightMostSprite.x + rightMostSprite.size +
          spacing[rightMostSprite.index] * grid;
        sprite.index = (rightMostSprite.index + 1) % spacing.length;
      }

      // sprite is moving to the right and goes offscreen
      if (sprite.speed > 0 && sprite.x > canvas.width) {

        // find the leftmost sprite
        let leftMostSprite = sprite;
        for (let j = 0; j < row.length; j++) {
          if (row[j].x < leftMostSprite.x) {
            leftMostSprite = row[j];
          }
        }

        // move the sprite to the next spot in the pattern so it continues
        const spacing = patterns[r].spacing;
        let index = leftMostSprite.index - 1;
        index = index >= 0 ? index : spacing.length - 1;
        sprite.x = leftMostSprite.x - spacing[index] * grid - sprite.size;
        sprite.index = index;
      }
    }
  }

  // draw frogger
  frogger.x += frogger.speed || 0;
  frogger.render();

  // draw scored froggers
  scoredFroggers.forEach(frog => frog.render());

  // check for collision with all sprites in the same row as frogger
  const froggerRow = frogger.y / grid - 1 | 0;
  let collision = false;
  for (let i = 0; i < rows[froggerRow].length; i++) {
    let sprite = rows[froggerRow][i];

    // axis-aligned bounding box (AABB) collision check
    // treat any circles as rectangles for the purposes of collision
    if (frogger.x < sprite.x + sprite.size - gridGap &&
        frogger.x + grid - gridGap > sprite.x &&
        frogger.y < sprite.y + grid &&
        frogger.y + grid > sprite.y) {
      collision = true;

      // reset frogger if got hit by car
      if (froggerRow > rows.length / 2) {
        frogger.x = grid * 6;
        frogger.y = grid * 13;
      }
      // move frogger along with obstacle
      else {
        frogger.speed = sprite.speed;
      }
    }
  }

  if (!collision) {
    // if fogger isn't colliding reset speed
    frogger.speed = 0;

    // frogger got to end bank (goal every 3 cols)
    const col = (frogger.x + grid / 2) / grid | 0;
    if (froggerRow === 0 && col % 3 === 0 &&
        // check to see if there isn't a scored frog already there
        !scoredFroggers.find(frog => frog.x === col * grid)) {
      scoredFroggers.push(new Sprite({
        ...frogger,
        x: col * grid,
        y: frogger.y + 5
      }));
    }

    // reset frogger if not on obstacle in river
    if (froggerRow < rows.length / 2 - 1) {
      frogger.x = grid * 6;
      frogger.y = grid * 13;
    }
  }
}

// listen to keyboard events to move frogger
document.addEventListener('keydown', function(e) {
  // left arrow key
  if (e.which === 37) {
    frogger.x -= grid;
  }
  // right arrow key
  else if (e.which === 39) {
    frogger.x += grid;
  }

  // up arrow key
  else if (e.which === 38) {
    frogger.y -= grid;
  }
  // down arrow key
  else if (e.which === 40) {
    frogger.y += grid;
  }

  // clamp frogger position to stay on screen
  frogger.x = Math.min( Math.max(0, frogger.x), canvas.width - grid);
  frogger.y = Math.min( Math.max(grid, frogger.y), canvas.height - grid * 2);
});

// start the game
requestAnimationFrame(loop);
</script>
</body>
</html>
# Matching game
<html>
<head>
    <title>Frog Memory Match Game</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        .memory-game {
            display: grid;
            grid-template-columns: repeat(4, 100px);
            grid-gap: 10px;
        }

        .memory-card {
            width: 100px;
            height: 100px;
            background-color: #2196F3;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            user-select: none;
        }

        .matched {
            background-color: #4CAF50;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div class="memory-game" id="memory-game"></div>

    <script>
        const memoryGame = document.getElementById("memory-game");
        const frogs = [
            '🐸', '🐸', '🐢', '🐢', '🐍', '🐍', '🐊', '🐊',
            '🦎', '🦎', '🦖', '🦖', '🦗', '🦗', '🐛', '🐛'
        ];
        const shuffledFrogs = frogs.sort(() => 0.5 - Math.random());
        let firstCard = null;
        let secondCard = null;
        let canFlip = true;

        function createCard(frog) {
            const card = document.createElement('div');
            card.classList.add('memory-card');
            card.textContent = frog;
            card.addEventListener('click', flipCard);
            memoryGame.appendChild(card);
        }

        function flipCard() {
            if (!canFlip) return;
            if (!firstCard) {
                firstCard = this;
                firstCard.classList.add('matched');
                return;
            }
            if (this === firstCard) return;
            secondCard = this;
            secondCard.classList.add('matched');
            canFlip = false;

            setTimeout(checkForMatch, 1000);
        }

        function checkForMatch() {
            if (firstCard.textContent === secondCard.textContent) {
                firstCard.removeEventListener('click', flipCard);
                secondCard.removeEventListener('click', flipCard);
            } else {
                firstCard.classList.remove('matched');
                secondCard.classList.remove('matched');
            }

            firstCard = null;
            secondCard = null;
            canFlip = true;

            if (document.querySelectorAll('.memory-card.matched').length === frogs.length) {
                alert('Congratulations! You matched all the frogs!');
            }
        }

        shuffledFrogs.forEach(createCard);
    </script>
</body>
</html>

# Flash cards
<!DOCTYPE html>
<html>
<head>
    <title>Frog Flash Cards</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            text-align: center;
            margin: 0;
            padding: 0;
        }

        #flash-cards-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }

        .flash-card {
            width: 200px;
            height: 120px;
            background-color: #fff; /* White background for the flash card */
            border: 1px solid #ccc;
            margin: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: transform 0.2s ease-in-out;
            position: relative;
            border-radius: 5px;
        }

        .flash-card:hover {
            transform: scale(1.05);
        }

        .front, .back {
            background-color: #fff; /* White background for both sides */
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            text-align: center;
            padding: 10px;
        }

        .front {
            color: #000; /* Black text color */
            border-radius: 5px;
        }

        .back {
            color: #000; /* Black text color */
            display: none;
        }

        h3 {
            font-size: 20px;
            margin: 0;
            padding: 5px;
        }

        p {
            font-size: 14px;
            margin: 0;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div id="flash-cards-container"></div>

    <script>
        const flashCardsContainer = document.getElementById("flash-cards-container");

        // Fetch data from your backend API
        fetch('https://projectsailbackend.stu.nighthawkcodingsociety.com/api/frog-items/') // Replace with your actual API endpoint
            .then(response => response.json())
            .then(data => {
                data.forEach(frog => {
                    const flashCard = document.createElement("div");
                    flashCard.className = "flash-card";
                    flashCard.innerHTML = `
                        <div class="front">
                            <h3>${frog.name}</h3>
                        </div>
                        <div class="back">
                            <p>Prey: ${frog.prey}<br>Predators: ${frog.predators}</p>
                        </div>
                    `;
                    flashCardsContainer.appendChild(flashCard);

                    flashCard.addEventListener("click", () => {
                        flashCard.querySelector(".front").style.display = "none";
                        flashCard.querySelector(".back").style.display = "block";
                    });

                    flashCard.addEventListener("mouseleave", () => {
                        flashCard.querySelector(".front").style.display = "block";
                        flashCard.querySelector(".back").style.display = "none";
                    });
                });
            })
            .catch(error => console.error(error));
    </script>
</body>
</html>

Pseudo notes

# Variables and Data Types

# Structure
<VariableName> <- <Value>
# Example
Age <- 40
Name <- "Bob Joe"

Input and Output

Conditional Statements (IF-ELSE)

# Structure
IF <Condition> THEN
    <CodeBlock1>
ELSE
    <CodeBlock2>
ENDIF
# Example
IF Age > 18 THEN
    Output "You are an adult"
ELSE
    Output "You are a minor"
ENDIF

Loops (FOR)

# Structure
WHILE <Condition>
    <CodeBlock>
ENDWHILE
# Example
WHILE Age < 30
    Output "Happy Birthday!"
    Age <- Age + 1
ENDWHILE

Arrays

# Structure
Array <Name> [<Size>]

# Example
Array Numbers[5]
Numbers[0] <- 10
Numbers[1] <- 20

Functions

# Structure
FUNCTION <Name>(<Parameters>)
    <CodeBlock>
    RETURN <Value>
ENDFUNCTION

# Example
FUNCTION Add(a, b)
    RETURN a + b
ENDFUNCTION

Result <- Add(10, 20)

Comments

# Structure
// This is a comment
# Example
// This function adds two numbers
FUNCTION Add(a, b)
    RETURN a + b
ENDFUNCTION

Student Teaching

Developing Algorithms

Developing algorithms is a fundamental skill in computer science and problem-solving. An algorithm is a well-defined step-by-step procedure or set of rules used to solve a specific problem or accomplish a task. The process of creating algorithms involves several key steps and considerations:

Understanding the Problem

Before designing an algorithm, it’s crucial to thoroughly understand the problem you intend to solve. This includes defining the problem’s scope, gathering relevant information, and specifying the input data, desired output, and any constraints or requirements.

Code Implementation

Once you have a well-designed algorithm, you can implement it in your preferred programming language. In Python, you can use the def keyword to define functions that encapsulate the algorithm’s logic. Follow best coding practices and add comments to improve code readability.

Data Abstraction

Data abstraction is a programming concept that involves hiding the complex details of how data is stored and manipulated while providing a simplified interface for interacting with that data. This concept is achieved through the use of classes and objects in Python.

Algorithms and Simulations

Algorithms are step-by-step procedures used to solve specific problems or accomplish tasks efficiently. They play a fundamental role in computer science, mathematics, and various other fields. Algorithms are essential for structured problem-solving and have applications in a wide range of areas.

Simulations involve using algorithms to model and analyze real-world processes or systems. In simulations, algorithms are employed to observe how a system behaves under different conditions. Simulations are widely used in fields such as computer science, engineering, and social sciences for experimentation and analysis.

Python is a versatile tool for both algorithm development and simulations, as it allows you to implement and test algorithms and models for a wide variety of scenarios.

These topics are fundamental in programming, and a solid understanding of them can greatly enhance your ability to develop efficient algorithms, work with data, make decisions, create simulations, and utilize data abstraction in Python or any other programming language.

College Board Study Guide

1. Data Representation

Binary, Decimal, Hexadecimal:

Conversion between Number Systems:

Bitwise Operations (AND, OR, XOR, NOT):

2. Compression and Encryption

Data Compression Purpose and Methods:

Compression Algorithms (e.g., Huffman Coding):

Data Encryption Purpose and Methods:

Encryption Algorithms (e.g., AES, RSA):

3. Error Detection and Correction

Parity Bits for Error Detection:

Error Correction Techniques (e.g., Hamming Code):

4. Digital Logic and Circuits

Logic Gates and Truth Tables:

Digital Circuit Components:

Boolean Algebra:

5. Boolean Algebra

Laws and Theorems of Boolean Algebra:

Simplifying Boolean Expressions:

6. CPU Architecture

Components of a CPU:

Fetch-Decode-Execute Cycle:

7. Memory

Types of Memory:

Cache Memory:

8. Input and Output Devices

Input Devices:

Output Devices:

9. File Systems

File Systems and Data Organization:

File Naming Conventions and Permissions:

10. Networking and the Internet

Basic Networking Concepts:

OSI Model and Its Layers:

11. Cybersecurity

Common Cybersecurity Threats:

Cybersecurity Best Practices:

12. Ethical and Social Implications

Ethical Considerations in Technology:

Impact of Technology on Society:

Summary of what I learned in Trimester 1 and problems I had

  1. Problems
    • For the passion project, we already started off behind since we did our team test so much later than we should of, causing us to be very behind
    • Since we were behind we werent sure what each job did and what were meant to do before
    • We had to get rid of ideas that we already had work on as we realized we cant show python code on the site.
    • We had a lot of trouble connecting our front and backend because we could not get the flask link, but we then figured out we had to edit our main.py more
    • We couldn’t seperate the information of each frog before when you clicked on them. But we fixed it by making different permalinks for the .mds and havinjg different functions for the on-click events.
    • We had trouble deploying AWS as the ports were full, to fix this we connected to a CSA port and point towards CSA.
  2. Things I learned and accomplishments
    • Despite our set backs, we still came out with a pretty good final product and our teamwork improved drastically.
    • I learned how to interact with vscode and learnt JS and Python.
    • I know how to make quizzes and flash cards with other apis and backend.
    • I learned how to do frontend and connect it to the backend

My commits on the passion project

  • For the passion project I did the entire Frontend except the homepage. This includes the 2 games, flash cards, quiz and image searcher. This shows everything I learned in this class so far by showing many different things that are not similar in making of them.
  • I deployed AWS after failed attempts from teammates with the help of other classmates and teachers.
  • I used other another api for my image searcher but did not use it for the flash cards to show 2 different things while not making it to similar.
  • I also worked of frogs.py by helping collect the data of the frogs and organizing them.

Uses information from API

Frog-quiz

Frog game, go across

Frog-game

Frog searcher, search up your favorite frog to see a image of it

Frog-image-searcher

Image matcher with different reptiles

Image-matching-game

Flash cards to study your frogs!

Frog-flash-cards

# Image searcher
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    
    <form id="search-form">
        <input type="text" id="query" placeholder="Enter your search query">
        <button type="submit">Search</button>
    </form>
    <div id="image-results"></div>

    <script>
        const searchForm = document.getElementById('search-form');
        const queryInput = document.getElementById('query');
        const imageResults = document.getElementById('image-results');

        searchForm.addEventListener('submit', function (e) {
            e.preventDefault();
            const query = queryInput.value;
            if (query) {
                // Replace 'YOUR_API_KEY' with your actual Unsplash API key
                const apiKey = 'n9U-OR3Ylnh7at-fl7b7dFETxYrtLaB3CAzvUc6GRCY';
                const apiUrl = `https://api.unsplash.com/search/photos?query=${query}&per_page=10&client_id=${apiKey}`;

                fetch(apiUrl)
                    .then(response => response.json())
                    .then(data => {
                        displayImageResults(data.results);
                    })
                    .catch(error => {
                        console.error('Error fetching data:', error);
                    });
            }
        });

        function displayImageResults(results) {
            imageResults.innerHTML = '';

            results.forEach(result => {
                const imgElement = document.createElement('img');
                imgElement.src = result.urls.small;
                imgElement.alt = result.description;
                imageResults.appendChild(imgElement);
            });
        }
    </script>
</body>
</html>

# Quiz about frogs
<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f2f2f2;
        }

        #quiz-container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }

        h1 {
            text-align: center;
            color: #009688;
        }

        #question {
            font-size: 18px;
            margin-bottom: 15px;
            color: #333;
        }

        .option {
            display: block;
            width: 100%;
            padding: 10px;
            margin: 5px 0;
            background-color: #009688;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }

        .option:hover {
            background-color: #00716d;
        }

        #result {
            font-size: 18px;
            text-align: center;
            margin-top: 20px;
            color: #333;
        }

        #score-container {
            text-align: center;
            margin-top: 20px;
        }

        #score-bar {
            background-color: #4CAF50;
            height: 20px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div id="quiz-container">
        <h1>Frog Quiz</h1>
        <div id="question-container">
            <p id="question"></p>
        </div>
        <div id="options-container">
            <button class="option" onclick="checkAnswer(this.textContent)">Option 1</button>
            <button class="option" onclick="checkAnswer(this.textContent)">Option 2</button>
            <button class="option" onclick="checkAnswer(this.textContent)">Option 3</button>
            <button class="option" onclick="checkAnswer(this.textContent)">Option 4</button>
        </div>
        <p id="result"></p>
        <div id="score-container">
            <p>Your Score:</p>
            <div id="score-bar" style="width: 100%; background-color: #4CAF50;"></div>
        </div>
    </div>

    <script>
    const questions = [
        {
            question: "What is the scientific name for the American Bullfrog?",
            options: ["Lithobates catesbeianus", "Rana sylvatica", "Atelopus zeteki", "Dendrobatidae family"],
            correctAnswer: "Lithobates catesbeianus"
        },
        {
            question: "What is the scientific name for the Red-eyed Tree Frog?",
            options: ["Agalychnis callidryas", "Rana aurora", "Hyperolius marmoratus", "Hyla gratiosa"],
            correctAnswer: "Agalychnis callidryas"
        },
        {
            question: "What is the scientific name for the Poison Dart Frog?",
            options: ["Dendrobatidae family", "Trachycephalus resinifictrix", "Phyllobates terribilis", "Duellmanohyla soralia"],
            correctAnswer: "Dendrobatidae family"
        },
        {
            question: "Where does the Red-eyed Tree Frog primarily live?",
            options: ["Rainforests of Central America", "Deserts of North America", "Mountains of Asia", "Savannahs of Africa"],
            correctAnswer: "Rainforests of Central America"
        },
        {
            question: "What is the primary predator of the Poison Dart Frog?",
            options: ["Snakes", "Eagles", "Crocodiles", "Cats"],
            correctAnswer: "Snakes"
        },
        {
            question: "What is the main prey of the Goliath Frog?",
            options: ["Insects", "Small Fish", "Birds", "Plants"],
            correctAnswer: "Insects"
        },
        {
            question: "Where can you find the Tomato Frog?",
            options: ["Madagascar", "Australia", "Amazon Rainforest", "North America"],
            correctAnswer: "Madagascar"
        },
        {
            question: "What is the primary habitat of the Glass Frog?",
            options: ["Tropical Rainforests", "Deserts", "Swamps", "Grasslands"],
            correctAnswer: "Tropical Rainforests"
        },
        {
            question: "What is the primary predator of the Barking Tree Frog?",
            options: ["Owls", "Foxes", "Alligators", "Wolves"],
            correctAnswer: "Owls"
        },
        {
            question: "What type of habitat does the White's Tree Frog prefer?",
            options: ["Woodlands and Rainforests", "Deserts", "Mountains", "Swamps"],
            correctAnswer: "Woodlands and Rainforests"
        },
        {
            question: "What is the primary prey of the Painted Reed Frog?",
            options: ["Insects", "Small Fish", "Birds", "Amphibians"],
            correctAnswer: "Insects"
        },
        {
            question: "Where is the Eastern Spadefoot Toad commonly found?",
            options: ["North America", "Asia", "Africa", "Australia"],
            correctAnswer: "North America"
        },
        {
            question: "What type of habitat does the Plains Leopard Frog prefer?",
            options: ["Ponds, Lakes, and Marshes", "Mountains", "Deserts", "Tundra"],
            correctAnswer: "Ponds, Lakes, and Marshes"
        },
        {
            question: "What type of habitat does the American Bullfrog prefer?",
            options: ["Ponds, Lakes, and Rivers", "Deserts", "Rainforests", "Mountains"],
            correctAnswer: "Ponds, Lakes, and Rivers"
        },
        {
            question: "What is the primary predator of the Red-eyed Tree Frog?",
            options: ["Snakes", "Owls", "Jaguars", "Caimans"],
            correctAnswer: "Snakes"
        },
        {
            question: "What is the main prey of the Poison Dart Frog?",
            options: ["Ants", "Beetles", "Mosquitoes", "Flies"],
            correctAnswer: "Ants"
        },
        {
            question: "Where does the Wood Frog hibernate during winter?",
            options: ["Underground", "In Trees", "In Rivers", "In Caves"],
            correctAnswer: "Underground"
        },
        {
            question: "What is the unique feature of the Goliath Frog?",
            options: ["Largest Frog in the World", "Bioluminescent Skin", "Mimics the Color of Leaves", "Translucent Skin"],
            correctAnswer: "Largest Frog in the World"
        },
        {
            question: "What is the Tomato Frog's warning coloration?",
            options: ["Bright Red", "Green", "Yellow", "Brown"],
            correctAnswer: "Bright Red"
        },
        {
            question: "How do Glass Frogs get their name?",
            options: ["Translucent Belly", "Glass-Like Skin", "Reflective Eyes", "Glassy Croaking Sound"],
            correctAnswer: "Translucent Belly"
        },
        {
            question: "What is the primary habitat of the African Clawed Frog?",
            options: ["African Lakes and Rivers", "Deserts", "Arctic Tundra", "Caves"],
            correctAnswer: "African Lakes and Rivers"
        },
        {
            question: "What is the most toxic frog in the world?",
            options: ["Golden Poison Dart Frog", "Blue Poison Dart Frog", "Green Tree Frog", "Fire-bellied Toad"],
            correctAnswer: "Golden Poison Dart Frog"
        },
        {
            question: "Where is the Panamanian Golden Frog endemic to?",
            options: ["Panama", "Madagascar", "Australia", "Amazon Rainforest"],
            correctAnswer: "Panama"
        }
    ];

        let currentQuestionIndex = 0;
        const questionElement = document.getElementById("question");
        const options = document.querySelectorAll(".option");
        const resultElement = document.getElementById("result");
        const scoreBar = document.getElementById("score-bar");
        let score = 0;

        function shuffleArray(array) {
            for (let i = array.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [array[i], array[j]] = [array[j], array[i]];
            }
        }

        function displayQuestion() {
            const currentQuestion = questions[currentQuestionIndex];
            questionElement.textContent = currentQuestion.question;
            shuffleArray(currentQuestion.options);
            options.forEach((option, index) => {
                option.textContent = currentQuestion.options[index];
            });
        }

        function checkAnswer(selectedAnswer) {
            const correctAnswer = questions[currentQuestionIndex].correctAnswer;

            if (selectedAnswer === correctAnswer) {
                resultElement.textContent = "Correct!";
                score++;
            } else {
                resultElement.textContent = "Incorrect. The correct answer is " + correctAnswer;
            }

            currentQuestionIndex++;

            if (currentQuestionIndex < questions.length) {
                displayQuestion();
            } else {
                questionElement.textContent = "Quiz complete!";
                document.getElementById("options-container").style.display = "none";
                const percentage = (score / questions.length) * 100;
                scoreBar.style.width = percentage + "%";
                resultElement.textContent = `You scored ${score} out of ${questions.length} questions (${percentage}%)`;
            }
        }

        displayQuestion();
    </script>
</body>
</html>



# Crossy road game
<!DOCTYPE html>
<html>
<head>
  <title>Basic Frogger HTML Game</title>
  <meta charset="UTF-8">
  <style>
  html, body {
    height: 100%;
    margin: 0;
  }

  body {
    background: black;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  </style>
</head>
<body>
<canvas width="624" height="720" id="game"></canvas>
<script>
const canvas = document.getElementById('game');
const context = canvas.getContext('2d');

const grid = 48;
const gridGap = 10;

// a simple sprite prototype function
function Sprite(props) {
  // shortcut for assigning all object properties to the sprite
  Object.assign(this, props);
}
Sprite.prototype.render = function() {
  context.fillStyle = this.color;

  // draw a rectangle sprite
  if (this.shape === 'rect') {
    // by using a size less than the grid we can ensure there is a visual space
    // between each row
    context.fillRect(this.x, this.y + gridGap / 2, this.size, grid - gridGap);
  }
  // draw a circle sprite. since size is the diameter we need to divide by 2
  // to get the radius. also the x/y position needs to be centered instead of
  // the top-left corner of the sprite
  else {
    context.beginPath();
    context.arc(
      this.x + this.size / 2, this.y + this.size / 2,
      this.size / 2 - gridGap / 2, 0, 2 * Math.PI
    );
    context.fill();
  }
}

const frogger = new Sprite({
  x: grid * 6,
  y: grid * 13,
  color: 'greenyellow',
  size: grid,
  shape: 'circle'
});
const scoredFroggers = [];

// a pattern describes each obstacle in the row
const patterns = [
  // end bank is safe
  null,

  // log
  {
    spacing: [2],      // how many grid spaces between each obstacle
    color: '#c55843',  // color of the obstacle
    size: grid * 4,    // width (rect) / diameter (circle) of the obstacle
    shape: 'rect',     // shape of the obstacle (rect or circle)
    speed: 0.75        // how fast the obstacle moves and which direction
  },

  // turtle
  {
    spacing: [0,2,0,2,0,2,0,4],
    color: '#de0004',
    size: grid,
    shape: 'circle',
    speed: -1
  },

  // long log
  {
    spacing: [2],
    color: '#c55843',
    size: grid * 7,
    shape: 'rect',
    speed: 1.5
  },

  // log
  {
    spacing: [3],
    color: '#c55843',
    size: grid * 3,
    shape: 'rect',
    speed: 0.5
  },

  // turtle
  {
    spacing: [0,0,1],
    color: '#de0004',
    size: grid,
    shape: 'circle',
    speed: -1
  },

  // beach is safe
  null,

  // truck
  {
    spacing: [3,8],
    color: '#c2c4da',
    size: grid * 2,
    shape: 'rect',
    speed: -1
  },

  // fast car
  {
    spacing: [14],
    color: '#c2c4da',
    size: grid,
    shape: 'rect',
    speed: 0.75
  },

  // car
  {
    spacing: [3,3,7],
    color: '#de3cdd',
    size: grid,
    shape: 'rect',
    speed: -0.75
  },

  // bulldozer
  {
    spacing: [3,3,7],
    color: '#0bcb00',
    size: grid,
    shape: 'rect',
    speed: 0.5
  },

  // car
  {
    spacing: [4],
    color: '#e5e401',
    size: grid,
    shape: 'rect',
    speed: -0.5
  },

  // start zone is safe
  null
];

// rows holds all the sprites for that row
const rows = [];
for (let i = 0; i < patterns.length; i++) {
  rows[i] = [];

  let x = 0;
  let index = 0;
  const pattern = patterns[i];

  // skip empty patterns (safe zones)
  if (!pattern) {
    continue;
  }

  // allow there to be 1 extra pattern offscreen so the loop is seamless
  // (especially for the long log)
  let totalPatternWidth =
    pattern.spacing.reduce((acc, space) => acc + space, 0) * grid +
    pattern.spacing.length * pattern.size;
  let endX = 0;
  while (endX < canvas.width) {
    endX += totalPatternWidth;
  }
  endX += totalPatternWidth;

  // populate the row with sprites
  while (x < endX) {
    rows[i].push(new Sprite({
      x,
      y: grid * (i + 1),
      index,
      ...pattern
    }));

    // move the next sprite over according to the spacing
    const spacing = pattern.spacing;
    x += pattern.size + spacing[index] * grid;
    index = (index + 1) % spacing.length;
  }
}

// game loop
function loop() {
  requestAnimationFrame(loop);
  context.clearRect(0,0,canvas.width,canvas.height);

  // draw the game background
  // water
  context.fillStyle = '#000047';
  context.fillRect(0, grid, canvas.width, grid * 6);

  // end bank
  context.fillStyle = '#1ac300';
  context.fillRect(0, grid, canvas.width, 5);
  context.fillRect(0, grid, 5, grid);
  context.fillRect(canvas.width - 5, grid, 5, grid);
  for (let i = 0; i < 4; i++) {
    context.fillRect(grid + grid * 3 * i, grid, grid * 2, grid);
  }

  // beach
  context.fillStyle = '#8500da';
  context.fillRect(0, 7 * grid, canvas.width, grid);

  // start zone
  context.fillRect(0, canvas.height - grid * 2, canvas.width, grid);

  // update and draw obstacles
  for (let r = 0; r < rows.length; r++) {
    const row = rows[r];

    for (let i = 0; i < row.length; i++) {
      const sprite = row[i]
      sprite.x += sprite.speed;
      sprite.render();

      // loop sprite around the screen
      // sprite is moving to the left and goes offscreen
      if (sprite.speed < 0 && sprite.x < 0 - sprite.size) {

        // find the rightmost sprite
        let rightMostSprite = sprite;
        for (let j = 0; j < row.length; j++) {
          if (row[j].x > rightMostSprite.x) {
            rightMostSprite = row[j];
          }
        }

        // move the sprite to the next spot in the pattern so it continues
        const spacing = patterns[r].spacing;
        sprite.x =
          rightMostSprite.x + rightMostSprite.size +
          spacing[rightMostSprite.index] * grid;
        sprite.index = (rightMostSprite.index + 1) % spacing.length;
      }

      // sprite is moving to the right and goes offscreen
      if (sprite.speed > 0 && sprite.x > canvas.width) {

        // find the leftmost sprite
        let leftMostSprite = sprite;
        for (let j = 0; j < row.length; j++) {
          if (row[j].x < leftMostSprite.x) {
            leftMostSprite = row[j];
          }
        }

        // move the sprite to the next spot in the pattern so it continues
        const spacing = patterns[r].spacing;
        let index = leftMostSprite.index - 1;
        index = index >= 0 ? index : spacing.length - 1;
        sprite.x = leftMostSprite.x - spacing[index] * grid - sprite.size;
        sprite.index = index;
      }
    }
  }

  // draw frogger
  frogger.x += frogger.speed || 0;
  frogger.render();

  // draw scored froggers
  scoredFroggers.forEach(frog => frog.render());

  // check for collision with all sprites in the same row as frogger
  const froggerRow = frogger.y / grid - 1 | 0;
  let collision = false;
  for (let i = 0; i < rows[froggerRow].length; i++) {
    let sprite = rows[froggerRow][i];

    // axis-aligned bounding box (AABB) collision check
    // treat any circles as rectangles for the purposes of collision
    if (frogger.x < sprite.x + sprite.size - gridGap &&
        frogger.x + grid - gridGap > sprite.x &&
        frogger.y < sprite.y + grid &&
        frogger.y + grid > sprite.y) {
      collision = true;

      // reset frogger if got hit by car
      if (froggerRow > rows.length / 2) {
        frogger.x = grid * 6;
        frogger.y = grid * 13;
      }
      // move frogger along with obstacle
      else {
        frogger.speed = sprite.speed;
      }
    }
  }

  if (!collision) {
    // if fogger isn't colliding reset speed
    frogger.speed = 0;

    // frogger got to end bank (goal every 3 cols)
    const col = (frogger.x + grid / 2) / grid | 0;
    if (froggerRow === 0 && col % 3 === 0 &&
        // check to see if there isn't a scored frog already there
        !scoredFroggers.find(frog => frog.x === col * grid)) {
      scoredFroggers.push(new Sprite({
        ...frogger,
        x: col * grid,
        y: frogger.y + 5
      }));
    }

    // reset frogger if not on obstacle in river
    if (froggerRow < rows.length / 2 - 1) {
      frogger.x = grid * 6;
      frogger.y = grid * 13;
    }
  }
}

// listen to keyboard events to move frogger
document.addEventListener('keydown', function(e) {
  // left arrow key
  if (e.which === 37) {
    frogger.x -= grid;
  }
  // right arrow key
  else if (e.which === 39) {
    frogger.x += grid;
  }

  // up arrow key
  else if (e.which === 38) {
    frogger.y -= grid;
  }
  // down arrow key
  else if (e.which === 40) {
    frogger.y += grid;
  }

  // clamp frogger position to stay on screen
  frogger.x = Math.min( Math.max(0, frogger.x), canvas.width - grid);
  frogger.y = Math.min( Math.max(grid, frogger.y), canvas.height - grid * 2);
});

// start the game
requestAnimationFrame(loop);
</script>
</body>
</html>
# Matching game
<html>
<head>
    <title>Frog Memory Match Game</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        .memory-game {
            display: grid;
            grid-template-columns: repeat(4, 100px);
            grid-gap: 10px;
        }

        .memory-card {
            width: 100px;
            height: 100px;
            background-color: #2196F3;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            user-select: none;
        }

        .matched {
            background-color: #4CAF50;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div class="memory-game" id="memory-game"></div>

    <script>
        const memoryGame = document.getElementById("memory-game");
        const frogs = [
            '🐸', '🐸', '🐢', '🐢', '🐍', '🐍', '🐊', '🐊',
            '🦎', '🦎', '🦖', '🦖', '🦗', '🦗', '🐛', '🐛'
        ];
        const shuffledFrogs = frogs.sort(() => 0.5 - Math.random());
        let firstCard = null;
        let secondCard = null;
        let canFlip = true;

        function createCard(frog) {
            const card = document.createElement('div');
            card.classList.add('memory-card');
            card.textContent = frog;
            card.addEventListener('click', flipCard);
            memoryGame.appendChild(card);
        }

        function flipCard() {
            if (!canFlip) return;
            if (!firstCard) {
                firstCard = this;
                firstCard.classList.add('matched');
                return;
            }
            if (this === firstCard) return;
            secondCard = this;
            secondCard.classList.add('matched');
            canFlip = false;

            setTimeout(checkForMatch, 1000);
        }

        function checkForMatch() {
            if (firstCard.textContent === secondCard.textContent) {
                firstCard.removeEventListener('click', flipCard);
                secondCard.removeEventListener('click', flipCard);
            } else {
                firstCard.classList.remove('matched');
                secondCard.classList.remove('matched');
            }

            firstCard = null;
            secondCard = null;
            canFlip = true;

            if (document.querySelectorAll('.memory-card.matched').length === frogs.length) {
                alert('Congratulations! You matched all the frogs!');
            }
        }

        shuffledFrogs.forEach(createCard);
    </script>
</body>
</html>

# Flash cards
<!DOCTYPE html>
<html>
<head>
    <title>Frog Flash Cards</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            text-align: center;
            margin: 0;
            padding: 0;
        }

        #flash-cards-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }

        .flash-card {
            width: 200px;
            height: 120px;
            background-color: #fff; /* White background for the flash card */
            border: 1px solid #ccc;
            margin: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: transform 0.2s ease-in-out;
            position: relative;
            border-radius: 5px;
        }

        .flash-card:hover {
            transform: scale(1.05);
        }

        .front, .back {
            background-color: #fff; /* White background for both sides */
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            text-align: center;
            padding: 10px;
        }

        .front {
            color: #000; /* Black text color */
            border-radius: 5px;
        }

        .back {
            color: #000; /* Black text color */
            display: none;
        }

        h3 {
            font-size: 20px;
            margin: 0;
            padding: 5px;
        }

        p {
            font-size: 14px;
            margin: 0;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div id="flash-cards-container"></div>

    <script>
        const flashCardsContainer = document.getElementById("flash-cards-container");

        // Fetch data from your backend API
        fetch('https://projectsailbackend.stu.nighthawkcodingsociety.com/api/frog-items/') // Replace with your actual API endpoint
            .then(response => response.json())
            .then(data => {
                data.forEach(frog => {
                    const flashCard = document.createElement("div");
                    flashCard.className = "flash-card";
                    flashCard.innerHTML = `
                        <div class="front">
                            <h3>${frog.name}</h3>
                        </div>
                        <div class="back">
                            <p>Prey: ${frog.prey}<br>Predators: ${frog.predators}</p>
                        </div>
                    `;
                    flashCardsContainer.appendChild(flashCard);

                    flashCard.addEventListener("click", () => {
                        flashCard.querySelector(".front").style.display = "none";
                        flashCard.querySelector(".back").style.display = "block";
                    });

                    flashCard.addEventListener("mouseleave", () => {
                        flashCard.querySelector(".front").style.display = "block";
                        flashCard.querySelector(".back").style.display = "none";
                    });
                });
            })
            .catch(error => console.error(error));
    </script>
</body>
</html>

Pseudo notes

# Variables and Data Types

  • Variables are used to store data in a program.
  • They can hold different types of information, such as numbers, strings, or booleans.
# Structure
<VariableName> <- <Value>
# Example
Age <- 40
Name <- "Bob Joe"

Input and Output

  • Input allows a program to receive data from a user.
  • Output allows a program to display information to the user.

Conditional Statements (IF-ELSE)

  • Conditional statements allow a program to make decisions based on certain conditions.
  • IF-ELSE statements execute different code blocks based on whether a condition is true or false.
# Structure
IF <Condition> THEN
    <CodeBlock1>
ELSE
    <CodeBlock2>
ENDIF
# Example
IF Age > 18 THEN
    Output "You are an adult"
ELSE
    Output "You are a minor"
ENDIF

Loops (FOR)

  • Loops allow a program to repeatedly execute a block of code.
  • FOR loops are used when the number of iterations is known beforehand.
# Structure
WHILE <Condition>
    <CodeBlock>
ENDWHILE
# Example
WHILE Age < 30
    Output "Happy Birthday!"
    Age <- Age + 1
ENDWHILE

Arrays

  • Arrays are used to store multiple pieces of data under a single variable name.
  • Elements in an array can be accessed using their index.
# Structure
Array <Name> [<Size>]

# Example
Array Numbers[5]
Numbers[0] <- 10
Numbers[1] <- 20

Functions

  • Functions are blocks of reusable code that perform a specific task.
  • They can accept parameters (inputs) and return a value (output).
# Structure
FUNCTION <Name>(<Parameters>)
    <CodeBlock>
    RETURN <Value>
ENDFUNCTION

# Example
FUNCTION Add(a, b)
    RETURN a + b
ENDFUNCTION

Result <- Add(10, 20)

Comments

  • Comments are used to add human-readable explanations to code.
  • They are not executed by the program and are ignored by the compiler or interpreter.
# Structure
// This is a comment
# Example
// This function adds two numbers
FUNCTION Add(a, b)
    RETURN a + b
ENDFUNCTION

Student Teaching

Developing Algorithms

Developing algorithms is a fundamental skill in computer science and problem-solving. An algorithm is a well-defined step-by-step procedure or set of rules used to solve a specific problem or accomplish a task. The process of creating algorithms involves several key steps and considerations:

Understanding the Problem

Before designing an algorithm, it’s crucial to thoroughly understand the problem you intend to solve. This includes defining the problem’s scope, gathering relevant information, and specifying the input data, desired output, and any constraints or requirements.

Code Implementation

Once you have a well-designed algorithm, you can implement it in your preferred programming language. In Python, you can use the def keyword to define functions that encapsulate the algorithm’s logic. Follow best coding practices and add comments to improve code readability.

Data Abstraction

Data abstraction is a programming concept that involves hiding the complex details of how data is stored and manipulated while providing a simplified interface for interacting with that data. This concept is achieved through the use of classes and objects in Python.

Algorithms and Simulations

Algorithms are step-by-step procedures used to solve specific problems or accomplish tasks efficiently. They play a fundamental role in computer science, mathematics, and various other fields. Algorithms are essential for structured problem-solving and have applications in a wide range of areas.

Simulations involve using algorithms to model and analyze real-world processes or systems. In simulations, algorithms are employed to observe how a system behaves under different conditions. Simulations are widely used in fields such as computer science, engineering, and social sciences for experimentation and analysis.

Python is a versatile tool for both algorithm development and simulations, as it allows you to implement and test algorithms and models for a wide variety of scenarios.

These topics are fundamental in programming, and a solid understanding of them can greatly enhance your ability to develop efficient algorithms, work with data, make decisions, create simulations, and utilize data abstraction in Python or any other programming language.

College Board Study Guide

1. Data Representation

Binary, Decimal, Hexadecimal:

  • Binary: A base-2 numbering system (0 and 1).
  • Decimal: A base-10 numbering system (0 to 9).
  • Hexadecimal: A base-16 numbering system (0 to 9, A to F representing 10 to 15).

Conversion between Number Systems:

  • Binary to Decimal: Each bit position represents a power of 2.
  • Decimal to Binary: Divide the decimal number by 2 and keep track of remainders.
  • Hexadecimal to Decimal: Similar to binary but using base 16.
  • Decimal to Hexadecimal: Divide the decimal number by 16, keep track of remainders, and convert remainders greater than 9 to corresponding letters (A, B, C, D, E, F).

Bitwise Operations (AND, OR, XOR, NOT):

  • AND: 1 if both bits are 1, otherwise 0.
  • OR: 1 if at least one bit is 1, otherwise 0.
  • XOR: 1 if only one of the bits is 1, otherwise 0.
  • NOT: Flips the bits (0 becomes 1, 1 becomes 0).

2. Compression and Encryption

Data Compression Purpose and Methods:

  • Purpose: Reduce storage space or transmission time of data.
  • Methods: Lossless (no data loss) and lossy (some data loss).

Compression Algorithms (e.g., Huffman Coding):

  • Huffman Coding: Variable-length encoding based on frequency of characters. More frequent characters have shorter codes.

Data Encryption Purpose and Methods:

  • Purpose: Secure data from unauthorized access.
  • Methods: Symmetric key (same key for encryption and decryption) and asymmetric key (public and private keys).

Encryption Algorithms (e.g., AES, RSA):

  • AES (Advanced Encryption Standard): Symmetric key encryption widely used.
  • RSA: Asymmetric key encryption for secure communication and digital signatures.

3. Error Detection and Correction

Parity Bits for Error Detection:

  • Parity bit added to ensure even or odd number of 1s in a binary sequence.
  • Used for detecting errors in transmission.

Error Correction Techniques (e.g., Hamming Code):

  • Hamming Code: Adds extra bits for error detection and correction.

4. Digital Logic and Circuits

Logic Gates and Truth Tables:

  • AND Gate: Outputs 1 only when both inputs are 1.
  • OR Gate: Outputs 1 when at least one input is 1.
  • NOT Gate: Outputs the opposite of the input.
  • NAND, NOR, XOR Gates: Combinations of basic gates with specific logic.

Digital Circuit Components:

  • Flip-Flops: Sequential logic components that store binary information. They can be used as memory elements.
  • Multiplexers (MUX): A data selector used to route data from multiple sources to a single output.

Boolean Algebra:

  • Laws (e.g., Associative, Commutative, Distributive): Rules governing operations in Boolean algebra.
  • Theorems (e.g., De Morgan’s laws): Equivalences used for simplification.
  • Simplification Techniques (e.g., Karnaugh Maps): Graphical method to simplify Boolean expressions.

5. Boolean Algebra

Laws and Theorems of Boolean Algebra:

  • Idempotent Law: A OR A = A, A AND A = A.
  • Absorption Law: A OR (A AND B) = A, A AND (A OR B) = A.
  • Complement Law: A OR (NOT A) = 1, A AND (NOT A) = 0.

Simplifying Boolean Expressions:

  • Algebraic Simplification: Using Boolean algebra laws and theorems to simplify expressions.
  • Karnaugh Maps: A graphical method for simplification of Boolean expressions with fewer variables.

6. CPU Architecture

Components of a CPU:

  • ALU (Arithmetic Logic Unit): Performs arithmetic (addition, subtraction) and logical (AND, OR) operations.
  • Registers: Small, fast storage locations within the CPU used for temporary data storage.
  • Control Unit: Coordinates operations and manages the fetch-decode-execute cycle.

Fetch-Decode-Execute Cycle:

  • Fetch: The CPU fetches the next instruction from memory.
  • Decode: The CPU interprets the instruction and prepares to execute it.
  • Execute: The CPU carries out the instruction.

7. Memory

Types of Memory:

  • RAM (Random Access Memory): Volatile memory that stores data that is actively being used or processed by the computer.
  • ROM (Read-Only Memory): Non-volatile memory that contains firmware or permanent instructions.

Cache Memory:

  • Purpose: Stores frequently accessed data to speed up CPU operations.
  • Levels (L1, L2, L3): Different levels of cache, with L1 being closest to the CPU and fastest.

8. Input and Output Devices

Input Devices:

  • Keyboard: A device with keys used to input characters and commands.
  • Mouse: A pointing device used to navigate graphical interfaces.
  • Touchscreen: An input device that allows users to interact with the screen directly.
  • Microphone: Converts sound waves into electrical signals for audio input.

Output Devices:

  • Monitor: Displays visual information generated by the computer.
  • Printer: Produces hard copies of digital documents or images.
  • Speakers: Output audio signals as sound waves for the user to hear.

9. File Systems

File Systems and Data Organization:

  • Hierarchy: Files are organized into directories or folders, which can contain other files or subdirectories.
  • File Attributes: Information associated with a file, such as size, type, and permissions.
  • File Extensions: Typically denote the type or format of a file (e.g., .txt for text files, .jpg for image files).

File Naming Conventions and Permissions:

  • File Naming Rules: Names can include letters, numbers, and special characters, with specific restrictions on length and character usage.
  • Access Permissions (Read, Write, Execute): Determine what actions users can perform on a file (e.g., read-only, read-write).

10. Networking and the Internet

Basic Networking Concepts:

  • IP Addresses: Unique identifiers for devices on a network, allowing for communication.
  • Protocols (e.g., TCP/IP): Rules governing how data is transmitted across a network.

OSI Model and Its Layers:

  • Physical Layer: Concerned with the physical connection between devices.
  • Data Link Layer: Responsible for reliable data transfer across a physical link.
  • Network Layer: Manages routing and addressing to ensure data reaches its destination.
  • Transport Layer: Ensures reliable data transfer between devices.
  • Session Layer: Establishes, manages, and terminates sessions or connections.
  • Presentation Layer: Responsible for data formatting and encryption.
  • Application Layer: Provides network services directly to end users.

11. Cybersecurity

Common Cybersecurity Threats:

  • Malware (e.g., Viruses, Worms, Trojans): Malicious software designed to harm or exploit a system.
  • Phishing: Deceptive techniques used to trick individuals into revealing sensitive information.

Cybersecurity Best Practices:

  • Strong Passwords: Use complex passwords with a combination of letters, numbers, and special characters.
  • Regular Updates and Patches: Keep software, operating systems, and security tools up-to-date.
  • Firewalls and Antivirus Software: Provide essential protection against unauthorized access and malware.

12. Ethical and Social Implications

Ethical Considerations in Technology:

  • Privacy: Protecting individuals’ personal information and data.
  • Intellectual Property: Respecting copyrights and intellectual rights of creators.
  • Security: Ensuring the safety and integrity of digital systems and data.

Impact of Technology on Society:

  • Digital Divide: Unequal access to technology and information.
  • Automation and Employment: Consideration of the effects of automation on jobs and employment trends.

Summary of what I learned in Trimester 1 and problems I had

  1. Problems
    • For the passion project, we already started off behind since we did our team test so much later than we should of, causing us to be very behind
    • Since we were behind we werent sure what each job did and what were meant to do before
    • We had to get rid of ideas that we already had work on as we realized we cant show python code on the site.
    • We had a lot of trouble connecting our front and backend because we could not get the flask link, but we then figured out we had to edit our main.py more
    • We couldn’t seperate the information of each frog before when you clicked on them. But we fixed it by making different permalinks for the .mds and havinjg different functions for the on-click events.
    • We had trouble deploying AWS as the ports were full, to fix this we connected to a CSA port and point towards CSA.
  2. Things I learned and accomplishments
    • Despite our set backs, we still came out with a pretty good final product and our teamwork improved drastically.
    • I learned how to interact with vscode and learnt JS and Python.
    • I know how to make quizzes and flash cards with other apis and backend.
    • I learned how to do frontend and connect it to the backend