teaching machines

CS 145 Lecture 14 – Logic Part Trois

October 3, 2014 by . Filed under cs145, fall 2014, lectures.

Agenda

TODO

Collision Detection

Code

RectangleMover.java

package lecture1003;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.lang.ProcessBuilder.Redirect;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class RectangleMover extends JFrame {
  private Rectangle r1 = new Rectangle(50, 100, 100, 150);
  private Rectangle r2 = new Rectangle(300, 400, 200, 50);
  private Rectangle target;
  private Point downAt;

  public static void main(String[] args) {
    new RectangleMover();
  }

  public RectangleMover() {
    super("Rectangle Mover");
    add(new Panel());
    setSize(1000, 600);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
  }

  class Panel extends JPanel implements MouseListener, MouseMotionListener {
    public Panel() {
      addMouseListener(this);
      addMouseMotionListener(this);
    }
    
    @Override
    public void paintComponent(Graphics g) {
      super.paintComponent(g);

      g.setColor(RectangleUtilities.collides(r1.getMinX(), r1.getMaxX(), r1.getMinY(), r1.getMaxY(),
                                             r2.getMinX(), r2.getMaxX(), r2.getMinY(), r2.getMaxY()) ? Color.RED : Color.BLUE);

      g.fillRect(r1.x, r1.y, r1.width, r1.height);
      g.fillRect(r2.x, r2.y, r2.width, r2.height);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
      downAt = e.getPoint();
      if (r1.contains(e.getPoint())) {
        target = r1;
      } else if (r2.contains(e.getPoint())) {
        target = r2;
      } else {
        target = null;
      }
    }

    @Override
    public void mouseReleased(MouseEvent e) {
      target = null;
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mouseDragged(MouseEvent e) {
      if (target != null) {
        target.translate(e.getPoint().x - downAt.x, e.getPoint().y - downAt.y);
        downAt = e.getPoint();
        repaint();
      }
    }

    @Override
    public void mouseMoved(MouseEvent e) {
    }
  }
}

RectangleUtilities.java

package lecture1003;

public class RectangleUtilities {
  public static boolean collides(double l1, double r1, double b1, double t1,
                                 double l2, double r2, double b2, double t2) {
    boolean isFree = r1 < l2 || r2 < l1 ||
                     t1 < b2 || t2 < b1;
    
    return !isFree;
  }
}

Haiku

on the joy of computing:
Hare wrote ten bad lines
Tortoise wrote one and tested
Tortoise got his fix