Category Archives: Classwork

Input/Output: Animation: DeluxeBouncingBall.java

Screen Shot 2015-02-23 at 12.19.21 AM

Standard Drawing: Animation and images
Images. PU standard draw library supports drawing pictures as well as geometric shapes.

  • Images. Our standard draw library supports drawing pictures as well as geometric shapes. The command StdDraw.picture(x, y, filename) plots the image in the given filename (either JPEG, GIF, or PNG format) on the canvas, centered on (x, y).
  • Resources:
    https://introcs.cs.princeton.edu/java/15inout/TennisBall.png 
    https://introcs.cs.princeton.edu/java/15inout/pipebang.wav
  • User interaction. Our standard draw library also includes methods so that the user can interact with the window using the mouse.
    double mouseX()          return x-coordinate of mouse
    double mouseY()          return y-coordinate of mouse
    boolean mousePressed()   is the mouse currently being pressed?
    
      • A first example. MouseFollower.java is the HelloWorld of mouse interaction. It draws a blue ball, centered on the location of the mouse. When the user holds down the mouse button, the ball changes color from blue to cyan. A simple attractor. OneSimpleAttractor.java simulates the motion of a blue ball that is attracted to the mouse. It also accounts for a drag force.
      • Many simple attractors. SimpleAttractors.java simulates the motion of 20 blue balls that are attracted to the mouse. It also accounts for a drag force. When the user clicks, the balls disperse randomly.
      • Springs. Springs.java implements a spring system.

    Standard audio.

    StdAudio is a library that you can use to play and manipulate sound files. It allows you to play, manipulate and synthesize sound.

    We introduce some some basic concepts behind one of the oldest and most important areas of computer science and scientific computing: digital signal processing.

    • Concert A. Concert A is a sine wave, scaled to oscillate at a frequency of 440 times per second. The function sin(t) repeats itself once every 2π units on the x-axis, so if we measure t in seconds and plot the function sin(2πt × 440) we get a curve that oscillates 440 times per second. The amplitude (y-value) corresponds to the volume. We assume it is scaled to be between −1 and +1.
    • Other notes. A simple mathematical formula characterizes the other notes on the chromatic scale. They are divided equally on a logarithmic (base 2) scale: there are twelve notes on the chromatic scale, and we get the ith note above a given note by multiplying its frequency by the (i/12)th power of 2.

    • When you double or halve the frequency, you move up or down an octave on the scale. For example 880 hertz is one octave above concert A and 110 hertz is two octaves below concert A.
    • Sampling. For digital sound, we represent a curve by sampling it at regular intervals, in precisely the same manner as when we plot function graphs. We sample sufficiently often that we have an accurate representation of the curve—a widely used sampling rate is 44,100 samples per second. It is that simple: we represent sound as an array of numbers (real numbers that are between −1 and +1).
    •  

    For example, the following code fragment plays concert A for 10 seconds.

    int SAMPLING_RATE = 44100;
    double hz = 440.0;
    double duration = 10.0;
    int n = (int) (SAMPLING_RATE * duration);
    double[] a = new double[n+1];
    for (int i = 0; i <= n; i++) {
       a[i] = Math.sin(2 * Math.PI * i * hz / SAMPLING_RATE); 
    }
    StdAudio.play(a);
    • Play that tune. PlayThatTune.java is an example that shows how easily we can create music with StdAudio. It takes notes from standard input, indexed on the chromatic scale from concert A, and plays them on standard audio.

Input/Output: Animation: First One: Bouncing Ball

Your first animation using java!!!
duke

Screen Shot 2015-02-23 at 12.19.21 AM

Standard Drawing: Animation and images Images.

/******************************************************************************
 *  Compilation:  javac BouncingBall.java
 *  Execution:    java BouncingBall
 *  Dependencies: StdDraw.java
 *
 *  Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1).
 *
 *  % java BouncingBall
 *
 ******************************************************************************/

public class BouncingBall { 
    public static void main(String[] args) {

        // set the scale of the coordinate system
        StdDraw.setXscale(-1.0, 1.0);
        StdDraw.setYscale(-1.0, 1.0);
        StdDraw.enableDoubleBuffering();

        // initial values
        double rx = 0.480, ry = 0.860;     // position
        double vx = 0.015, vy = 0.023;     // velocity
        double radius = 0.05;              // radius

        // main animation loop
        while (true)  { 

            // bounce off wall according to law of elastic collision
            if (Math.abs(rx + vx) > 1.0 - radius) vx = -vx;
            if (Math.abs(ry + vy) > 1.0 - radius) vy = -vy;

            // update position
            rx = rx + vx; 
            ry = ry + vy; 

            // clear the background
            StdDraw.clear(StdDraw.GRAY);

            // draw ball on the screen
            StdDraw.setPenColor(StdDraw.BLACK); 
            StdDraw.filledCircle(rx, ry, radius); 

            // copy offscreen buffer to onscreen
            StdDraw.show();

            // pause for 20 ms
            StdDraw.pause(20);

        } 
    } 
} 


Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne. 
Last updated: Tue Aug 30 09:58:33 EDT 2016.

Classwork:
Add this program to your current project.
Make the following changes, submit a screenshot for each change and the final program:

  1. Comment out the “clear” function and describe what you see. Remove the comments to continue working.
  2. Make the ball color change when it bounces. Choose a random color at every bounce.
  3. Change the background color from the original.
  4. Change the shape of the ball.

Reminder:

Array: as Frequency Counter

Classwork:
Write a program, BarGraph2_YI.java to create a bar graph with asterisks as in the previous bar graph. However, the array’s values are the raw data. Use this array and values, dataSet = { 67, 89, 55, 100, 95, 93, 57, 19, 88, 87, 86, 91,90}.


Output:
00-09:
10-19: *
20-29:
30-39:
40-49:
50-59: **
60-69: *
70-79: 
80-89: ****
90-99: ****
  100: *

Do not use if statements to check if the value fall within a range.
HINT: What is the result of dividing each grade by 10?
WARNING: DO NOT USE if STATEMENTS!!! or WHILE LOOPS TO FIND THE RANGE OF THE GRADES!!!

Claswork/Homework:

Consider the following:
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the student cafeteria, with 1 being “awful” and 5 being “excellent.” Randomly assign 20 responses to an integer array and determine the frequency of each rating.

cafeteriafood

Using what you learned about the elements of an array as counters, write a program, FoodSurvey_YI.java to display the rating and their frequency in two well formatted columns.

Output example:

Rating  Frequency
  1:       10
  2:        5
  3:        2
  4:        2
  5:        1

Arrays: 2D Arrays Intro

2D Arrays

Screen Shot 2014-11-21 at 9.58.20 AM

Screen Shot 2014-11-21 at 10.03.51 AM

Additional programming style guidelines:

/* 
 * 1. Make sure your program has indentation when is needed.
 * 2. Please include a comment line about local variables and group them all 
 *    together at the top of the program as long as it is not an OOD program.
 * 3. Never create a new local variable inside a loop!
 * 4. Have a blank line between different parts of the program
 */

final int COUNTRIES = 7;
final int MEDALS = 3;
int[][] counts = new int[COUNTRIES][MEDALS];

or but not both:

int[][] counts = {
 { 1, 0, 1 }, 
 { 1, 1, 0 }, 
 { 0, 0, 1 }, 
 { 1, 0, 0 }, 
 { 0, 1, 1 }, 
 { 0, 1, 1 }, 
 { 1, 1, 0 }
 };
for (int i = 0; i < COUNTRIES; i++)
{
  // Process the ith row
  for (int j = 0; j < MEDALS; j++) 
  {
      // Process the jth column in the ith row
      System.out.printf("%8d", counts[i][j]); 
  }
  System.out.println(); // Start a new line at the end of the row 
 }

Screen Shot 2014-11-21 at 10.09.23 AM

for (int i = 0; i < counts.length; i++) 
{
  for (int j = 0; j < counts[0].length; j++) 
  {
     System.out.printf("%8d", counts[i][j]); 
  }
  System.out.println(); 
}

Accessing the neighboring elements of a 2D array
Screen Shot 2014-11-21 at 10.11.40 AM

Screen Shot 2014-11-21 at 10.12.44 AM

Adding by rows:

int total = 0;
for (int i = 0; i < COUNTRIES; i++)
{
  total = 0;
  for (int j = 0; j < MEDALS; j++) 
  {
    total = total + counts[i][j];
  }
}

Screen Shot 2014-11-21 at 10.13.44 AM

Adding by columns:

int total = 0;
for (int j = 0; j < MEDALS; j++)
{
  total = 0;
  for (int i = 0; i < COUNTRIES; i++) 
  {
    total = total + counts[i][j]; 
  }
}

Classwork:
Write a program, MedalsTable_YI.java to produce the following output:

Screen Shot 2014-11-21 at 11.30.17 AM

Assignment:
Consider as an example an 8 × 8 array for a board game:
int[][] board = new int[8][8];

BoardGame_YI.java: Using two nested loops, initialize the board using "for" loops so that zeroes and ones alternate, as on a checkerboard. Prompt the user for the size of the "square" 2D array and display the board on the screen.

0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
...
1 0 1 0 1 0 1 0

Hint: Check whether i + j is even.

Arrays 2D: Minesweeper

Screen Shot 2014-12-07 at 12.13.44 PM

minesweeper

youtube “how-to”

Write a program Minesweeper_YI.java that takes 3 input arguments m, n, and p and produces an m-by-n boolean array where each entry is occupied with probability p. In the minesweeper game, occupied cells represent bombs and empty cells represent safe cells. Print the array using an asterisk for bombs and a period for safe cells. Then, replace each safe square with the number of neighboring bombs (above, below, left, right, or diagonal) and print the solution.

HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.2
. . . 
. . . 
* . . 

0 0 0 
1 1 0 
* 1 0 


Try to write your code so that you have as few special cases as possible to deal with, by using an (m+2)-by-(n+2) boolean array.

HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.3
. . * 
. . * 
. . * 

0 2 * 
0 3 * 
0 2 * 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.4
. . . 
* . . 
. . . 

1 1 0 
* 1 0 
1 1 0 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.5
* * * 
. * * 
* . * 

* * * 
4 * * 
* 4 * 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.6
* * * 
. . * 
* * * 

* * * 
4 7 * 
* * * 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.7
. * * 
* * * 
* . * 

3 * * 
* * * 
* 5 * 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.8
* . * 
* * . 
* * * 

* 4 * 
* * 4 
* * * 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.9
* * * 
* * . 
* * * 

* * * 
* * 5 
* * *

Required Submission:

  1. Copy and paste the program (with the output as a paragraph comment at the end of your program) to the Text entry tab.

  2. Submit the file with the ‘”java” extension.

3. Make sure you document code snippets that have a particular purpose!

4. Testing: Have multiple boards with different board sizes and different probabilities. The minimum should be 3 boards.


					

Arrays: Game of Life

Game Of Life:

If you have successfully completed the random block program and written the draft for the algorithm in pseudocode, you should be able to get started with the game of life assignment.

Start small. Hardcode the seed for the glider:

Requirements:
1. Take as input the size of the grid.
2. Show the live cells in color other than black.

Challenges:
1. Take as input the coordinates for the seed. You must include in your documentation the coordinates for the glider seed.
2. Change the color of the dead cells to a faded color for at least one generation after dying.
3. Take as input the option to speed or slow down the simulation.

Arrays – Connect Four

Classwork/Homework:
(Game: connect four) Connect four is a two-player board game in which the players alternately drop colored disks into a seven-column, six-row vertically suspended grid, as shown below.

connectfour

The objective of the game is to connect four same-colored disks in a row, a column, or a diagonal before your opponent can do likewise. The program prompts two players to drop a red or yellow disk alternately. In the preceding figure, the red disk is shown in a dark color and the yellow in a light color. Whenever a disk is dropped, the program redisplays the board on the console and determines the status of the game (win, draw, or continue). Here is a sample run:

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
———————————————

Drop a red disk at column (0–6): 0
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | | | | |
———————————————

Drop a yellow disk at column (0–6): 4

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | |Y| | |
.
.
.
.

Drop a yellow disk at column (0–6): 6 

| | | | | | | |
| | | | | | | |
| | | | |Y| | |
| | | |Y|Y|Y|R|
| | |Y|R|R|Y|Y|
|R|Y|R|Y|R|R|R|
———————————————
The yellow player won
Do you want to play again?

Write the two-player program, YI_Connect4.java. Display at a every move the board as shown in the example above. Include a prompt to continue playing.

Your program should include:
1. Good documentation
2. An introduction message
3. Functions (Optional)
4. An end of game message
5. Input/output

What is good documentation?
Answer:

  1. Header with author’s name, assignment description, date and python version.
  2. Comments in each function. A short sentence will be sufficient.
  3. Comments for code snippets written for specific handling. An example might be checking if there are 3 in a row, or 4 in a row.
  4. Comments to indicate unusual or rare situations that don’t follow a pattern or repetition.

Blackboard: Nothing like pseudocode

Nothing like good pseudocode!!
javapseudocodeconn4

One more
lastpeudocode