teaching machines

CS 145 Lecture 14 – Testing and conditionals via collision detection

October 28, 2011 by . Filed under cs145, fall 2011, lectures.


Collision detection

  1. Suppose you have two horizontal line segments in the same line. (Or two pens.) When are they intersecting?
  2. Suppose you have two circles. When are they intersecting?
  3. Suppose you have two rectangles. When are they intersecting?



package lecture;

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

public class CollisionUtilities {

  public static void main(String[] args) throws FileNotFoundException {
    Scanner in = new Scanner(new File("/home/cjohnson/Desktop/lines.txt"));

    while (in.hasNextDouble()) {
      double leftA = in.nextDouble();
      double rightA = in.nextDouble();
      double leftB = in.nextDouble();
      double rightB = in.nextDouble();
      boolean expected = in.nextBoolean();

      boolean actual = isColliding(leftA, rightA, leftB, rightB);
      if (actual != expected) {
        System.out.printf("[%f, %f] vs. [%f, %f] expected: " + expected + ", actual: " + actual + "%n", leftA, rightA, leftB, rightB);


   * Checks whether two 1-D line segments intersect.
   * @param leftA
   * Left bounds of line segment A, assumed < rightA
   * @param rightA
   * Right bounds of line segment A
   * @param leftB
   * Left bounds of line segment B, assumed < rightB
   * @param rightB
   * Right bounds of line segment B
   * @return True if they collide, false otherwise
  public static boolean isColliding(double leftA,
                                    double rightA,
                                    double leftB,
                                    double rightB) {
    return !(leftB > rightA || rightB < leftA);


Test-driven development

Here’s by far the best strategy for writing a method with minimal headache:

  1. Write its specification. What does it need to do? What does it needs from the outside world? What does it give back the outside world?
  2. Write its signature/interface.
  3. Write tests.
  4. Implement it.
  5. Execute your tests.