Skip to content
Jim edited this page Oct 7, 2024 · 74 revisions
image

README

Java

if, else-if, else

  • An if statement lets us conditionally execute a block of code

    if (i == 0) {
        PRINT("i is 0");
    }
  • if (Condition) { Body }

    • Condition: Before running the body, the computer checks this condition (boolean expression)
      • If the condition is true (the if "succeeds"), then the if body is run
      • If the condition is false (the if "fails"), the body is skipped
    • Body: The code inside the curly braces
  • An else provides a "backup plan" if its corresponding if fails

    int i = ...;
    
    if (i == 0) {
        PRINT("i is 0");
    } else if (i == 1) {
        PRINT("i is 1");
    } else {
        PRINT("i is neither 0 nor 1");
    }
  • NOTE: If an if succeeds, its else must be skipped (even if it is actually an else if with a true condition)

    int i = 2;
    
    if (i == 2) {
        PRINT("if i is 2, this line will get printed.");
    } else if (i == 2) {
        PRINT("if i is 2, this line will NOT get printed.");
    }

while

  • A while loops lets us repeat a block of code

    // 1
    // 2
    // 3
    // Boom!
    
    int i = 1;
    while (i < 4) {
        PRINT(i);
        ++i;
    }
    PRINT(Boom!);
  • while (Condition) { Body }

    • Initialization: We often declare and initialize a variable before the loop; this is optional
      • int i = 1; declares an int called i and initializes to 1
    • Condition: Before each iteration of the loop, the computer checks this condition
      • i < 4 tells us whether i is less than 4
        • If the condition is true, the loop body (PRINT(i); ++i;) is run
        • If the condition is false, we exit the loop
    • Body: The code inside the curly braces
    • This cycle—checking the condition and executing the body—continues until the condition is found to be false and the loop exits
  • NOTE: If the condition is never found to be false, the loop will continue running forever (an infinite loop)

    while (true) {
        PRINT("Oh no.");
    }

for

  • A for loop can be more a convenient alternative to a while loop

    // 1
    // 2
    // 3
    // Boom!
    
    for (int i = 1; i < 4; ++i) {
        PRINT(i);
    }
    PRINT("Boom!");
  • for (Initialization; Condition; Update) { Body }

    • Initialization: This is where you usually define and initialize a variable to control the loop
      • int i = 1; declares an int called i and initializes to 1 before the loop starts running
    • Condition: Before each iteration of the loop, the computer checks this condition
      • i < 4 tells us whether i is less than 4
        • If the condition is true, the loop body (PRINT(i);) is run
        • If the condition is false, we exit the loop
    • Update: After each iteration, the loop updates the control variable
      • ++i increments i by 1 after every loop iteration
    • Body: The code inside the curly braces
    • This cycle—checking the condition, running the body, and running the update—continues until the condition is found to be false and the loop exits

cast

  • We can cast variables from one type to another
    • The syntax (Bar)(foo) "cast foo to type Bar"
    • NOTE: Casting is a "special tactic" in modern Java; we will only ever use it on this lab (and even then, probably only once)

char's are integers

  • char's are integers (but they are NOT int's)
  • We can use a cast to find a char's "integer equivalent"
    • (int)('A') is 65
    • (int)('0') is 48
  • NOTE: The char's are "in order"
    • (int)('A') is 65
    • (int)('B') is 66
    • (int)('C') is 67
    • ...
    • (int)('a') is 97
    • (int)('b') is 98
    • (int)('c') is 99
    • ...
  • We can add char's and subtract char's
    int i = ('B' - 'A'); // 1
    
    // NOTE: We needed to "cast to a char" because, in Java, a char plus an int is an int
    char c = (char) ('c' + i); // 'd'
    
    ++c; // 'e'

Math

Distance Formula

  • The distance between two points $\mathbf{a} = {(a_x, a_y)}$ and $\mathbf{b} = {(b_x, b_y)}$ is $\sqrt{{\Delta_x}^2 + {\Delta_y}^2}$, where $\Delta_x = (b_x - a_x)$ and $\Delta_y = (b_y - a_y)$
    • NOTE: The distance is "the length of the line segment connecting the two points"

Circle

  • A circle has center $\mathbf{c} = {(c_x, c_y)}$ and radius $r$
    • NOTE: The circle is "the set of all points that are distance $r$ from point $\mathbf{c}$"
  • NOTE: This section is for the chasing part of the homework, NOT the WASD part
  • A simple way to tween (smoothly move) some number x to a target is to (repeatedly) use this update: x += 0.1 * (target - x)
    • Note that x + (target - x) --> target
    • In other words, if we add (target - x) to x, we get all the way to the target
    • If instead, we add 0.1 * (target - x), we move 10% of the way to the target
    • If x is far away from the target, it will move quickly; as it gets closer it will slow down
  • NOTE: See the linked video for a more fun explanation.

Reference

  • Your app should match the look and (approximate) behavior of this Reference animation
    • NOTE: To help you understand what’s going on, I’m showing you when I press keys and click the mouse (key pops up in top left; gray ring pops up around mouse); this is NOT something you need to do in your code

YouTube Link: https://youtube.com/shorts/y1vOXe2Ryg0

image

NOTE's

  • Handle the number keys with a for loop and some arithmetic. Do NOT have 10 separate if statements.

TODO's

NOTE: You will want to do the TODO's in order :)

  • A-
    • Check out the Documentation for Cow.java (there are functions like boolean keyHeld(char key))
    • Update your copy of Cow.java (you will need to do this every week; this week the update includes the drawTriangle(...) function)
      • 🍏 Mac
        • Option A: Finder
          • Open your CS136 folder in Finder
          • Double click the UpdateCow program
        • Option B: Terminal
          • Navigate into your CS136 folder in the Terminal
          • Type ./UpdateCow
          • Press ENTER
      • 🤷‍♂️ Windows
        • Option A: File Explorer
          • Open your CS136 folder in File Explorer
          • Double click the UpdateCow.bat program
        • Option B: Command Prompt
          • Navigate into your CS136 terminal in the Command Prompt
          • Type UpdateCow.bat
          • Press ENTER
    • If the mouse is inside the circle, color it MAGENTA; otherwise BLUE
    • User can move the circle using WASD
      • Holding W should move the circle up
      • Holding A should move the circle left
      • Holding S should move the circle down
      • Holding D should move the circle right
    • User can change the circle's radius using the number keys
      • Pressing 0 should make the radius $0.0$
      • Pressing 1 should make the radius $10.0$
      • Pressing 2 should make the radius $20.0$
      • ...
      • Pressing 9 should make the radius $90.0$
    • Implement chasing
      • Pressing P should make the circle start chasing the mouse (app is "playing"); pressing P again should make the circle stop (app is "paused").
      • Draw the appropriate play and pause symbols (⏯️) in the lower left corner
  • A
    • User can redraw the circle
      • Clicking the first time should pick the new center
      • Clicking a second time should pick the new radius
      • NOTE: The mouse is never held down
      • While the user is redrawing the circle (after they've clicked the first time, but before they've clicked the second time), a preview of the circle should be drawn in CYAN
      • NOTE: The circle should NOT chase you while the user is redrawing it, even if the app is playing
    • While the user is redrawing the circle, draw the appropriate ... symbol in the lower left corner
  • A+
    • Implement a version of Pong that builds on top of what you've done so far.
    • You can even draw the score using drawRectangle(...)
    • (Easier) You could use tally marks or dots to indicate score :)

Starter Code

// NOTE: You will want to do the TODO's from the HW01 page in order :)
class HW01 extends Cow {

	// Returns the distance between points (x1, y1) and (x2, y2)
	static double getDistance(double x1, double y1, double x2, double y2) {
		// TODO
		return 0.0;
	}

	public static void main(String[] arguments) {
		double x = 128.0;
		double y = 128.0;
		double radius = 10.0;

		canvasConfig(0.0, 0.0, 256.0, 256.0);
		while (beginFrame()) {
			// TODO

			drawCircle(x, y, radius, BLUE);
		}
	}
	
}

HINT's

What does canvasConfig(0.0, 0.0, 256.0, 256.0) mean?

This means the lower-left corner of the canvas will be $(0, 0)$ and the upper-right corner will be $(256, 256)$.

What state should I store? Here are the variables above my while loop:
// A-
double x = 128.0;
double y = 128.0;
double radius = 10.0;
boolean playing = false; // NOTE: You don't need this if you use keyToggled('P') everywhere

// A
double xNext = 0.0;
double yNext = 0.0;
double radiusNext = 0.0;
boolean waitingForSecondClick = false;
How do I convert 7 to '7'?
// NOTE: The syntax (char)(...) is a "cast"
int i = 7;
char c = (char)('0' + i); // '7'
Can this be done inside a for loop?

Yes!

for (int i = 0; i < 10; ++i) {
    char c = (char)('0' + i); // '0', '1', '2', ..., '9'
}
How does chasing work?

The reading will explain how to do chasing in one dimension (how to make x go to mouseX). To go in two dimensions, what if you made x go to mouseX and y go to mouseY?--That could be cool! :)

For redrawing the circle, how do I tell the difference between the first and second click?

The trick is to use a flag.

boolean flag = false; // NOTE: Maybe call this waitingForSecondClick?

while (beginFrame()) {

    // Handle mouse presses
    if (mousePressed) {
        if (!flag) {
            PRINT(0);
        } else {
            PRINT(1);
        }
        flag = !flag;
    }

}
For pong, how can I add a second app to the same file?

An if-else will work 🙂👍

boolean playingPong = false;

while (beginFrame()) {
    if (keyPressed(TAB)) {
        playingPong = !playingPong;
    }

    if (!playingPong) {
        // entire update and draw for A-/A
        ...
    } else {
        // entire update and draw for Pong
        ...
    }
}

Solution

👀
class HW01A extends Cow {

    static double getDistance(double x1, double y1, double x2, double y2) {
        double dx = x2 - x1;
        double dy = y2 - y1;
        return SQRT(dx * dx + dy * dy);
    }

    public static void main(String[] arguments) {
        // A-
        double x = 128.0;
        double y = 128.0;
        double radius = 10.0;
        boolean playing = false;

        // A
        double xNext = 0.0;
        double yNext = 0.0;
        double radiusNext = 0.0;
        boolean waitingForSecondClick = false;

        canvasConfig(0.0, 0.0, 256.0, 256.0);

        boolean playingPong = false;
        while (beginFrame()) {
            if (keyPressed(TAB)) {
                playingPong = !playingPong;
            }
            if (!playingPong) {
                // // UPDATE

                if (keyPressed('P')) {
                    playing = !playing;
                }

                // WASD
                if (!playing) {
                    double speed = 4.0;
                    if (keyHeld('W')) y += speed;
                    if (keyHeld('A')) x -= speed;
                    if (keyHeld('S')) y -= speed;
                    if (keyHeld('D')) x += speed;
                }

                // 0-9
                for (int i = 0; i <= 9; ++i) {
                    if (keyPressed('0' + i) ){
                        radius = 10 * i;
                    }
                }

                // chasing
                if (playing && (!waitingForSecondClick)) {
                    x += 0.1 * (mouseX - x);
                    y += 0.1 * (mouseY - y);
                }

                // redrawing
                if (mousePressed) {
                    if (!waitingForSecondClick) { // if we are not waiting for the second click
                        xNext = mouseX;
                        yNext = mouseY;
                    } else {
                        x = xNext;
                        y = yNext;
                        radius = radiusNext;
                    }
                    waitingForSecondClick = !waitingForSecondClick;
                }
                if (waitingForSecondClick) {
                    radiusNext = getDistance(xNext, yNext, mouseX, mouseY);
                }

                // // DRAW

                // circle color
                Color color; {
                    double distance = getDistance(x, y, mouseX, mouseY);
                    boolean mouseIsInside = (distance < radius);
                    if ((!waitingForSecondClick) && mouseIsInside) {
                        color = MAGENTA;
                    } else {
                        color = BLUE;
                    }
                }

                // draw circles
                drawCircle(x, y, radius, color);
                if (waitingForSecondClick) {
                    drawCircle(xNext, yNext, radiusNext, CYAN);
                }

                // draw play/pause/redraw symbols
                if (waitingForSecondClick) {
                    drawCircle(10.0, 15.0, 2.0, GREEN);
                    drawCircle(15.0, 15.0, 2.0, GREEN);
                    drawCircle(20.0, 15.0, 2.0, GREEN);
                } else {
                    if (playing) {
                        drawTriangle(10.0, 10.0, 10.0, 20.0, 20.0, 15.0, GREEN);
                    } else {
                        drawRectangle(10.0, 10.0, 14.0, 20.0, GREEN);
                        drawRectangle(16.0, 10.0, 20.0, 20.0, GREEN);
                    }
                }
            } else {
                // TODO: pong
            }
        }
    }
}
Clone this wiki locally