Work solutiuons/demo code

Important Notes

All Assignments will be submitted via GitHub classroom. Labs and projects will have their own assignment links, all homeworks should be submitted in the homework repository. Follow the instructions below to set that up.

If you did not receive credit (see a 0 on jupiter) for an assignment that you completed, fill out this form. This includes if you submitted work late for an absence or otherwise. _DO NOT__ fill out this form if the assignment doesn’t appear on jupiter at all.

GitHub Classroom Setup Instructions

  1. Click on the correct link to join the GitHub classroom assignment:
    1. Period 4: https://classroom.github.com/a/Ue4qdoyn
  2. After following that link, click “Accept this assignment”
  3. After ~1 minute (maybe less), refresh the page.
  4. You should see a link that looks something like: https://github.com/stuycs-gh-classrooms/nextcs-work-jonalf
    • The end of that url will differ based on your class period and github username
    • Click on that url.
    • This will create a GitHub repository for you, and add a basic README.md file to it.
  5. You will be taken to the repository page for your work. You will see the contents of README.md, which should display: “Work For NeXtCS” and then “Name: YOUR NAME HERE”.
  6. Edit README.md by clicking on the pencil icon found to the far right of “README.md”
    • Replace “YOUR NAME HERE” with your full name, first then last.
  7. Find the “Commit changes” button and click it.

Git/GitHub Help.

If you need more help with GitHub, look over the following.

  1. The notes page

  • Work 21: You'll Flip Over This

    Due: Thursday 4/18 10:00am

    Submission name: w21_flip

    For this, you will need the ExpressionTreeNode and ExpressionTree classes, which you can get here: https://github.com/nextcs-dw/dwsource/tree/main/Expression

    Reminder: Test Thursday 4/18

    Modify your Expression tree to allow for the following capabilities:

    • When an operator node is selected (via mouse press), it changes to another operation. Cycle through the operations like so: + - * / + ...
    • When a value node is selected, if it is non-zero, change it to zero. If it is zero, change it to an integer in the range [-99, 99]

  • Work 20: Evaluations

    Due: Wednesday 4/17 10:00am

    Submission name: w20_evaluate

    For this, you will need the ExpressionTreeNode and ExpressionTree classes, which you can get here: https://github.com/nextcs-dw/dwsource/tree/main/Expression

    Reminder: Test Thursday 4/18

    Expression Tree Nodes:

    Modify the class so that when an operation node is displayed, it will show the operation and the value directly underneath the operation. Note: processing’s text() function will respect the \n character. toString() should not include extra newlines, since that would make traversals less useful.

    Expression Tree:

    • Modify inOrder() so that it include () where appropriate.
    • Create a new method (and wrapper): float evaluate(ExpressionTreeNode current)
      • If current is an operation node, it should evaluate the operation using the left and right subtrees, and set current.value to that result.
      • It should always return current.value

    Driver:

    Call showStats() in draw(). Modify showStats() so that it evaluates the tree and puts the answer on the left side of the window.

    a20-tree


  • Work 19: Express Yourself!

    Due: Tuesday 4/16 10:00am

    Submission name: w19_expression

    For this, you will need the ExpressionTreeNode and ExpressionTree classes, which you can get here: https://github.com/nextcs-dw/dwsource/tree/main/Expression

    Reminder: Test Thursday 4/18

    Expression Tree Nodes:

    Modify the ExpressionTreeNodeclass as follows:

    • Add a new constructor ExpressionTreeNode(boolean operation, int x, int y)
      • If operation is true, set value to 0 and type to a random int in the range [1, 4].
      • If operation is false set value to a random integer in the range [-99, 99] and type to VALUE.
      • Set the other instance variables as they would be in the other provided constructor.
    • Add a toString() method which should return a String containing:
      • The value if the node is a value node.
      • The correct operation symbol (+ - * /) if the node is an operator node.
    • Change display so that is uses the toString() result when printing nodes.

    Expression Tree:

    Modify makeTree in the ExpressionTree class as follows:

    • Nodes should have a random chance of being operator or value nodes. Use this to determine the randomness:
      • operator = random(1) < float(levels)/numLevels
    • Leaf nodes (nodes at the last possible level of the tree) should always be value nodes, regardless of the random calculation above.
    • Value nodes should not have any child nodes.
    • Operator nodes should always have 2 child nodes.
    • The provided makeTree includes the code for position a node, but does not include any recursive parts (base case or recursive case).

  • Lab 05: Balance

    Due: Monday 4/15 10:00am

    Read the instructions in the code and write the requested code.

    Addition for Friday 4/12

    Add the ability to remove nodes with a mouse right-click with the following:

    • Tree class
      • New wrapper method: void removeNode(TreeNode target)
        • Call removeNode(target, root), do not allow target to be equal to root.
      • New recursive method: void removeNode(TreeNode target, TreeNode current)
        • Remove target from the tree. current starts at root (see wrapper method above), and traverses until target can be removed.
    • Driver File
      • mouseButton is a variable similar to key. It will return LEFT or RIGHT depending on which mouse button is being pressed. Modify mousePressed so that LEFT will add a node below the selected node, and RIGHT will remove the selected node.

  • Work 18: Every Node Counts

    Due: Thursday 4/11 10:00am

    Submission name: w18_treeStats

    For this, you will need the TreeNode and Tree classes, which you can get here: https://github.com/nextcs-dw/dwsource/tree/main/TreeBasic

    Make the following modifications to your Tree class (reminder to keep your base cases to null to make your code simpler):

    • Add wrapper methods for display(), preOrder(), inOrder(), and postOrder().
    • countNodes(TreeNode current)
      • Return the total number of nodes in the tree rooted at current.
      • Also include the wrapper function countNodes()
    • getHeight(TreeNode current)
      • Return the height of the tree rooted at current.
      • Remember that the height may not be the same as the value of numLevels.
      • Also include the wrapper function getHeight()
    • Display the number of nodes and height in setup()

    a18-tree


  • Work 17: Climbing Trees

    Due: Tuesday 4/9 10:00am

    Submission name: w17_traversal

    For this, you will need the TreeNode and Tree classes, which you can get here: https://github.com/nextcs-dw/dwsource/tree/main/TreeBasic

    Make the following modifications to your Tree class:

    • Change makeTree so that left and right subtrees are not always made.
      • This means that makeTree will no longer definitely make trees with a particular height. That is ok.
      • You can decided how likely your program is to generate a subtree. If you’re going to use the same percentage each time, I suggest something at least as large as 60%, otherwise you won’t get very interesting trees. If you want to try something fancier, you could tie the percentage to the current level, where levels closer to the root are more likely to have subtrees than lower levels.
    • Add three methods to the Tree class. preOrder, inOrder, and postOrder. Each should return a String which is the result of doing a pre, in, and post order traversal of a tree. In your driver file, display the traversal results on the screen.

    a17-tree


  • Work 16: Tree's a Crowd

    Due: Monday 4/8 10:00am

    Submission name: w16_tree

    For this, you will need a TreeNode class, which you can get here: https://github.com/nextcs-dw/dwsource/tree/main/NodeStuff

    Create a Tree class with the following elements:

    Instance Variables:

    • TreeNode root
    • int numLevels: The height of the tree

    Methods:

    • Constructor: Tree(int x, int y, int levels)
      • Create a node at (x, y) for the root.
      • Set numLevels to levels
      • Assign root.left and root.right to the return value for makeTree (described below).
    • TreeNede makeTree(int x, int y, int levels)
      • Create a new node at (x, y) with a random character.
        • char(int(random(26)) + 'A')
      • Create a full left subtree with levels-1 levels
      • Create a full right subtree with levels-1 levels
      • When creating a subtree, you want the next level down to be below and to the left/right of (x, y). You can either make these offsets from (x, y) based on constants (i.e. (x-50, y+100)…) or dynamically based on the current level. You may take either approach.
      • If numLevels is 0, return null
    • void display(TreeNode current)
      • Draw the tree rooted at current.

    Main Driver File. Use the following file:

    Tree oak;
    
    
    void setup() {
      size(800, 500);
    
      Oak = new Tree(width/2, 50, 4);
      oak.display(oak.root);
    
    }//setup
    

    a16-tree


  • Lab 04:

    Due: Thursday 4/04 10:00am

    Submission name: DNAnalysis

    Due to some technical difficulties with GitHub, this lab will not a separate GitHub repository. Instead do the following:

    1. Get the starter code: https://github.com/stuycs-gh-classrooms/nextdw-lab03-dna-template/blob/main/DNAnalysis/DNAnalysis.pde
    2. Create a new processing program called DNAnalysis.
    3. Put the DNAnalysis folder in your normal work repository.

    l04-dna


  • Work 15: High-Protein Diet

    Due: Thursday 3/28 10:00am

    Submission name: w15-proteins

    Background Genetics Information

    DNA is made up of strands of nucleotides, of which there are 4 types: adenine, thymine, cytosine and guanine. Because of this, DNA sequences can be represented as strings like this:

    tcgcagctcgaaccactatg
    

    When two strands of DNA match, then adenine is paired with thymine, and cytosine is paired with guanine. So the following two DNA strands match:

     tcgcagctcgaaccactatg
     agcgtcgagcttggtgatac
    

    Generally, DNA is translated into RNA, and then RNA is used to create proteins using amino acids. In DNA, 3 nucleotides together represent a single amino acid. We refer to sequences of 3 nucleotides as codons. Additionally, the sequence atg represents the start of a protein, and taa, tga, and tag represent the end of a protein. We will be working on a processing program to help visualize different information about DNA strands.

    Useful Java Stuff

    • If you want to look at a working version of the previous assignment, check the solutions github repository.
    • indexOf(String sub) is a Java Sting method that returns either:
      • The index of the start of the first occurrence of sub in the calling string.
      • -1 if sub does not appear in the calling string.
    • substring() is a Java String method that returns a portion of a String, as a new String object. There are 2 versions of substring():
      1. s.substring(start)
        • Returns a String made from the characters in s starting at index start and going to the end of s.
      2. s.substring(start, end)
        • Returns a String made from the characters in s starting at index start and ending at index end-1.

    Task at Hand

    Create a copy of your work from yesterday, then add the following methods:

    • intFindProteinEnd(String strand)
      • Returns the index of the first end codon in strand.
      • Returns -1 if there is no end codon in strand.
    • boolean containsProtein(String dna)
      • Returns true if dna contains at least one full exon.
      • For our purposes, a DNA sequence contains an exon if:
        • It has a start codon
        • It has an end codon
        • The number of nucleotides between the start and end is a multiple of 3 (i.e. there are no nucleotides unattached to a codon)
        • It has at least 5 other codons between those 2. (this is not biologically accurate, in reality this is closer to 430 codons).
    • String getProtein(String dna)
      • Returns the first protein-encoding (exon) portion of dna. It should not include the start or end codons.
      • If there are no exons in dna, return the empyt string.

    Here are a series of useful test cases for this assignment:

    println("protein end in [" + protein1 + "] (21): " + findProteinEnd(protein1));
    println("protein end in [" + noProtein0 + "] (-1): " + findProteinEnd(noProtein0));
    println("protein end in [" + noProtein2 + "] (3): " + findProteinEnd(noProtein2));
    
    println("protein in [" + protein0 + "] (true): " + containsProtein(protein0));
    println("protein in [" + protein1 + "] (true): " + containsProtein(protein1));
    println("protein in [" + protein2 + "] (true): " + containsProtein(protein2));
    println("protein in [" + noProtein0 + "] (false): " + containsProtein(noProtein0));
    println("protein in [" + noProtein1 + "] (false): " + containsProtein(noProtein1));
    println("protein in [" + noProtein2 + "] (false): " + containsProtein(noProtein2));
    println("protein in [" + noProtein3 + "] (false): " + containsProtein(noProtein3));
    println("protein in [" + noProtein4 + "] (false): " + containsProtein(noProtein4));
    
    println();
    println("protein in [" + protein0 + "] " + getProtein(protein0));
    

  • Work 14: The Code of Life

    Due: Wednesday 3/27 10:00am

    Submission name: w14_drawDNA

    Background Genetics Information

    DNA is made up of strands of nucleotides, of which there are 4 types: adenine, thymine, cytosine and guanine. Because of this, DNA sequences can be represented as strings like this:

    tcgcagctcgaaccactatg
    

    When two strands of DNA match, then adenine is paired with thymine, and cytosine is paired with guanine. So the following two DNA strands match:

     tcgcagctcgaaccactatg
     agcgtcgagcttggtgatac
    

    Task at Hand

    Using the information above, write the following processing functions:

    • void drawBase(char base, int x, int y, int sz)
      • Draws a single base in a square at (x, y) with side length sz.
      • The squares should have no stroke, and each type of nucleotide should be given a distinct color.
      • The letter for the nucleotide should be displayed within the square in a color that is easy to see.
    • void drawStrand(String dna, int x, int y, int sz)
      • Draws the entire dna strand starting at (x, y) using sz for the size of each square.
      • This method should call drawBase().

      a06_drawStrand

    • boolean strandMatch(String strand0, String strand1)
      • Returns true if strand0 and strand1 match as described above.
    • void strandCompare(String strand0, String strand1, int x, int y, int sz)
      • Draws strand0 directly above strand1.
      • If there is a nucleotide mismatch, draw a red border around the nucleotide.

      a06_strandCompare

    • Write a setup() method that tests these methods.

  • Work 13: What a Bunch of Characters

    Due: Thursday 3/21 10:00am

    Submission name: w13_drawChar

    Write a processing program with the following functions

    color charToColor(char c)

    • Create and return a color based on the value of c as follows:
    • Multiply c by 23, 41 and 67, respectively to to get red, green and blue values (you could use other numbers, but small, relatively prime numbers work best).
    • Don’t forget to make sure each color is within the range [0, 255]

    void drawChar(char c, int x, int y)

    • Draw a square using the color from charToColor() at the given x and y location, using c as the side length.
    • Set textSize to the value of c.
    • Display c as a character inside the square.

    setup()

    • Set the screen size to 600x400
    • Using a for loop controlled by a char variable, loop through the chars from 'A' to 'Z', calling drawChar() appropriately. Set x and y values as you see fit.

    Reference Image:

    abcs.png


  • Project 00: May The Force(s) Be With You

    Due: Multiple Due Dates

    Project Description

    Your mission is to destroy the Death Star create a Processing program that demonstrates different physical forces, building off of the framework we have been creating in class. Your program should do the following:

    • Reasonably model gravity (in the classical mechanics sense), drag, and the spring force. The force calculations for both have already been done in class.
    • Add one more force. The force can be rooted in reality, or something of your own invention. Regardless, calculating the force should involve some combination of an orbs mass, velocity, acceleration and external factors (which may be another orb). Calculating the force should work the same way as the others, by adding a method that returns a PVector to the Orb class.
    • Add the ability to toggle on/off the wall bouncing behavior (which has been built in to all our physics programs from the start).
    • Use both an array and a linked list amongst different simulations.
    • Produce different simulations as follows:
      • A demonstration of gravity showing “planets” orbiting a central massive body. This one should use an array of orbs with a fixed central orb.
      • A demonstration of the spring force that includes at least 1 non moving orb. This should use a linked list of orbs.
      • A demonstration of drag that involves at least 2 or more orbs moving through at least 2 areas with different drag results.
      • A demonstration that combines at least 3 of the forces.

    Interface Requirements

    Your program should be able to visually indicate:

    • Whether movement is on/off
    • Whether bouncing is on/off
    • Which force(s) are currently being applied. Your program should respond to the following keyboard commands:
    • ' ': movement on/off
    • 'b': wall bouncing on/off
    • '1': Setup simulation 1 (orbital gravity)
    • '2': Setup simulation 2 (spring)
    • '3': Setup simulation 3 (drag)
    • '3': Setup simulation 4 (custom)
    • '3': Setup simulation 5 (combination)

    Phase 0 - Analyze & Plan

    Due: Monday, 3/18 10:00am

    Fill in the README.md file created when you make your repository.

    Phase 1 - Demos & Feedback

    Due: Tuesday, 3/26 10:00am

    In class on Monday, you should have a program that performs at least 3 of your proposed simulations. During class, other students will have a chance to run your code and provide feedback, so it is important that your project is in a state where it can work. More details on the logistics of theses demos will be published Tuesday.

    Phase 2 - Finished Version & Documentations

    Due: Tuesday, 4/2 10:00am

    Instructions to follow By this time your repository should have the final version of your program. You will also need to complete a document describing your project use this template to create a file in your repository called FINAL.md.

    Your completed repository should have the following parts:

    • README.md: Your design document.
    • FINAL.md: Your project summary document (described above).
    • Processing Program Folder
      • Make sure all of your code files have the .pde extension are in a folder with the same name as your driver file (i.e. a normal processing program folder.).

  • Lab 03: Node Springs

    Due: Friday 3/15 10:00am

    Read the instructions in the code and write the requested code.


  • Work 12: Noddeing Off

    Due: Wednesday 3/13 10:00am

    Submission name: w12_orbnodes

    We will continue with the work started in class on using a node based Orb structure.

    • Start with the program developed in class.

    • Add the following to the driver file (it should still do all the things from the previous assignment).

      • The ability to calculate and apply earthGravity if that option is on.
      • The ability to add a random node to the front of the chain when '=' is pressed.
      • The ability to remove the front node of the chain when '-' is pressed.
      • For adding and removing, you may assume there is always at least 1 node.

  • Work 11: Nodular Design

    Due: Tuesday 3/12 10:00am

    Submission name: w11_orbnodes

    We will continue with the work started in class on using a node based Orb structure.

    • Start with the program developed in class.

    • OrbNode should also have the following methods
      • void display(int springLength)
        • Display the OrbNode.
        • If there is a next node, draw a line between this and the next OrbNode objects.
        • Make the color of the line related to the state of the spring (extended, compressed, neither).
      • void applySprings(int springLength, float springK)
        • Apply the spring force between the calling Orb and it’s next and previous neighbors when applicable.
    • Write a driver file that creates at least 3 OrbNodes and connects them. Then in draw
      • Use a while loop to display each OrbNode
      • Use a while loop to call applySprings on each OrbNode
      • Use a while loop to call run on each OrbNode
      • These loops should not be integer-counter based.

    Reference Image:

    a11-nodes


  • Lab 02: Spring Ahead!

    Due: Monday 3/11 10:00am

    Read the instructions in the code and write the requested code.

    ADDITION FRIDAY!!!

    Once you have the lab working, add the following features:

    • When the - key is pressed, the last Orb in the array should be removed.
      • This action does not need to change the size of the Orb array.
      • This should not change the functionality of the rest of the program.
      • If the Orb array is empty, there should be no action (otherwise you’ll get a NullPointerException).
    • When the = key is pressed, a new Orb should be added at the end of the chain of Orbs.
      • This may or may not require you to “expand” the Orb array. (arrayCopy(link)) can assist you here.
      • Be careful, as the end of the chain of the orbs may not be the last spot in the Orb array.

  • Work 10: Spring into Action

    Due: Thursday 3/7 10:00am

    Submission name: w10_spring

    Add Spring

    Add the method PVector getSpring(Orb o, int springLength, float springConstnat)

    • This should calculate the force of a spring between the calling object and o.
    • The resulting force should pull the calling object towards o if the spring is extended past springLength and should push the calling object away from o if the spring is compressed to be less than springLength.

    Create a driver file that tests the spring force. A single FixedOrb and regular Orb will suffice.

    Relevant Physics to find the force a spring connecting \(A\) to \(B\), where \(B\) is a fixed point:

    • \[F = kx\hat{AB}\]
    • Where \(k\) is the spring constant,
    • \(x\) is the displacement, or difference of the distance between \(A\) and \(B\) and the length of the spring.
    • \(\hat{AB}\) is the normalized vector from \(A\) to \(B\).

  • Work 09: Massive Changes

    Due: Tuesday 3/5 10:00am

    Submission name: w09_mass

    Add Drag

    Start with the code from class today (source code page will be updated by the end of class). BEfore doing anything, it should have a collection of Orb objects exerting a gravitational force on each other. Currently the “mass” of our Orb objects is tied to the size. We will separate those two by adding a float mass field to the Orb class. You will need the following changes:

    • Add float mass as a field to Orb.
    • Modify the parameter based constructor to take a float parameter for the mass.
    • Modify the default constructor to set the mass to a random value in the range [10, 100).
    • Modify the color so that it scales with the density (mass/size) of the Orb. The most dense orbs should be black and the least dense should be whatever original color you set (in my example this is (0, 255, 255)). You should look at the lerpColor (link) function in processing to help.

    Reference Image:

    a09-mass


  • Work 08: What a Drag

    Due: Wednesday 2/28 10:00am

    Submission name: w08_drag

    Calculate Drag

    Drag is a force that “pushes” opposite to velocity. In order to calculate the drag force we need to figure out the direction it will apply and the magnitude of the force. The (simplified) Formula for Drag is:

    \[{\overrightarrow F} = -\dfrac{1}{2} v^2 C_d {\hat v}\]

    What is this?

    • \(v\) Is the magnitude of the velocity vector. Luckily, we can get the magnitude using velocity.mag(), which returns a float value.
    • \(C_d\) is the coefficient of drag, this is different depending on the material (air, water, honey…).
    • \({\hat v}\) is the normalized velocity vector. This has the same direction as the velocity vector, but the magnitude is 1. Once again, we have a nice method for this. vector.normalize() will normalize a vector (it will modify vector, so don’t do this directly on velocity).

    Add Drag

    Start with the work from yesterday (but make a new sketch and submission). Add drag to your simulation as follows:

    • Add PVector getDragForce(float coef) to the Orb class. It should calculate and return a PVector representing drag as described above.
    • draw()
      • When an Orb reaches a height of 200 or more, calculate and apply a drag force.
      • Draw a rectangle from (0, 200) that takes up the lower half of the screen to help see when the drag force should be applied.

    Reference Image:

    a08-drag


  • Work 07: That's Not How the Force Works

    Due: Wednesday 2/28 10:00am

    Submission name: w07_forcerunner

    Use the Force

    Start with the code developed in class. You will modify the driver file to produce a more complex simulation as follows:

    • Create an array of Orb objects.
    • Create two forces as PVector objects, gravity and wind.
    • Add a boolean variable moving that will control whether the simulation is runnogn or not.
    • setup()
      • Make the gravity and wind forces <0, 0>.
      • Create at least 5 Orb objets. They should all have the same y coordiante, x values that keep them from overlapping and random sizes in the range [10, 60).
    • draw()
      • Display all the Orb objects in the array.
      • Display the current values of the gravity and wind forces.
      • If moving is true, apply gravity and wind to all the Orb objects, then call run() on each.
    • keyPressed()
      • Left/Right arrows: Change the x direction of wind in 0.1 incriments.
      • Up/Down arrows: Change the y direction of gravity in 0.1 incriments.
      • Space: Toggle moving on/off.

    Reference Image:

    a07-force


  • Lab 01: Fill Up Your Tanks

    Due: Friday 2/16 10:00am

    Over the next few days we’ll be expanding our Aquarium programs. Start by creating a new repository with the link below and following the instructions in the README.md file.

    Full Assignment Guidelines

    For this lab, you will have a driver file, Tank class, Animal subclass and at least 4 subclasses of Animal. Guidelines below:

    • Driver file
      • When the program is run, initialize and empty Tank.
      • In draw() display the Tank and have it call whatever method you’ve created that will run the simulation.
      • Users should be able to add new Animal subclass objects to the tank with the number keys 1-0, each key should map to a different subclass. The Animal should be placed at the current coordinates of the mouse.
    • Animal class general requirements
      • All animals should be able to be displayed on the screen.
      • All animals should be able to move about the tank.
      • NEW all animals should have some way to die. Options discussed in class are:
        • Needing a certain amount of food, with food being added somehow in the driver (possible mouse click).
        • Needing a certain amount of food, but the food comes from eating other (smaller) animals.
        • A combination of both of theses, or something else.
    • Subclasses
      • Each subclass should differ at a minimum by:
        • How they look.
        • How they move.
        • At least one subclass should have a different death mechanism from the other three.
      • Tank class
        • Have defined water and floor areas.
        • Hold all the animals in an ArrayList<Animal> instance variable.
        • Have a method that displays all the animals.
        • Have a method that runs the simulation, which may include movement and eating/death in one, or may be split up into multiple methods.

  • Work 06: Something Seems Fishy

    Due: Monday 2/12 10:00am

    Submission name: w06_fish

    Make some Fish! (or other animal)

    Create two subclasses of Animal and add them to your program. At a minimum, your subclasses must have different movement behavior and look different. You made add other changes if you have time. One subclass should be an animal that stays in the water area of the tank, the other should stay on the ground area of the tank.

    Using Images (not required!)

    If you want to use small images as the displayed shapes for your subclasses, you can look into the PImage processing class. Specifically the loadimage and image functions. In order to use images, you must put them in a directory called data/ inside your processing sketch folder. Here is a small example that loads and displays and image:

    PImage img;
    img = loadImage("shells.jpg");
    image(img, 0, 0, 25, 50); //the image's corner will be at (0, 0) and the size of the image will be 25x50
    

  • Work 05:

    Due: Friday 2/8 10:00am

    Submission name: w05_aquarium

    Overview

    Over the next few days, we will create an aquarium program. In this program we will have an Tank class, which will contain various subclasses of Animal. When the program is run, we will see the aquarium, and all of the animals in it moving about.

    Design Requirements

    Tank class:

    • Should have a well defined “floor” area visually distinct from the water.
    • Does not necessarily have to take up the entire screen.
    • Should have the ability to store many Animal objects.

    Animal class:

    • You wrote an outline of what an Animal should have yesterday, add the features you believe are necessary, be sure to include the following:
    • All animals should be able to move within the tank.
    • An animal should never move outside the tank.
    • Eventually, we will have subclasses of Animal, but to start, consider what common instance variables and methods would be needed.
    • Remember, since the Tank class will only know that it has Animal objects, it will only be able to use methods from the Animal class.

    There may be other elements to the aquarium as well.

    Build it!

    Write the Tank and Animal classes that at a minimum meet the requirements stated above. You can use the small driver file below, which adds an animal when the mouse is pressed. We will add more to this over the next few days.

    Tank t;
    int tankX = 0;
    int tankY = 50;
    int floorH = 100;
    int tankW;
    int tankH;
    
    
    void setup() {
      size(600, 600);
      tankW = width;
      tankH = height - 50;
      t = new Tank(tankX, tankY, tankW, tankH, floorH);
      t.display();
    }//setup
    
    
    void draw() {
      background(150);
      t.moveAnimals();
      t.display();
    }
    
    void mouseClicked() {
      t.addAnimal(mouseX, mouseY);
    }
    

    a05-tank


  • Work 04: Kingdom Anamalia

    Due: Thursday 2/7 10:00am

    Submission name: w04_aquarium-design.md

    Overview

    Over the next few days, we will create an aquarium program. In this program we will have an Tank class, which will contain various subclasses of Animal (and possibly others). When the program is run, we will see the aquarium, and all of the animals in it moving about.

    Class Design

    In class, we discussed lots of things that can go into our aquarium. Let’s start designing it, focussing on the Animals inside. In a markdown document, including the following:

    • A class hierarchy showing the Animal superclass and the subclasses of it. You may represent this tree using text only, or by draying it and including an image (to add an image to a markdown document: ![image description](path to image), e.g. ![a cat](cat.jpg) just make sure you upload the image as well.
    • A list of the instance variables and methods you believe should go into the Animal superclass.

  • Lab 00: So Many Shapes

    Due: Wednesday 2/07 10:00am

    Read the instructions in the code and write the requested code.

    l00-shapes


  • Work 03: Finding Your Center

    Due: Monday 2/6 10:00am

    Submission name: w03_centroid

    A Little Geomerty:

    The centroid of a polygon is a formulaic way of identifying what we would consider the “center”, which is non-trivial for irregular polygons. To find the centroid you must iterate over all the vertices of the polygon.

    • For each point from 0 to the number of points - 1, take the sum of the following, stored separately (like in sumX and sumY variables):
      • \[(x_{i} + x_{i+1})(x_{i}y_{i+1} - x_{i+1}y_{i})\]
      • \[(y_{i} + y_{i+1})(x_{i}y_{i+1} - x_{i+1}y_{i})\]
      • When i gets to the last point, perform the calculations above replacing \(i + 1\) with 0. That is to say the correct calculation requires the last point to loop back around to the first.
    • Take each of those sums and divide them by 6 times the signed area of the polygon.

    Add Centroid to our Shapes

    With all this in mind, add the following features to the PathShape class from last week:

    • 1 new instance variables:
      • PVector centroid: an array to store the x and y values of the centroid.
    • 1 new method
      • void setCentroid()
        • Sets the centroid instance variable.
    • 2 modified methods
      • display
        • Draws a circle of diameter 5 at the centroid. Use a different color than the inside instance variable.
      • makeRandomShape() or the Constructor
        • call setCentroid() after setArea()

    a03-pathcentroid


  • Work 02: Area, but Harder

    Due: Monday 2/5 10:00am

    Submission name: w02_inherit

    A Little Geomerty:

    The signed area of a polygon is a measure of how much space is enclosed by the shape. For a polygon with non intersecting sides, this is the same as the area, but it is also a measure that can be made for shapes with sides that intersect.

    • The signed area can be found by iterating over the vertices of the polygon. For each point from 0 to the number of points - 1, take the sum of the following (this is known as the shoelace formula).
      • sum+= \((x_{i} y_{i+1} - x_{i+1}y_{i})\)
      • When i gets to the last point, perform the calculations above replacing \(i + 1\) with 0. That is to say the correct calculation requires the last point to loop back around to the first.
      • At then end, take the cumulative sum and divide it by 2, this is the signed area.

    Add Area to our Shapes

    First, get the updated PathShapeDriver code from the source code page (this includes updates from class on Friday). Then add the following:

    • To PathShape
    • New instance variables:
      • float area: stores the signed area.
    • New method:
      • void setArea()
        • Sets the area instance variable as defined above.
    • Modified method:
      • void makeRandomShape()
        • Call setArea() after the points are made.
        • Set inside to magenta (255, 0, 255) if area is less than shapeSize and cyan (0, 255, 255) is area is greater than shapeSize.
    • Verify that the above changes have been added to Polygon, if not, add code to Polygon where needed.

    a02-patharea


  • Work 00: Shaping Your Path

    Due: Thursday 2/1 10:00am

    Submission name: w00_pathShape

    Step 0: Create your new work repository:

    Use this link: https://classroom.github.com/a/Ue4qdoyn

    Step 1: Code!

    Create a class called PathShape. A PathShape will represent a shape made by connecting a series of points that will be contained in a square area (but may not take up the entire area).

    A PathShape will have the following instance variables:

    • ArrayList<PVector> points; An ArrayList of PVector objects representing the vertices of the PathShape.
      • You can see more about PVectors here but at the moment, we only need to use the fact that they have x and y instance variables.
    • int numPoints: The total number of vertices the shape should have.
    • PVector corner: (x, y) position of thew top-left area that will contain the shape.
    • int ShapeSize: The side length of the suqare area that will contain the shape.
    • color inside: The fill color for the shape.

    And the following methods:

    • PathShape(int np, int cx, int cy, int ss):
      • Set numPoints to np.
      • Sets the corner to (cx, cy).
      • Sets shapeSize to ss.
      • Sets inside to a color of your chosing.
      • Initializes points and calls makeRandomShape() (see below).
    • void makeRandomShape()
      • Adds np random points to points by calling makeRandomPoint()
      • The shape need not be a polygon.
    • PVector makeRandomPoint()
      • Returns a new PVector object where the x and y values will always be within the square area that defines the calling PathShape object.
    • display()
      • Use beginShape, vertex and endshape to draw the PathShape on the processing screen.
      • The shape use the instance variable colors accordingly.
      • The shape should be closed, so that last point should connect to the first.

    Create a drive file that will create 4 PathShape objects to be displayed in a grid like so:

    a00-pathgrid


  • Work 00: Getting to Know You

    Due: Monday 09/11 10:00am

    1. Please fill out the student info form found here: https://forms.gle/xkZ9kjw2kEjd6MuWA
    2. You will need a GitHub account in order to submit work for this class. If you don’t have one already, go to https://github.com/ and create one.
      • If you attach it to your stuy.edu email address, you can sign up for the GitHub Student Developer Pack. It includes access to a bunch of programming tools/services. It is not required that you sign up for it.
    3. Read and acknowledge the Stuyvesant Computer Science Lab and Network Usage Policy
    4. Download & install Processing.
      • Make sure to install version 4.3 for your appropriate operating system (OS).