teaching machines

CS 1: Lecture 23 – Loops, Part 5

November 1, 2017 by . Filed under cs1, cs145, cs148, fall 2017, lectures.

Dear students,

Here’s your TODO list to complete before we meet again:

See you next class!

Sincerely,

P.S. It’s time for a haiku!

i went on and on
not knowing y exactly
until i met u

P.P.S. Here’s the code we wrote together in class…

Alliterative.java

package lecture1101;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Alliterative {
  public static void main(String[] args) throws FileNotFoundException {
    File file = new File("/Users/johnch/Desktop/wisconsin.txt");
    Scanner in = new Scanner(file);
 
    String run = "";
    while (in.hasNext()) {
      String current = in.next();
      
      if (run.startsWith("" + current.charAt(0))) {
        run += " " + current;
      } else {
        if (run.contains(" ")) {
          System.out.println(run);
        }
        run = current;
      }
      
    }
    
    in.close();
  }
}

Linesweeper.java

package lecture1101;

import java.util.Random;
import java.util.Scanner;

public class Linesweeper {
  public static void main(String[] args) {
    String uncovered = getBoard();
    String covered = "----------";

    Scanner in = new Scanner(System.in);

    prompt(covered);
    while (in.hasNextInt()) {
      int i = in.nextInt();
      covered = uncover(covered, uncovered, i);
      prompt(covered);
    }
  }

  private static String uncover(String covered,
                                String uncovered,
                                int i) {
    String newCovered = covered.substring(0, i) +
                        uncovered.charAt(i) +
                        covered.substring(i + 1);
    return newCovered;
  }

  private static void prompt(String board) {
    System.out.println("0123456789");
    System.out.println(board);
    System.out.print("Where? ");
  }

  public static String getBoard() {
    String s = "";
    Random g = new Random();
    for (int i = 0; i < 10; ++i) {
      if (g.nextInt(100) < 30) {
        s += "*";
      } else {
        s += ".";
      }
    }
    return s;
  }
}

GifSequenceWriter.java

package lecture1101;
//  GifSequenceWriter.java

//  
//  Created by Elliot Kroo on 2009-04-25.
//
// This work is licensed under the Creative Commons Attribution 3.0 Unported
// License. To view a copy of this license, visit
// http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative
// Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.

import javax.imageio.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.image.*;
import java.io.*;
import java.util.Iterator;

public class GifSequenceWriter {
  protected ImageWriter gifWriter;
  protected ImageWriteParam imageWriteParam;
  protected IIOMetadata imageMetaData;
  protected ImageOutputStream outputStream;

  /**
   * Creates a new GifSequenceWriter
   * 
   * @param outputStream
   *          the ImageOutputStream to be written to
   * @param imageType
   *          one of the imageTypes specified in BufferedImage
   * @param timeBetweenFramesMS
   *          the time between frames in miliseconds
   * @param loopContinuously
   *          wether the gif should loop repeatedly
   * @throws IIOException
   *           if no gif ImageWriters are found
   *
   * @author Elliot Kroo (elliot[at]kroo[dot]net)
   */
  public GifSequenceWriter(File outFile,
                           int timeBetweenFramesMS,
                           boolean loopContinuously) {
    try {
      // my method to create a writer
      gifWriter = getWriter();
      imageWriteParam = gifWriter.getDefaultWriteParam();
      ImageTypeSpecifier imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);

      imageMetaData = gifWriter.getDefaultImageMetadata(imageTypeSpecifier, imageWriteParam);

      String metaFormatName = imageMetaData.getNativeMetadataFormatName();

      IIOMetadataNode root = (IIOMetadataNode) imageMetaData.getAsTree(metaFormatName);

      IIOMetadataNode graphicsControlExtensionNode = getNode(root, "GraphicControlExtension");

      graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
      graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
      graphicsControlExtensionNode.setAttribute("transparentColorFlag", "FALSE");
      graphicsControlExtensionNode.setAttribute("delayTime", Integer.toString(timeBetweenFramesMS / 10));
      graphicsControlExtensionNode.setAttribute("transparentColorIndex", "0");

      IIOMetadataNode commentsNode = getNode(root, "CommentExtensions");
      commentsNode.setAttribute("CommentExtension", "Created by MAH");

      IIOMetadataNode appEntensionsNode = getNode(root, "ApplicationExtensions");

      IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension");

      child.setAttribute("applicationID", "NETSCAPE");
      child.setAttribute("authenticationCode", "2.0");

      int loop = loopContinuously ? 0 : 1;

      child.setUserObject(new byte[] { 0x1, (byte) (loop & 0xFF), (byte) ((loop >> 8) & 0xFF)
      });
      appEntensionsNode.appendChild(child);

      imageMetaData.setFromTree(metaFormatName, root);

      outputStream = new FileImageOutputStream(outFile);
      gifWriter.setOutput(outputStream);
      gifWriter.prepareWriteSequence(null);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public void appendFrame(BufferedImage img) {
    try {
      gifWriter.writeToSequence(new IIOImage(img, null, imageMetaData), imageWriteParam);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Close this GifSequenceWriter object. This does not close the underlying
   * stream, just finishes off the GIF.
   */
  public void close() {
    try {
      gifWriter.endWriteSequence();
      outputStream.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Returns the first available GIF ImageWriter using
   * ImageIO.getImageWritersBySuffix("gif").
   * 
   * @return a GIF ImageWriter object
   * @throws IIOException
   *           if no GIF image writers are returned
   */
  private static ImageWriter getWriter() throws IIOException {
    try {
      Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif");
      if (!iter.hasNext()) {
        throw new IIOException("No GIF Image Writers Exist");
      } else {
        return iter.next();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Returns an existing child node, or creates and returns a new child node (if
   * the requested node does not exist).
   * 
   * @param rootNode
   *          the <tt>IIOMetadataNode</tt> to search for the child node.
   * @param nodeName
   *          the name of the child node.
   * 
   * @return the child node, if found or a new node created with the given name.
   */
  private static IIOMetadataNode getNode(IIOMetadataNode rootNode,
                                         String nodeName) {
    int nNodes = rootNode.getLength();
    for (int i = 0; i < nNodes; i++) {
      if (rootNode.item(i).getNodeName().compareToIgnoreCase(nodeName) == 0) {
        return ((IIOMetadataNode) rootNode.item(i));
      }
    }
    IIOMetadataNode node = new IIOMetadataNode(nodeName);
    rootNode.appendChild(node);
    return node;
  }
}

BouncingBall.java

package lecture1101;

import java.awt.Color;
import java.awt.Desktop;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;

public class BouncingBall {
  public static void main(String[] args) throws IOException {
    GifSequenceWriter out = new GifSequenceWriter(new File("/Users/johnch/Desktop/foo.gif"), 16, true);
  
    BufferedImage image = new BufferedImage(700, 400, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();
    
    double x = 0;
    double y = 52;
    double xVelocity = 3;
    double yVelocity = 7;
    double gravity = 9.8;
    
    for (int t = 0; t < 400; ++t) {
      
      if (y + 20 >= image.getHeight()) {
        yVelocity *= -0.8;
      }
      
      g.setColor(Color.WHITE);
      g.fillRect(0, 0, image.getWidth(), image.getHeight());
      
      g.setColor(Color.BLUE);
      g.fillOval((int) x, (int) y, 20, 20);
      
      x += xVelocity;
      y += yVelocity;
      yVelocity += gravity;

    
      out.appendFrame(image);
    }
    
    out.close();
    
    Desktop desktop = Desktop.getDesktop();
    desktop.browse(URI.create("file:///Users/johnch/Desktop/foo.gif"));
  }
}

Intersection.java

package lecture1101;

import java.awt.Point;

public class Intersection {
  public static void main(String[] args) {
    String s1 = "dinosaur";
    String s2 = "aardvark";
    
    // i1, i2 = find intersection point
    Point p = getIntersection(s1, s2);
    
    // print some stuff
    for (int i = 0; i < p.x; ++i) {
      System.out.printf("%" + (p.y + 1) + "c%n", s1.charAt(i));
    }
    
    System.out.println(s2);
    
    for (int i = p.x + 1; i < s1.length(); ++i) {
      System.out.printf("%" + (p.y + 1) + "c%n", s1.charAt(i));
    }
  }
  
  private static Point getIntersection(String s1,
                                   String s2) {
    for (int i1 = 0; i1 < s1.length(); ++i1) {
      // s1.charAt(i1)
      for (int i2 = 0; i2 < s2.length(); ++i2) {
        // s2.charAt(i2)
        if (s1.charAt(i1) == s2.charAt(i2)) {
          return new Point(i1, i2);
        }
      }
    }
    return null;
  }
}