Create a new project in Unit_2, InputOutput or InOut
Add the available StdLib classes to your project via the Edit tab, drag them or create them in your project.
Your project you look like this:
Let’s test our project with this program:
NOTE: include documentation and attach the image (screenshot)
/**
* Write a description of class Triangle here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Triangle
{
public static void main(String args[])
{
StdDraw.line(0,0,.1,.1);
StdDraw.line(0,0,0,1);
StdDraw.line(0,0,1,0);
}
}
Write a java program, MyRandArt_YI.java to create an abstract painting using the geometric functions in the StdDraw library and the random function to generate points, colors, and thickness. Note: make sure to restrict ranges for each feature.
Geometric Abstract Painting: Mary Heilmann
Write a java program, MyCubicArt_YI.java to create an abstract painting using the geometric functions in the StdDraw library in the link below.
Students’ work from previous years
How to create your own colors:
setPenColor(int red, int green, int blue)
Creates an opaque RGB color with the specified red, green, and blue values.
Parameters:
red – the amount of red (between 0 and 255)
green – the amount of green (between 0 and 255)
blue – the amount of blue (between 0 and 255)
Write a java program, MyRandCubicArt_YI.java to create an abstract painting using the geometric functions in the StdDraw library and the random function to generate points, colors, and thickness. Note: make sure to restrict ranges for each feature.
How to draw a polygon:
Write a short program with a polygon and play with it until you understand how it works.
[spoiler title=’APoly’]
/**
* Playing with colors and shapes.
*
* @GE
* @java 1.8.4
* 12/5/18
*/
public class APoly
{
public static void main(String [] args)
{
// rescale the coordinate system
StdDraw.setXscale(0, 2);
StdDraw.setYscale(0, 2);
StdDraw.setPenColor(255,0,255);
double y[] = {.5,.5,1.5,1.5}; // y coordinates of each vertex
double x[] = {.5,1.5,1.5,.5}; // x coordinates of each vertex
//StdDraw.setPenColor(255,0,255);
StdDraw.filledPolygon(x,y);
StdDraw.setPenColor(0,0,255);
StdDraw.setPenRadius(0.008);
StdDraw.polygon(x,y);
}
}
[/spoiler]
How to change thickness:
setPenRadius(0.05)
Sets the pen size to the default size (0.002). The pen is circular, so that lines have rounded ends, and when you set the pen radius and draw a point, you get a circle of the specified radius.
Java’s print() and println() methods are the ones that you have been using. The printf() method gives us more control over the appearance of the output.
Formatted printing basics. In its simplest form, printf() takes two arguments. The first argument is called the format string. It contains a conversion specification that describes how the second argument is to be converted to a string for output.
Format strings begin with % and end with a one-letter conversion code. The following table summarizes the most frequently used codes:
Format string. The format string can contain characters in addition to those for the conversion specification. The conversion specification is replaced by the argument value (converted to a string as specified) and all remaining characters are passed through to the output.
Multiple arguments. The printf() function can take more than two arguments. In this case, the format string will have an additional conversion specification for each additional argument.
What preparation do I need before beginning this assignment? Read Sections 2.1–2.3 of the textbook.
The API expects the angles to be in degrees but Java’s trigonometric functions assume the arguments are in radians. How do I convert between the two? Recall GreatCircle.java from Assignment 0.
What is the purpose of the copy() function in Transform2D? As noted in the assignment, the transformation methods mutate a given polygon. This means that the parallel arrays representing the polygon are altered by the transformation methods. It is often useful to save a copy of the polygon before applying a transform. For example:
// Set the x- and y-scale
StdDraw.setScale(-5.0, 5.0);
// Original polygon
double[] x = { 0, 1, 1, 0 };
double[] y = { 0, 0, 2, 1 };
// Copy of original polygon
double[] cx = Transform2D.copy(x);
double[] cy = Transform2D.copy(y);
// Rotate, translate and draw the copy
Transform2D.rotate(cx, cy, -45.0);
Transform2D.translate(cx, cy, 1.0, 2.0);
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.polygon(cx, cy);
// Draw the original polygon
StdDraw.setPenColor(StdDraw.RED);
StdDraw.polygon(x, y);
Does a polygon have to be located at the origin in order to rotate it? No. You can rotate any polygon about the origin. For example:
// Original polygon
double[] x = { 1, 2, 2, 1 };
double[] y = { 1, 1, 3, 2 };
StdDraw.setPenColor(StdDraw.RED);
StdDraw.polygon(x, y);
// Rotate polygon// 90 degrees counterclockwise
Transform2D.rotate(x, y, 90.0);
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.polygon(x, y);
Does our code have to account for invalid arguments? No. You can assume:
the array passed to copy() is not null,
arrays passed to scale(), translate() and rotate() are not null, are the same length, and do not contain the values NaN,infinity or negative infinity.
the values for the parameters alpha, theta, dx and dy are not NaN, infinity or negative infinity.
Frequently Asked Questions: Sierpinski
What is the formula for the height of an equilateral triangle of side length s? The height is (s \sqrt{3} / 2 ).
What is the layout of the initial equilateral triangle? The top vertex lies at ((1/2, \sqrt{3} / 2)) You can use this diagram as a reference.
How do I draw a filled equilateral triangle? Call the method StdDraw.filledPolygon() with appropriate arguments.
I get a StackOverflowError message even when n is a very small number like 3. What could be wrong? This means you are running out of space to store the function-call stack. Often, this error is caused by an infinite recursive loop. Have you correctly defined the base case and reduction step?
May I use different colors to draw the triangles? Yes, you may use any colors that you like to draw either the outline triangle or the filled triangles, provided it contrasts with the white background.
Frequently Asked Questions: Art
The API checker says that I need to make my methods private. How do I do that? Use the access modifier private instead of public in the method signature. A public method can be called directly by a method in another class; a private method cannot. The only public method that you should have in Art is main().
How should I approach the artistic part of the assignment? This part is meant to be fun, but here are some guidelines in case you’re not so artistic. A very good approach is to first choose a self-referential pattern as a target output. Check out the graphics exercises in Section 2.3. Here are some of our favorite student submissions from a previous year. See also the Famous Fractals in Fractals Unleashed for some ideas. Here is a list of fractals, by Hausdorff dimension. Some pictures are harder to generate than others (and some require trigonometry); consult your preceptor for advice if you’re unsure.
What will cause me to lose points on the artistic part? We consider three things: the structure of the code; the structure of the recursive function-call tree; and the art itself.
For example, the Quadricross looks very different from the in-class examples, but the code to generate it looks extremely similar to HTree, so it is a bad choice. On the other hand, even though the Sierpinski curve eventually generates something that looks like the Sierpinski triangle, the code is very different (probably including an “angle” argument in the recursive method) and so it would earn full marks.
You must do at least two of these things to get full credit on Art.java:
call one or more Transform2D method
use different parameters than our examples: f(n, x, y, size)
use different StdDraw methods than in examples (e.g., ellipses, arcs, text)
number of recursive calls not constant per level (e.g., conditional recursion)
mutually recursive methods
multiple recursive methods
doesn’t always recur from level n to level n-1
draw between recursive calls, not just before or after all recursive calls
use recursive level for secondary purpose (e.g. level dictates color)
Contrast this with the examples Htree, Sierpinski, and NestedCircles which have very similar structures to one another.
You will also lose points if your artwork can be created just as easily without recursion (such as Factorial.java). If the recursive function-call tree for your method is a straight line, it probably falls under this category.
May I use GIF, JPG, or PNG files in my artistic creation? Yes. If so, be sure to submit them along with your other files. Make it clear in your readme.txt what part of the design is yours and what part is borrowed from the image file.
How can I call the Transform2D methods inside Art.java? You must fully qualify each method name with the Transform2D library. For example:
Transform2D.rotate(x, y, 45);
My function for Art.java takes several parameters, but the assignment says that I can only read in one command-line argument n. What should I do? Choose a few of the best parameter values and do something like the following:
if (n == 1) { x = 0.55; y = 0.75; }
else if (n == 2) { x = 0.55; y = 0.75; }
else if (n == 3) { x = 0.32; y = 0.71; }
else if ...
How can I create colors that aren’t predefined in standard drawing? It requires using objects that we’ll learn about in Chapter 3. In the meantime, you can use this color guide.
Possible Progress Steps: Sierpinski
These are purely suggestions for how you might make progress. You do not have to follow these steps. Note that your final Sierpinski.java program should not be very long (no longer than Htree, not including comments and blank lines).
Write the (non-recursive) function height() that takes the length of the sides in an equilateral triangle as an argument and returns its height. The body of this method should be a one-liner.Test your height() function.
Write a (nonrecursive) function filledTriangle() that takes three real-valued arguments (x, y, and length), and draws a filled equilateral triangle (pointed downward) with bottom vertex at (x, y) of the specified side length.To debug and test your function, write main() so that it calls filledTriangle() a few times, with different arguments. You will be able to use this function without modification in Sierpinski.java.
Write a recursive function sierpinski() that takes four (4) arguments (n, x, y, and length) and plots a Sierpinski triangle of order n, whose largest triangle has bottom vertex (x, y) and the specified side length.
Write a recursive function sierpinski() that takes one argument n, prints the value n, and then calls itself three times with the value n-1. The recursion should stop when n becomes 0. To test this function out, write main() so that it takes an integer command-line argument n and calls sierpinski(n). Ignoring whitespace, you should get the following output when you call sierpinski() with n ranging from 0 to 5. Make sure you understand how this function works, and why it prints the numbers in the order it does.
Modify sierpinski() so that in addition to printing n, it also prints the length of the triangle to be plotted. Your function should now take two arguments: n and length. The initial call from main() should be to sierpinski(n, 0.5) since the largest triangle has side length 0.5. Each successive level of recursion halves the length. Ignoring whitespace, your function should produce the following output.
Modify sierpinski() so that it takes four (4) arguments (n, x, y, and length) and plots a Sierpinski triangle of order n, whose largest triangle has bottom vertex (x, y) and the specified side length. Start by drawing Sierpinski triangles with pencil and paper. Use the picture in the Q+A above to figure out the geometry of where the smaller Sierpinski triangles should go.
Remove all print statements before submitting.
Below are the target Sierpinski triangles for different values of n.
% java-introcs Sierpinski 1
% java-introcs Sierpinski 2
% java-introcs Sierpinski 3
Reviewing Your Program
Transform2D.java: The main must call each of the methods defined by the Transform2D API.
Sierpinski.java: Do not call StdDraw.save(), StdDraw.setCanvasSize(), StdDraw.setXscale(), StdDraw.setYscale(), or StdDraw.setScale(). These method calls interfere with grading. (However, changing the x– or y-scales in Transform2D.java and Art.java is permitted.)
Art.java: Must take exactly one integer command-line argument n (which will be between 1 and 7).
Be sure to include a comment just above each method definition explaining what the method does—this will be required in all future assignments as well. Leaving a comment for main() is not required since the header already does basically the same thing.
Continue to follow the style guidelines from the assignment FAQ.
Fractal dimension (optional diversion). In grade school, you learn that the dimension of a line segment is 1, the dimension of a square is 2, and the dimension of a cube is 3. But you probably didn’t learn what is really meant by the term dimension. How can we express what it means mathematically or computationally? Formally, we can define the Hausdorff dimension or similarity dimension of a self-similar figure by partitioning the figure into a number of self-similar pieces of smaller size. We define the dimension to be the log (# self similar pieces) / log (scaling factor in each spatial direction). For example, we can decompose the unit square into 4 smaller squares, each of side length 1/2; or we can decompose it into 25 squares, each of side length 1/5. Here, the number of self-similar pieces is 4 (or 25) and the scaling factor is 2 (or 5). Thus, the dimension of a square is 2 since log (4) / log(2) = log (25) / log (5) = 2. We can decompose the unit cube into 8 cubes, each of side length 1/2; or we can decompose it into 125 cubes, each of side length 1/5. Therefore, the dimension of a cube is log(8) / log (2) = log(125) / log(5) = 3.We can also apply this definition directly to the (set of white points in) Sierpinski triangle. We can decompose the unit Sierpinski triangle into 3 Sierpinski triangles, each of side length 1/2. Thus, the dimension of a Sierpinski triangle is log (3) / log (2) ≈ 1.585. Its dimension is fractional—more than a line segment, but less than a square! With Euclidean geometry, the dimension is always an integer; with fractal geometry, it can be something in between. Fractals are similar to many physical objects; for example, the coastline of Britain resembles a fractal; its fractal dimension has been measured to be approximately 1.25.
This assignments consists of three parts. First, write a library of static methods that performs geometric transforms on polygons. Next, write a program that plots a Sierpinski triangle. Finally, develop a program that plots a recursive pattern of your own design.
Part 1. In this part, you will write a library of static methods that performs various geometric transforms on polygons. Mathematically, a polygon is defined by its sequence of vertices (x0, y0), (x1, y1), (x2, y2), …. In Java, we will represent a polygon by storing the x– and y-coordinates of the vertices in two parallel arrays x[] and y[].
Write a two-dimensional transformation library Transform2D.java by implementing the following API:
public class Transform2D {// Returns a new array object that is an exact copy of the given array.// The given array is not be mutated.public static double[] copy(double[] array)// Scales the polygon by the factor alpha.public static void scale(double[] x, double[] y, double alpha)// Translates the polygon by (dx, dy).public static void translate(double[] x, double[] y, double dx, double dy)// Rotates the polygon theta degrees counterclockwise, about the origin.public static void rotate(double[] x, double[] y, double theta)// Tests each of the API methods by directly calling them.public static void main(String[] args)}
Note that the transformation methods scale(), translate() and rotate()mutate the polygons. Here are some example test cases:
// Scales polygon by the factor 2.
StdDraw.setScale(-5.0, +5.0);
double[] x = { 0, 1, 1, 0 };
double[] y = { 0, 0, 2, 1 };
double alpha = 2.0;
StdDraw.setPenColor(StdDraw.RED);
StdDraw.polygon(x, y);
scale(x, y, alpha);
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.polygon(x, y);
Part 2. The Sierpinski triangle is an example of a fractal pattern like the H-tree pattern from Section 2.3 of the textbook.
order 1
order 2
order 3
order 4
order 5
order 6
The Polish mathematician Wacław Sierpiński described the pattern in 1915, but it has appeared in Italian art since the 13th century. Though the Sierpinski triangle looks complex, it can be generated with a short recursive function. Your main task is to write a recursive function sierpinski() that plots a Sierpinski triangle of order n to standard drawing. Think recursively: sierpinski() should draw one filled equilateral triangle (pointed downwards) and then call itself recursively three times (with an appropriate stopping condition). It should draw 1 filled triangle for n = 1; 4 filled triangles for n = 2; and 13 filled triangles for n = 3; and so forth.
API specification. When writing your program, exercise modular design by organizing it into four functions, as specified in the following API:
public class Sierpinski {// Height of an equilateral triangle whose sides are of the specified length.public static double height(double length)// Draws a filled equilateral triangle whose bottom vertex is (x, y)// of the specified side length.public static void filledTriangle(double x, double y, double length)// Draws a Sierpinski triangle of order n, such that the largest filled// triangle has bottom vertex (x, y) and sides of the specified length.public static void sierpinski(int n, double x, double y, double length)// Takes an integer command-line argument n;// draws the outline of an equilateral triangle (pointed upwards) of length 1;// whose bottom-left vertex is (0, 0) and bottom-right vertex is (1, 0); and// draws a Sierpinski triangle of order n that fits snugly inside the outline.public static void main(String[] args)}
Restrictions: You may not change either the scale or size of the drawing window.
Part 3. In this part you will create a program Art.java that produces a recursive drawing of your own design. It must take one integer command-line argument n that controls the depth of recursion. It must stay within the drawing window when n is between 1 and 7. It can be a geometric pattern, a random construction, or anything else that takes advantage of recursive functions. For full marks, it must not be something that could be easily rewritten to use loops in place of recursion, and some aspects of the recursive function-call tree (or how parameters or overlapping are used) must be distinct from the in-class examples (HTree, Sierpinski, NestedCircles, Brownian).
Optionally, you may use the Transform2D library you implemented in Part 1. You may also define additional geometric transforms in Art.java, such as sheer, reflect across the x– or y- axis, or rotate about an arbitrary point.
Additional requirements: Your program must be organized into at least three separate functions, including main(). All functions except main() must be private.
Restrictions: You may not change the size of the drawing window (but you may change the scale). Do not add sound.
Submission. Submit Transform2D.java, Sierpinski.java, and Art.java. If your Art.java requires any supplementary image files, submit them as well. Finally, submit a readme.txt file and answer the questions therein.
Challenge for the bored. Write a program that plots Sierpinski triangles without using recursion.
Remember to work on the current assignments before you work on this assignment.
Write a program, YI_CircleGradient.java to draw the following:
Extra credit:
Write an animation program, YI_GrayGradient3D.java that shows the image below but the whitish to blackish region follows the mouse as the mouse moves over the ball.
If you fold a square diagonally, you will create a right isosceles triangle. We will take the triangle’s area to be 1. Continue to halve this triangle again and again by placing the acute angles on top of each other. Write a java program, HalfAreas_YI.java and prompt the user how many times wants the square to be folded.
As an example, let’s say the user’s response to the prompt is 5.
Output: in full sentence display the number of folds and the area of the final triangle.
Find an origami paper on the last table and do it manually first. Do the calculations so you can check your program is doing the right thing.
Once you confirm your program is running properly, run the program for an input of 7 folds. Submit both, the hand calculation, the output for the test and the solution for the 7 folds.
NOTE: if you are aware of finding the solution by using a formula, you can add that information to your documentation. For this assignment you must use loops.
Implement an animation, RandomBlock_YI.java. The CheckerBoard.java can easily be changed to randomly select a random number of squares on the grid and become a solid color (“alive”) and then randomly it will turn back to white (“dead”) again. Re-Use-Code: these are good resources for this assignment: MyGraphPaper.java BouncingBall.java CheckerBoard.java
/****************************************************************************** * Compilation: javac Checkerboard.java * Execution: java Checkerboard n * Dependencies: StdDraw.java * * Plots an n-by-n checkerboard. * ******************************************************************************/
public class Checkerboard {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
StdDraw.setXscale(0, n);
StdDraw.setYscale(0, n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((i + j) % 2 != 0) StdDraw.setPenColor(StdDraw.BLACK);
else StdDraw.setPenColor(StdDraw.RED);
StdDraw.filledSquare(i + 0.5, j + 0.5, 0.5);
}
}
}
}
Game: 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.
The objective of the game is to connect four same-colored disks in a row, a column, or a diagonal before an opponent can do likewise. The program prompts a player to choose a color disk. Then the computer and the player will drop a red or yellow disk alternately. In the figure, the player with the red disk is the winner of the game.
This implementation is text based. Take a look a the simplicity of the format. This will enable you to concentrate on the algorithm and the strategy you need to implement to have the computer to win. Let’s develop the “computer to win” a bit further. You do not want to play against an infallible player (the computer) because you will not even want to play the game. So a better approach would be a good blend of random moves with smart moves. You decide how “smart” the computer is.
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:
Write a one-player program, Connect4TwoD_YI.java using 2D array. Display at a every move the board as shown in the example above. Include a prompt to continue playing.
Write a one-player program, Connect4OneD_YI.java using only 1D array. Display at a every move the board as shown in the example above. Include a prompt to continue playing. This is a bit more complex but you will find a pattern to help you implement it.
Little help #1: Use paper and pencil to design, trace and test your algorithm before you start.
Little help #2: You can use static methods (functions) to make the code more readable and easier to manage. This is only optional.
Let’s not just connect 4. Let’s connect what you have learned about arrays and everything that brought you to this point to develop your first AI game in java.
What does “your” simplified flowchart for a game look like?
sum = 0;
for (int i = 0; i < square.length; i++) {
sum += square[i][i];
}
sum = 0;
for (int i = 0; i < square.length; i++) {
sum += square[i][square.length-i];
}
4. Add details to your simplified flowchart. Let's develop the "computer to win" a bit further. You do not want to play against an infallible player (the computer) because you will not even want to play the game. So a better approach would be a good blend of random moves with smart moves. You decide how "smart" the computer is.
5. Levels of difficulty. Choose the "Medium" level of difficulty and start the same as in the first game. Do the same for "Hard" level and compare to easy and medium. How different are the behaviors of the "computer" moves? Can you find a pattern?