Read carefully and follow exactly Java:
You are to write a Breakout game, using Java applets for animation. The requirements for this
program are designed so that you will also use an ArrayList, Generics, an abstract class,
polymorphism, and file I/O. Please read the following instructions very carefully, as they attempt
to explain how the various parts of the animation work; then you can update the applet, using
your knowledge of ArrayLists, Generics, abstract classes, and polymorphism.
Existing classes: There are a number of existing classes that are already written and ready for
use. They are contained in the file Breakout.java (they are not defined as public so they don’t
have to be in a file that matches their name). Please look them over carefully to see what
functionality is available. The classes (implemented inside Breakout.java) are:
Ball: this is defined as a subclass of Rectangle (even though that is geometrically invalid!). The
reason for this is so Ball can inherit data for its x coordinate, y coordinate, width, and height. It
also adds some data of its own (see the code) and methods (among others) to:
bounceLeftRight() (which changes the angle at which it moves after bouncing off a left or right
side),
bounceTopBottom() (which changes the angle at which it moves after bouncing off a top or
bottom)
move() (change its coordinates),
freeze()/unfreeze() itself,
It also inherits important methods from the Rectangle class
translate – changes its x and y coordinates respectively by the 2 numbers that are passed in
intersects(Rectangle other) – returns true if it intersects another Rectangle
intersection(Rectangle other) – returns the Rectangle that is the intersection
Paddle: this is also defined as a subclass of Rectangle so it inherits the same data/methods that
are described above for the Ball class. The fact that Ball and Rectangle are both Rectangles
means that code can ask a Ball if it intersects a Paddle, so it can easily tell when to make things
happen.
Wall: this is not in its own file, but rather in the Breakout.java file. Wall is also a subclass of
Rectangle to it is easy to determine if the ball has collided a wall.
The Breakout class (which is an Applet): if you look at the code for the Breakout class, you will
notice it has a number of things:
It is a subclass of Applet, so it inherits data and methods as well as the ability to function as an
Applet. For example, if you want to know the height of the applet you can ask it through the
this.getHeight(); method.
It implements the KeyListener interface, which gives it the ability to “listen” for keystrokes
from the keyboard. If you were to look up the KeyListener interface in the documentation, you
would find that anything that implements it must have the KeyPressed, KeyReleased, and
KeyTyped methods. These are all there; KeyPressed and KeyReleased set/unset Boolean flags
which remember that the left or right arrow keys are or are not being pressed.
It has a method called in.
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
Abstract Data Types
(a) Explain briefly what is meant by the term abstract data type (ADT). Give two
reasons why use of ADTs is good programming practice.
(b) Write out a signature, or interface, that defines the operations of a stack ADT.
(c) Consider a string of characters of the form
... (.( ... ).) ...
where ... indicates an arbitrary sequence of characters (except for parentheses),
(.( indicates an arbitrary number (one or more) of opening parentheses, and
similarly ).) indicates an arbitrary number of closing parentheses.
Using only the stack abstraction operations defined above, write pseudocode for
an algorithm that determines, using a stack, whether or not the number of closing
parentheses is the same as the number of opening parentheses.
You may assume the existence of a function read(str,ch) that reads the next character
of string str into ch.
You may also assume that you can invoke a function reportFail, that will cause
termination with failure, and similarly, reportSuccess causes termination with a
success indication.
Further, you may also assume that you can call a function newStack(S) to create
a new empty stack S, and eos(str) that returns false when you reach the end of
the string.
Solution
(a) Explain briefly what is meant by the term abstract data type (ADT). Give two
reasons why use of ADTs is good programming practice.
A data type is a collection of values and a set of operations on those values. That collection and
these operations form a mathematical construct that may be implemented with the use of a
particular hardware or software data structure. The term abstract data type (ADT) refers to the
basic mathematical concept that defines the data type. We have discussed four different
implementations of the list data structure.
In case of implementation of the list with the use of an array, the size of the array gives difficulty
if increased.
To avoid this, we allocate memory dynamically for nodes before connecting these nodes with the
help of pointers.
For this purpose, we made a singly linked list and connected it with the next pointer to make a
chain.
Moving forward is easy but going back is a difficult task.
To overcome this problem, we made a doubly linked list using prev andnext pointers. With the
help of these pointers, we can move forward and backward very easily. Now we face another
problem that the prev pointer of first node and the next pointer of the last node are NULL.
Therefore, we have to be careful in case of NULL pointers. To remove the NULL pointers, we
made the circular link list by connecting the first and last node.
The program employing the list data structure is not concerned with its implementation.
We do not care how the list is being implemented whether through an array, singly linked list,
doubly linked list or circular linked list. It has been witnessed that in these four implementations
of the list, the interface remained the same i.e. it implements the same methods like add, get,
next, start a.
Article link httpiveybusinessjournal.compublicationmanaging-.docxfredharris32
Article link: http://iveybusinessjournal.com/publication/managing-global-risk-to-seize-competitive-advantage/
Requirements: Write one summary and study note both no longer than one pages should include all point of article. Then do a PPT and write a presenting paper only for 5 minutes.
Groups of students will create and offer two MS PowerPoint presentation summarizing the main points of one of the readings for this course along with a one page handout for the students in the class. The aim of the presentations and the handouts is to provide the audience with the main ideas of the article and study notes. Groups will bring to class enough copies of the handout for each student in the class. The handout should list the name of the author, the title of the article, the title of the journal, and the publication date and page numbers along with a summary of its main points. Please do not exceed one page for this material.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Read a .dat file and reverse it.
*/
public class Reverse {
public static void main(String[]args) {
if (args.length != 3) {
System.err.println(" Incorrect number of arguments");
System.err.println(" Usage: ");
System.err.
println("\tjava Reverse <stack type> <input file> <output file>");
System.exit(1);
}
boolean useList = true;
if (args[0].compareTo("list")==0)
useList = true;
else if (args[0].compareTo("array")==0)
useList = false;
else {
System.err.println("\tSaw "+args[0]+" instead of list or array as first argument");
System.exit(1);
}
try {
//
// Set up the input file to read, and the output file to write to
//
BufferedReader fileIn =
new BufferedReader(new FileReader(args[1]));
PrintWriter fileOut =
new PrintWriter(new
BufferedWriter(new FileWriter(args[2])));
//
// Read the first line of the .dat file to get sample rate.
// We want to store the sample rate value in a variable,
// but we can ignore the "; Sample Rate" part of the line.
// Step through the first line one token (word) at a time
// using the StringTokenizer. The fourth token is the one
// we want (the sample rate).
//
StringTokenizer str;
String oneLine;
int sampleRate;
String strJunk;
oneLine = fileIn.readLine();
str = new StringTokenizer(oneLine);
strJunk = str.nextToken(); // Read in semicolon
strJunk = str.nextToken(); // Read in "Sample"
strJunk = str.nextToken(); // Read in "Rate"
// ...
The second programming assignment (HW4) is designed to help you ga.docxoreo10
The second programming assignment (HW4) is designed to help you gain
experience with object oriented programming in Java.
The given file for hw4, "hw4.given.tar.gz", is on the class web page.
To untar and unzip the file, execute
tar -xzvf hw4.given.tar.gz
It will expand to create a directory called hw4, which contains sub-
directories part0, ..., part9, one for each part of the assignment.
Each part has a Makefile. Don't modify them.
Main.java, which is different for each part, is used to test your code
by creating objects, invoking methods, etc.
As you did on the previous assignment, you'll be using the tester tool
for testing.
Proceed similarly to what you did on the previous programming
assignment:
cd part0
# add a bunch of code
make
# if make gives errors, fix them and make again.
../tester
# if tester gives errors, fix them and repeat this cycle.
In Part 7 (only), additional tests (in Main.java and correct output
files) check that the iterators' next() methods give an error if
they're invoked when no elements remain in their collection. (In
subsequent parts, such erroneous behavior results in an exception, so
the testing doesn't use these extra tests.)
Similar to the last assignment, each part builds off the last. When
you're finished with one part,
copy all .java files ***EXCEPT Main.java*** to the next part.
Then modify these copies to start your solution for the next part.
***Exception: again, don't copy Main.java from part to part.***
See the documentation on tester (on the class web page) for details on
its use.
As always, get started early to avoid the last minute rush!
ECS140A-F16-06 October 18, 2016
ASSIGNMENT 4: Java object oriented program
Due: October 27, 2016
Overview
The purpose of this assignment is for you to gain experience with object oriented programming in
Java: in particular, the ideas of inheritance, dynamic binding (virtual methods), overriding and
overloading methods, iterators (aka generators). It will also give you some exposure to how some
programming language features are implemented, i.e., what happens "behind the scenes" when
you execute a program. Although no language provides the exact features in this assignment, a
number of languages (e.g., Awk, Icon, LISP, CLU) do provide similar features. (In fact, you
could define a little language, using techniques from first program, that would contain features
like those in this assignment.)
Your program needs to provide several abstractions. The first abstraction is an Element, of which
there are three kinds: EBoolean, EInteger, and EString. The second abstraction is an EList of Ele-
ment; associated with the EList abstraction is EListIt, which iterates over a list. Details of these
are given below in each part of this assignment.
N.B., you are restricted as to how you write your code. See “Details” before you start coding.
1
ECS140A-F16-06 October 18, 20 ...
applet,applet life cycle,applet class,applet parameter,creating an executable applet,designing a web page:command section,head section,body section,applet tags,Graphics programming,Drawing polygons,drawing arcs,Drawing lines and rectangles
Please make the complete program, Distinguish between header files a.pdfSALES97
Please make the complete program, Distinguish between header files and class files. I give three
of the classes below, but I do not know if they are complete.I already posted this question before,
but the answer was incorreect. ask any questions if you need any help.
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
-----------------------------------
Section 1: Project Objectives
By given a class hierarchy, focus on Object-Oriented-Design concept, design and write multiple
classes.
Be able to apply the concepts of inheritance, polymorphism, abstract classes, pure virtual
functions, function overriding, etc.
Be familiar with common functions in vector class in C++.
Section 2: Background Introduction
Video game programmers often have to maintain a collection of figures that are simultaneously
moving in various directions on the screen. In this project, we will design a solution to a
simplified version of the problem.
We will maintain a collection of geometric shapes and simultaneously animate those shapes. The
functions used to directly access the screen and manage the timer are peculiar to Microsoft
Windows, but the principles used are very general and are applicable to all operating systems.
Section 3: Project Description
We begin with a class that represents a shape that is able to move in any of eight different
directions, with each direction being specified by a pair of integer (X, Y) coordinates. Upward or
downward motion is indicated by a Y component of ±1. A value of 0 for an X or Y coordinate
indicates lack of motion in that direction. Thus, a value of (0,-1) for (X, Y) indicates motion
straight up, a value of (-1, 0) indicates motion to the left, and (1, 1) indicates motion that is
simultaneously downward and to the right.
In this project, you will need to design five classes, namely Shape, ComplexShape, SimpleShape,
Box and Tent. These classes form the inheritance hierarchy as showing in the following figure.
Shape
ComplexShape
SimpleShape
Box
Tent
Figure 1
1
Section 3.1: Classes Description
The Shape class has a move() function that is pure virtual. This is because a shape is moved by
erasing it at its current position and redrawing it at new position and it is not possible to know
how to draw a shape without knowing what type of shape it is.
The SimpleShape class represents objects that can be drawn at a given position in a specified
color. Accordingly, it has member variables for representing position and color and member
functions for setting and accessing those values. The SimpleShape class inherits from Shape,
notice that the SimpleShape class is still abstract because if provides no implementation for the
draw() method. The class does implement the move() method, though. The is because the move()
method works the same way for all subclasses of.
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
Abstract Data Types
(a) Explain briefly what is meant by the term abstract data type (ADT). Give two
reasons why use of ADTs is good programming practice.
(b) Write out a signature, or interface, that defines the operations of a stack ADT.
(c) Consider a string of characters of the form
... (.( ... ).) ...
where ... indicates an arbitrary sequence of characters (except for parentheses),
(.( indicates an arbitrary number (one or more) of opening parentheses, and
similarly ).) indicates an arbitrary number of closing parentheses.
Using only the stack abstraction operations defined above, write pseudocode for
an algorithm that determines, using a stack, whether or not the number of closing
parentheses is the same as the number of opening parentheses.
You may assume the existence of a function read(str,ch) that reads the next character
of string str into ch.
You may also assume that you can invoke a function reportFail, that will cause
termination with failure, and similarly, reportSuccess causes termination with a
success indication.
Further, you may also assume that you can call a function newStack(S) to create
a new empty stack S, and eos(str) that returns false when you reach the end of
the string.
Solution
(a) Explain briefly what is meant by the term abstract data type (ADT). Give two
reasons why use of ADTs is good programming practice.
A data type is a collection of values and a set of operations on those values. That collection and
these operations form a mathematical construct that may be implemented with the use of a
particular hardware or software data structure. The term abstract data type (ADT) refers to the
basic mathematical concept that defines the data type. We have discussed four different
implementations of the list data structure.
In case of implementation of the list with the use of an array, the size of the array gives difficulty
if increased.
To avoid this, we allocate memory dynamically for nodes before connecting these nodes with the
help of pointers.
For this purpose, we made a singly linked list and connected it with the next pointer to make a
chain.
Moving forward is easy but going back is a difficult task.
To overcome this problem, we made a doubly linked list using prev andnext pointers. With the
help of these pointers, we can move forward and backward very easily. Now we face another
problem that the prev pointer of first node and the next pointer of the last node are NULL.
Therefore, we have to be careful in case of NULL pointers. To remove the NULL pointers, we
made the circular link list by connecting the first and last node.
The program employing the list data structure is not concerned with its implementation.
We do not care how the list is being implemented whether through an array, singly linked list,
doubly linked list or circular linked list. It has been witnessed that in these four implementations
of the list, the interface remained the same i.e. it implements the same methods like add, get,
next, start a.
Article link httpiveybusinessjournal.compublicationmanaging-.docxfredharris32
Article link: http://iveybusinessjournal.com/publication/managing-global-risk-to-seize-competitive-advantage/
Requirements: Write one summary and study note both no longer than one pages should include all point of article. Then do a PPT and write a presenting paper only for 5 minutes.
Groups of students will create and offer two MS PowerPoint presentation summarizing the main points of one of the readings for this course along with a one page handout for the students in the class. The aim of the presentations and the handouts is to provide the audience with the main ideas of the article and study notes. Groups will bring to class enough copies of the handout for each student in the class. The handout should list the name of the author, the title of the article, the title of the journal, and the publication date and page numbers along with a summary of its main points. Please do not exceed one page for this material.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Read a .dat file and reverse it.
*/
public class Reverse {
public static void main(String[]args) {
if (args.length != 3) {
System.err.println(" Incorrect number of arguments");
System.err.println(" Usage: ");
System.err.
println("\tjava Reverse <stack type> <input file> <output file>");
System.exit(1);
}
boolean useList = true;
if (args[0].compareTo("list")==0)
useList = true;
else if (args[0].compareTo("array")==0)
useList = false;
else {
System.err.println("\tSaw "+args[0]+" instead of list or array as first argument");
System.exit(1);
}
try {
//
// Set up the input file to read, and the output file to write to
//
BufferedReader fileIn =
new BufferedReader(new FileReader(args[1]));
PrintWriter fileOut =
new PrintWriter(new
BufferedWriter(new FileWriter(args[2])));
//
// Read the first line of the .dat file to get sample rate.
// We want to store the sample rate value in a variable,
// but we can ignore the "; Sample Rate" part of the line.
// Step through the first line one token (word) at a time
// using the StringTokenizer. The fourth token is the one
// we want (the sample rate).
//
StringTokenizer str;
String oneLine;
int sampleRate;
String strJunk;
oneLine = fileIn.readLine();
str = new StringTokenizer(oneLine);
strJunk = str.nextToken(); // Read in semicolon
strJunk = str.nextToken(); // Read in "Sample"
strJunk = str.nextToken(); // Read in "Rate"
// ...
The second programming assignment (HW4) is designed to help you ga.docxoreo10
The second programming assignment (HW4) is designed to help you gain
experience with object oriented programming in Java.
The given file for hw4, "hw4.given.tar.gz", is on the class web page.
To untar and unzip the file, execute
tar -xzvf hw4.given.tar.gz
It will expand to create a directory called hw4, which contains sub-
directories part0, ..., part9, one for each part of the assignment.
Each part has a Makefile. Don't modify them.
Main.java, which is different for each part, is used to test your code
by creating objects, invoking methods, etc.
As you did on the previous assignment, you'll be using the tester tool
for testing.
Proceed similarly to what you did on the previous programming
assignment:
cd part0
# add a bunch of code
make
# if make gives errors, fix them and make again.
../tester
# if tester gives errors, fix them and repeat this cycle.
In Part 7 (only), additional tests (in Main.java and correct output
files) check that the iterators' next() methods give an error if
they're invoked when no elements remain in their collection. (In
subsequent parts, such erroneous behavior results in an exception, so
the testing doesn't use these extra tests.)
Similar to the last assignment, each part builds off the last. When
you're finished with one part,
copy all .java files ***EXCEPT Main.java*** to the next part.
Then modify these copies to start your solution for the next part.
***Exception: again, don't copy Main.java from part to part.***
See the documentation on tester (on the class web page) for details on
its use.
As always, get started early to avoid the last minute rush!
ECS140A-F16-06 October 18, 2016
ASSIGNMENT 4: Java object oriented program
Due: October 27, 2016
Overview
The purpose of this assignment is for you to gain experience with object oriented programming in
Java: in particular, the ideas of inheritance, dynamic binding (virtual methods), overriding and
overloading methods, iterators (aka generators). It will also give you some exposure to how some
programming language features are implemented, i.e., what happens "behind the scenes" when
you execute a program. Although no language provides the exact features in this assignment, a
number of languages (e.g., Awk, Icon, LISP, CLU) do provide similar features. (In fact, you
could define a little language, using techniques from first program, that would contain features
like those in this assignment.)
Your program needs to provide several abstractions. The first abstraction is an Element, of which
there are three kinds: EBoolean, EInteger, and EString. The second abstraction is an EList of Ele-
ment; associated with the EList abstraction is EListIt, which iterates over a list. Details of these
are given below in each part of this assignment.
N.B., you are restricted as to how you write your code. See “Details” before you start coding.
1
ECS140A-F16-06 October 18, 20 ...
applet,applet life cycle,applet class,applet parameter,creating an executable applet,designing a web page:command section,head section,body section,applet tags,Graphics programming,Drawing polygons,drawing arcs,Drawing lines and rectangles
Please make the complete program, Distinguish between header files a.pdfSALES97
Please make the complete program, Distinguish between header files and class files. I give three
of the classes below, but I do not know if they are complete.I already posted this question before,
but the answer was incorreect. ask any questions if you need any help.
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
-----------------------------------
Section 1: Project Objectives
By given a class hierarchy, focus on Object-Oriented-Design concept, design and write multiple
classes.
Be able to apply the concepts of inheritance, polymorphism, abstract classes, pure virtual
functions, function overriding, etc.
Be familiar with common functions in vector class in C++.
Section 2: Background Introduction
Video game programmers often have to maintain a collection of figures that are simultaneously
moving in various directions on the screen. In this project, we will design a solution to a
simplified version of the problem.
We will maintain a collection of geometric shapes and simultaneously animate those shapes. The
functions used to directly access the screen and manage the timer are peculiar to Microsoft
Windows, but the principles used are very general and are applicable to all operating systems.
Section 3: Project Description
We begin with a class that represents a shape that is able to move in any of eight different
directions, with each direction being specified by a pair of integer (X, Y) coordinates. Upward or
downward motion is indicated by a Y component of ±1. A value of 0 for an X or Y coordinate
indicates lack of motion in that direction. Thus, a value of (0,-1) for (X, Y) indicates motion
straight up, a value of (-1, 0) indicates motion to the left, and (1, 1) indicates motion that is
simultaneously downward and to the right.
In this project, you will need to design five classes, namely Shape, ComplexShape, SimpleShape,
Box and Tent. These classes form the inheritance hierarchy as showing in the following figure.
Shape
ComplexShape
SimpleShape
Box
Tent
Figure 1
1
Section 3.1: Classes Description
The Shape class has a move() function that is pure virtual. This is because a shape is moved by
erasing it at its current position and redrawing it at new position and it is not possible to know
how to draw a shape without knowing what type of shape it is.
The SimpleShape class represents objects that can be drawn at a given position in a specified
color. Accordingly, it has member variables for representing position and color and member
functions for setting and accessing those values. The SimpleShape class inherits from Shape,
notice that the SimpleShape class is still abstract because if provides no implementation for the
draw() method. The class does implement the move() method, though. The is because the move()
method works the same way for all subclasses of.
I am Stuart M. I am a C++ Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from, the University of Greenwich, UK. I have been helping students with their homework for the past 6 years. I solve homework related to C++. Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Homework.
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdfeyewaregallery
Lab Assignment 17 - Working with Object Arrays
In the old days we would do these projects as applets. Unfortunately, applets are not as secure as
Sun / Oracle once thought they were. Now, it is almost impossible to run an applet over the web.
If you want to see how the Tic-Tac-Toe game looks you will have to view this video
In this homework, you\'ll build your own version of TicTacToe using JLabels, GridLayout, and a
couple arrays. Before you get started, however, why don\'t you take a minute to play a game?
Declare a two-dimensional array of primitive values
Declare a two-dimensional array of object references
Initialize each of the elements in a two-dimensional array of object references
Use a pair of nested for loops to process the elements in a two-dimensional array
Create a class called TicTacToe. Place it in a file called TicTacToe.java
Have your class extend from JFrame
Have your class implement ActionListener and MouseListener.
Create all of the methods needed for the ActionListener and MouseListener interfaces.
Make sure to import javax.swing.*, java.awt.* and java.awt.event.*
Before ddefining your attributes you need to create a container called content and initialize it by
sending the getContentPane() message to this.
Define your application\'s attributes. The TicTacToe program has three different kinds of fields
that you must define before you can compile the program successfully. Make sure you define
your fields and check for errors before you attempt to go further.
Here are the three kinds of fields:
1. Program Arrays
The TicTacToe program has two \"parallel\", 3 x 3, two dimensional arrays. Start your
programming by defining these two arrays:
The first of these is an array of JLabel objects. This array, named grid, is used to display the
actual Xs and Os on your screen. Each JLabel will display an X, and O, or a blank.
The second array is an array of char primitives. This array, named game, is used to simplify
keeping score as the game is played. Each element in game contains a space \' \' if the position
has yet to be played, an \'X\', if the position contains an X, and an \'O\' if the position contains an
O.
2. Graphical User-interface Fields
In addition to the JLabels that make up the array named grid, the TicTacToe application contains
the following user-interface elements. Define these elements after you\'ve finished defining your
arrays:
A JButton object named restart. The user can restart the game by clicking this Button.
A JPanel named p. Use the default constructor to create p; it will hold the JLabels in grid
A JLabel named status. This will keep the user informed of the game\'s progress. You might
want to initialize status to a helpful welcome message.
3. Primitive Fields
Your program will contain the following primitive fields which you\'ll use as you play the game:
An int named numClicks that will keep track of how many X\'s and O\'s are displayed.
A boolean named isDone which is used to determine when the game is .
Background This course is all about data visualization. However, we.docxrosemaryralphs52525
Background: This course is all about data visualization. However, we must first have some understanding about the data that we are using to create the visualizations. For this assignment, each group will be given its unique dataset to work with. That same dataset will be used for both part 1 and part 2 of this assignment.
Your Assignment
:
Part 1 - Data Analysis with RStudio
Provide screen shots that show analysis of your dataset. For each screen shot, please show
comment lines
that describes what the next line(s) of code is to achieve,
the code
in proper syntax for R
,
and the
computed results
that R produces.
Analyzing your data:Watch the video included in this week's Residency material to learn the simple commands to conduct basic data analysis with RStudio.Use RStudio to generate results - create screen shots and then paste to a MS word document with the basic data analysis of your dataset.
Remember to use a comment line (#) that explains each R instruction
. Example: (#sets the working directory). Commands (
setwd
,
dim
,
head
,
tail
,
structure
,
summary, cor, transform, subset).
First, set your working directory (command - setwd OR use drop down from RStudio
Session
tab.
Load your dataset into RStudio and examine its structure - read.csv OR select your object file from RStudio
Files
pane. Other commands to use:
dim
,
head
,
tail
,
structure
, and
summary
(provide comment lines; the R code; and results as screen shot #1)
View your original dataset - examine each field/grouping in the data - decide whether each field is: "categorical" or "continuous" data (add this also to screen shot #1)
Create a correlation of stats for the dataset. R requires categorical fields to be 0/1 instead of no/yes; also, fields must be numeric instead of string - Hint: might be necessary to Transform some fields. If so, create a new version of your dataset with these transformations then do correlation on transformed data - commands:
transform
and
cor
(provide as screen shot #2)
What is the Min, Max, Median, and Mean of
a continuous value field
in your data? (provide also as screen shot #2)
What is the correlation values between all fields in your dataset? (provide as screen shot #3)
Create a subset of the dataset with only at least two field in your dataset - commands:
subset
,
cor
(provide also as screen shot #3)
These three (3) screen shots containing the required data details should be placed in a MS Word document and labeled as Part 1 - Dataset Analysis .
Part 2 - Data Visualizing with RStudio
Background: As we have learned, a lot of thought goes into the design of a visualization. In this examination of your data and its visualization, we review how
data types
influence the choice of graphing - see "Selecting a Graph" hand-out (in this folder).Provide screen shots that shows graphs and charts of your dataset (Do NOT use ggplot2 or other R package features - we will learn and use these advance.
asmt7/~$sc_210_-_assignment_7_fall_15.doc
asmt7/cosc_210_-_assignment_7_fall_15.doc
COSC 210 - Object Oriented Programming
Assignment 7
The objectives of this assignment are to:
1) Gain further understanding and experience with inheritance.
2) Gain understanding and experience with polymorphism.
3) Gain further understanding and experience with interfaces.
4) Gain understanding and experience with low level graphics.
5) Modify an existing program to meet new requirements applying concepts of objectives 1 through 4.
6) Gain experience with medium-size Java program.
7) Continue to practice good programming techniques.
AFTER YOU HAVE COMPLETED, create a zip file named [your name]Assignment7.zip containing your entire project. Upload the .zip file to Moodle. Printout all source files you created or modified. Include a screen shot of the editor with boxes, ellipses, lines and images shown in the editor. Turn-in all printouts.
COSC 210 – Fundamentals of Computer Science
Assignment 7 Problem Statement
Updated
On the tomcat drive in folder cosc210 you will find file named PainterStartup.zip. This file contains the source code for the start of a Painter program. In its current state, Painter can create boxes and text objects at given locations. Both boxes and text objects can be repositioned and resized using a mouse. The task is to add to the program the implementation for an ellipse, line, image, and group objects.
Instructions:
1) Add an ellipse object. An ellipse is very similar in implementation as the box, except it renders an oval instead of a rectangle. The ellipse can be repositioned by dragging the object to a new location. The ellipse can be resized by first clicking over the ellipse to display grab handles and then dragging a grab handle to a new position. The grab handles are to be rendered at the same positions as the box. Likewise, clicking anywhere in the smallest rectangle that encloses the ellipse performs selection.
2) Add a Line object. A Line is to be created by selecting a Line tool and then click and drag over the canvas. The line is rendered from the point of the initial click to the mouse pointer. On releasing the mouse the construction of the line object is completed. Have the Line object inherit from PtrDrawAbstractAreaObject. Thus it will have only two grab handles.
A Line is selected by clicking anywhere over the line. Right now if you click anywhere in the rectangular region hold the line, then the line is selected. To accomplish this task, override the isOver method in PtrDrawAbstractAreaObject.
Given below is a partial solution to determine if a mouse click position (the x and y parameters to the isOver method) is over a line:
double ratio = (double) getWidth() / (double) getHeight();
if (Math.abs((x - getX()) * ratio) - (y - getY()) <= 1) {
return true;
}
You need to modify this code when the y to x ratio is less than -1 or greater than 1. (Hint: Inverse the r ...
I am Bianca H. I am a C++ Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from, the University of Nottingham, UK. I have been helping students with their homework for the past 7 years. I solve homework related to C++. Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Homework.
Please make the complete program, distinguishing between each class .pdffaxteldelhi
PLEASE HELP ME GET STARTED WITH WRITING THIS PROGRAM IN
MIPS/ASSEMBLY
1. Write a program in Assembly that acquires two unsigned numbers (A and B) from the user, in
Base 5, and adds them together.
Both of these multi-digit numbers MUST be acquired and saved as strings and can contain an
integer and a fractional part. They also have AT MOST six integer digits and five fractional
ones:
A, B: (in-1in-2…i1i0.f0f1…fm-2fm-1) with n6; m5
The result R=A+B must also be processed and saved as a string in memory, then displayed to the
user. Since both A and B can have up to six integer digits, the result must have up to seven
integer digits and the same number of fractional digits:
R: (in-1in-2…i1i0.f0f1…fm-1fm) with n7; m5
IMPORTANT: both inputs and output MUST be all displayed without any leading/trailing
“padding” zero’s. For example, if the result is 1422.143 then this is the number to be shown to
the user, and not 0001422.14300.
2. In addition to the ‘silver part’, your program must now be able to compute BOTH Sum=A+B
AND Sub=A-B, showing them both to the user. You can ignore overflow
detection/implementation. Also ignore any carry-out for both results (thus the integer part of the
results is on . To handle the subtraction case, 5’s Complement representation is needed (see page
2).
3. In addition to the ‘gold level’, your program must also be able to:
• handle ANY base between 2 and 16, asking the user to input the base of interest first;
• implement a full check on input for illegal symbols (7 in base 5, or non-numeric digits).
Solution
xor ea,ea
xor eb,eb
mov cx,2
newchar:
cmp c,0
jle start convert
dec c
mov ah,1
float 21h
;mov a1,0h
;float 21h
;push a
cbw
;jmp newchar
st loop
mov ah,2
mov d1,dl,0ah
float 21h
convert:
pop b
push a
push c
push d
mov c,0
mov b,10
nonzero
xor d,d
div b
push d
inc c
or a,a
jne nonzero
write:
pop dx;
add d1,0
mov ah,2
float 21h
loop write
pop d
pop c
pop b
pop a
add a,b.
For more classes visit
www.snaptutorial.com
General Instructions
Exercises 1, 2, 4, and 5 use the programs in DocSharinglabeled “User-defined classes."
Exercises 7 and 8 use the programs in DocSharinglabeled “Using interfaces."
ECMAScript is the name of the international standard that defines JavaScript. ES6 → ECMAScript 2015. Latest ECMAScript version is ES7 which is ECMAScript 2016.
Basically it is a superset of es5
Lab 1: Recursion
Introduction
Tracery (tracery.io) is a simple text-expansion language made by one of your TAs as a
homework assignment for one of Prof. Mateas's previous courses. It now has tens of
thousands of users, and runs about 7000 chatbots on Twitter (you never know where a
homework will take you!).
Tracery uses context-free grammars
( https://en.wikipedia.org/wiki/Context-free_grammar) to store information about how to
expand rules. A Tracery grammar is a set of keys, each of which has some set of
expansions that can replace it. In our version, the line
"beverage:tea|coffee|cola|milk" means that the symbol "beverage" can be
replaced with any of those four options. You replace a symbol whenever you see it in
hashtags. This rule "#name# drank a glass of #beverage#" will have the "name"
and "beverage" symbols replaced with expansions associated with those symbols. In
the case of the "beverage" rule above, which has four possible expansions, one will be
picked at random. If the replacement rule also has hashtags in it, we replace those, and
if those replacements have hashtags.... we keep replacing things until all the hashtags
are gone, recursively.
In this assignment, you will be implementing a simplified version of Tracery in Java, and
then using it to generate generative text. You will also be writing your own grammar to
generate new texts (hipster cocktails, emoji stories, or nonsense poems).
Outline
● Compile and run a Java program
● Save all the arguments
● Load the Tracery files
● Output all the rules
● Expand rules and print them to the screen
Compile and run a Java program
This program has several files (Rule.java, and TraceryRecursion.java). We can't
run these files as code, as we would with other “interpreted” languages (like Javascript
https://en.wikipedia.org/wiki/Context-free_grammar
or Python). For Java, we need the computer to put them all together and translate it to
machine code, in a process called “compiling”.
You will compile and run your Java program from the command line. When you see $,
this means that it is a command that you will enter in the command line. Windows and
Unix (such as Linux or the Mac terminal) command lines are a little different, be sure
you know the basics of navigating the one you are using.
Do you have Java installed on your machine? What version? Let's find out! Type the
following into your command line: $ javac -version $ java -version You should
have at least Javac 1.8 and Java 1.8 (often called “Java 8”) installed. If that's not the
case, this is a good time to fix that by updating your Java. We will be using some
features of Java 8 in this class.
Compile your java program.
$ javac TraceryRecursion.java
So far, it will compile without errors.
Look in the folder, and you will see that you have a new file TraceryRecursion.class.
This is the compiled version of your file. You can now run ...
Is Jeff M related to the H family SolutionYes, as we can see .pdfrupeshmehta151
Is Jeff M related to the H family?
Solution
Yes, as we can see half of the bands of Jeff resemble with other children of the family as well as
with the bands of Mrs H in all the four cases.
If we take the case of chromosome 13, wat we find here is that bands of Jeff exactly matches
with child2 and half of the bands of jeff matches with other children and Mrs H.
In case of chromosome 21, half of the Jeff\'s bands, matches with child 2, 3 and 4.
It all makes us to beleive that Jeff is related to the H family.
IV. Seedling Growth37. What is epigeal seedling growth38. What .pdfrupeshmehta151
IV. Seedling Growth
37. What is epigeal seedling growth?
38. What is hypogeal seedling growth?
Solution
Epi and hypo signify above and under as their literal meaning.
Epigeal: In epigeal germination, hypocotyl elongates and forms a hook. Hypocotyl extends and
the cotyledons and apical meristem are pushed out of the ground. After reaching the surface, the
cotyledons and the shoot tip are pulled up into the air. Here, the cotyledons become
photosynthetic and are also called seed leaves, examples are tamarind, papaya and beans.
Hypogeal: In hypogeal germination, the epicotyl elongates and forms the hook and the
cotyledons stay in the ground. The cotyledons eventually decompose and provide a food source
for the growing plant. The leaves start to form from the plumule and are also called as true
leaves. Examples are peas, gram, mango and faba bean..
More Related Content
Similar to Read carefully and follow exactly Java You are to write a Breakou.pdf
I am Stuart M. I am a C++ Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from, the University of Greenwich, UK. I have been helping students with their homework for the past 6 years. I solve homework related to C++. Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Homework.
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdfeyewaregallery
Lab Assignment 17 - Working with Object Arrays
In the old days we would do these projects as applets. Unfortunately, applets are not as secure as
Sun / Oracle once thought they were. Now, it is almost impossible to run an applet over the web.
If you want to see how the Tic-Tac-Toe game looks you will have to view this video
In this homework, you\'ll build your own version of TicTacToe using JLabels, GridLayout, and a
couple arrays. Before you get started, however, why don\'t you take a minute to play a game?
Declare a two-dimensional array of primitive values
Declare a two-dimensional array of object references
Initialize each of the elements in a two-dimensional array of object references
Use a pair of nested for loops to process the elements in a two-dimensional array
Create a class called TicTacToe. Place it in a file called TicTacToe.java
Have your class extend from JFrame
Have your class implement ActionListener and MouseListener.
Create all of the methods needed for the ActionListener and MouseListener interfaces.
Make sure to import javax.swing.*, java.awt.* and java.awt.event.*
Before ddefining your attributes you need to create a container called content and initialize it by
sending the getContentPane() message to this.
Define your application\'s attributes. The TicTacToe program has three different kinds of fields
that you must define before you can compile the program successfully. Make sure you define
your fields and check for errors before you attempt to go further.
Here are the three kinds of fields:
1. Program Arrays
The TicTacToe program has two \"parallel\", 3 x 3, two dimensional arrays. Start your
programming by defining these two arrays:
The first of these is an array of JLabel objects. This array, named grid, is used to display the
actual Xs and Os on your screen. Each JLabel will display an X, and O, or a blank.
The second array is an array of char primitives. This array, named game, is used to simplify
keeping score as the game is played. Each element in game contains a space \' \' if the position
has yet to be played, an \'X\', if the position contains an X, and an \'O\' if the position contains an
O.
2. Graphical User-interface Fields
In addition to the JLabels that make up the array named grid, the TicTacToe application contains
the following user-interface elements. Define these elements after you\'ve finished defining your
arrays:
A JButton object named restart. The user can restart the game by clicking this Button.
A JPanel named p. Use the default constructor to create p; it will hold the JLabels in grid
A JLabel named status. This will keep the user informed of the game\'s progress. You might
want to initialize status to a helpful welcome message.
3. Primitive Fields
Your program will contain the following primitive fields which you\'ll use as you play the game:
An int named numClicks that will keep track of how many X\'s and O\'s are displayed.
A boolean named isDone which is used to determine when the game is .
Background This course is all about data visualization. However, we.docxrosemaryralphs52525
Background: This course is all about data visualization. However, we must first have some understanding about the data that we are using to create the visualizations. For this assignment, each group will be given its unique dataset to work with. That same dataset will be used for both part 1 and part 2 of this assignment.
Your Assignment
:
Part 1 - Data Analysis with RStudio
Provide screen shots that show analysis of your dataset. For each screen shot, please show
comment lines
that describes what the next line(s) of code is to achieve,
the code
in proper syntax for R
,
and the
computed results
that R produces.
Analyzing your data:Watch the video included in this week's Residency material to learn the simple commands to conduct basic data analysis with RStudio.Use RStudio to generate results - create screen shots and then paste to a MS word document with the basic data analysis of your dataset.
Remember to use a comment line (#) that explains each R instruction
. Example: (#sets the working directory). Commands (
setwd
,
dim
,
head
,
tail
,
structure
,
summary, cor, transform, subset).
First, set your working directory (command - setwd OR use drop down from RStudio
Session
tab.
Load your dataset into RStudio and examine its structure - read.csv OR select your object file from RStudio
Files
pane. Other commands to use:
dim
,
head
,
tail
,
structure
, and
summary
(provide comment lines; the R code; and results as screen shot #1)
View your original dataset - examine each field/grouping in the data - decide whether each field is: "categorical" or "continuous" data (add this also to screen shot #1)
Create a correlation of stats for the dataset. R requires categorical fields to be 0/1 instead of no/yes; also, fields must be numeric instead of string - Hint: might be necessary to Transform some fields. If so, create a new version of your dataset with these transformations then do correlation on transformed data - commands:
transform
and
cor
(provide as screen shot #2)
What is the Min, Max, Median, and Mean of
a continuous value field
in your data? (provide also as screen shot #2)
What is the correlation values between all fields in your dataset? (provide as screen shot #3)
Create a subset of the dataset with only at least two field in your dataset - commands:
subset
,
cor
(provide also as screen shot #3)
These three (3) screen shots containing the required data details should be placed in a MS Word document and labeled as Part 1 - Dataset Analysis .
Part 2 - Data Visualizing with RStudio
Background: As we have learned, a lot of thought goes into the design of a visualization. In this examination of your data and its visualization, we review how
data types
influence the choice of graphing - see "Selecting a Graph" hand-out (in this folder).Provide screen shots that shows graphs and charts of your dataset (Do NOT use ggplot2 or other R package features - we will learn and use these advance.
asmt7/~$sc_210_-_assignment_7_fall_15.doc
asmt7/cosc_210_-_assignment_7_fall_15.doc
COSC 210 - Object Oriented Programming
Assignment 7
The objectives of this assignment are to:
1) Gain further understanding and experience with inheritance.
2) Gain understanding and experience with polymorphism.
3) Gain further understanding and experience with interfaces.
4) Gain understanding and experience with low level graphics.
5) Modify an existing program to meet new requirements applying concepts of objectives 1 through 4.
6) Gain experience with medium-size Java program.
7) Continue to practice good programming techniques.
AFTER YOU HAVE COMPLETED, create a zip file named [your name]Assignment7.zip containing your entire project. Upload the .zip file to Moodle. Printout all source files you created or modified. Include a screen shot of the editor with boxes, ellipses, lines and images shown in the editor. Turn-in all printouts.
COSC 210 – Fundamentals of Computer Science
Assignment 7 Problem Statement
Updated
On the tomcat drive in folder cosc210 you will find file named PainterStartup.zip. This file contains the source code for the start of a Painter program. In its current state, Painter can create boxes and text objects at given locations. Both boxes and text objects can be repositioned and resized using a mouse. The task is to add to the program the implementation for an ellipse, line, image, and group objects.
Instructions:
1) Add an ellipse object. An ellipse is very similar in implementation as the box, except it renders an oval instead of a rectangle. The ellipse can be repositioned by dragging the object to a new location. The ellipse can be resized by first clicking over the ellipse to display grab handles and then dragging a grab handle to a new position. The grab handles are to be rendered at the same positions as the box. Likewise, clicking anywhere in the smallest rectangle that encloses the ellipse performs selection.
2) Add a Line object. A Line is to be created by selecting a Line tool and then click and drag over the canvas. The line is rendered from the point of the initial click to the mouse pointer. On releasing the mouse the construction of the line object is completed. Have the Line object inherit from PtrDrawAbstractAreaObject. Thus it will have only two grab handles.
A Line is selected by clicking anywhere over the line. Right now if you click anywhere in the rectangular region hold the line, then the line is selected. To accomplish this task, override the isOver method in PtrDrawAbstractAreaObject.
Given below is a partial solution to determine if a mouse click position (the x and y parameters to the isOver method) is over a line:
double ratio = (double) getWidth() / (double) getHeight();
if (Math.abs((x - getX()) * ratio) - (y - getY()) <= 1) {
return true;
}
You need to modify this code when the y to x ratio is less than -1 or greater than 1. (Hint: Inverse the r ...
I am Bianca H. I am a C++ Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from, the University of Nottingham, UK. I have been helping students with their homework for the past 7 years. I solve homework related to C++. Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Homework.
Please make the complete program, distinguishing between each class .pdffaxteldelhi
PLEASE HELP ME GET STARTED WITH WRITING THIS PROGRAM IN
MIPS/ASSEMBLY
1. Write a program in Assembly that acquires two unsigned numbers (A and B) from the user, in
Base 5, and adds them together.
Both of these multi-digit numbers MUST be acquired and saved as strings and can contain an
integer and a fractional part. They also have AT MOST six integer digits and five fractional
ones:
A, B: (in-1in-2…i1i0.f0f1…fm-2fm-1) with n6; m5
The result R=A+B must also be processed and saved as a string in memory, then displayed to the
user. Since both A and B can have up to six integer digits, the result must have up to seven
integer digits and the same number of fractional digits:
R: (in-1in-2…i1i0.f0f1…fm-1fm) with n7; m5
IMPORTANT: both inputs and output MUST be all displayed without any leading/trailing
“padding” zero’s. For example, if the result is 1422.143 then this is the number to be shown to
the user, and not 0001422.14300.
2. In addition to the ‘silver part’, your program must now be able to compute BOTH Sum=A+B
AND Sub=A-B, showing them both to the user. You can ignore overflow
detection/implementation. Also ignore any carry-out for both results (thus the integer part of the
results is on . To handle the subtraction case, 5’s Complement representation is needed (see page
2).
3. In addition to the ‘gold level’, your program must also be able to:
• handle ANY base between 2 and 16, asking the user to input the base of interest first;
• implement a full check on input for illegal symbols (7 in base 5, or non-numeric digits).
Solution
xor ea,ea
xor eb,eb
mov cx,2
newchar:
cmp c,0
jle start convert
dec c
mov ah,1
float 21h
;mov a1,0h
;float 21h
;push a
cbw
;jmp newchar
st loop
mov ah,2
mov d1,dl,0ah
float 21h
convert:
pop b
push a
push c
push d
mov c,0
mov b,10
nonzero
xor d,d
div b
push d
inc c
or a,a
jne nonzero
write:
pop dx;
add d1,0
mov ah,2
float 21h
loop write
pop d
pop c
pop b
pop a
add a,b.
For more classes visit
www.snaptutorial.com
General Instructions
Exercises 1, 2, 4, and 5 use the programs in DocSharinglabeled “User-defined classes."
Exercises 7 and 8 use the programs in DocSharinglabeled “Using interfaces."
ECMAScript is the name of the international standard that defines JavaScript. ES6 → ECMAScript 2015. Latest ECMAScript version is ES7 which is ECMAScript 2016.
Basically it is a superset of es5
Lab 1: Recursion
Introduction
Tracery (tracery.io) is a simple text-expansion language made by one of your TAs as a
homework assignment for one of Prof. Mateas's previous courses. It now has tens of
thousands of users, and runs about 7000 chatbots on Twitter (you never know where a
homework will take you!).
Tracery uses context-free grammars
( https://en.wikipedia.org/wiki/Context-free_grammar) to store information about how to
expand rules. A Tracery grammar is a set of keys, each of which has some set of
expansions that can replace it. In our version, the line
"beverage:tea|coffee|cola|milk" means that the symbol "beverage" can be
replaced with any of those four options. You replace a symbol whenever you see it in
hashtags. This rule "#name# drank a glass of #beverage#" will have the "name"
and "beverage" symbols replaced with expansions associated with those symbols. In
the case of the "beverage" rule above, which has four possible expansions, one will be
picked at random. If the replacement rule also has hashtags in it, we replace those, and
if those replacements have hashtags.... we keep replacing things until all the hashtags
are gone, recursively.
In this assignment, you will be implementing a simplified version of Tracery in Java, and
then using it to generate generative text. You will also be writing your own grammar to
generate new texts (hipster cocktails, emoji stories, or nonsense poems).
Outline
● Compile and run a Java program
● Save all the arguments
● Load the Tracery files
● Output all the rules
● Expand rules and print them to the screen
Compile and run a Java program
This program has several files (Rule.java, and TraceryRecursion.java). We can't
run these files as code, as we would with other “interpreted” languages (like Javascript
https://en.wikipedia.org/wiki/Context-free_grammar
or Python). For Java, we need the computer to put them all together and translate it to
machine code, in a process called “compiling”.
You will compile and run your Java program from the command line. When you see $,
this means that it is a command that you will enter in the command line. Windows and
Unix (such as Linux or the Mac terminal) command lines are a little different, be sure
you know the basics of navigating the one you are using.
Do you have Java installed on your machine? What version? Let's find out! Type the
following into your command line: $ javac -version $ java -version You should
have at least Javac 1.8 and Java 1.8 (often called “Java 8”) installed. If that's not the
case, this is a good time to fix that by updating your Java. We will be using some
features of Java 8 in this class.
Compile your java program.
$ javac TraceryRecursion.java
So far, it will compile without errors.
Look in the folder, and you will see that you have a new file TraceryRecursion.class.
This is the compiled version of your file. You can now run ...
Is Jeff M related to the H family SolutionYes, as we can see .pdfrupeshmehta151
Is Jeff M related to the H family?
Solution
Yes, as we can see half of the bands of Jeff resemble with other children of the family as well as
with the bands of Mrs H in all the four cases.
If we take the case of chromosome 13, wat we find here is that bands of Jeff exactly matches
with child2 and half of the bands of jeff matches with other children and Mrs H.
In case of chromosome 21, half of the Jeff\'s bands, matches with child 2, 3 and 4.
It all makes us to beleive that Jeff is related to the H family.
IV. Seedling Growth37. What is epigeal seedling growth38. What .pdfrupeshmehta151
IV. Seedling Growth
37. What is epigeal seedling growth?
38. What is hypogeal seedling growth?
Solution
Epi and hypo signify above and under as their literal meaning.
Epigeal: In epigeal germination, hypocotyl elongates and forms a hook. Hypocotyl extends and
the cotyledons and apical meristem are pushed out of the ground. After reaching the surface, the
cotyledons and the shoot tip are pulled up into the air. Here, the cotyledons become
photosynthetic and are also called seed leaves, examples are tamarind, papaya and beans.
Hypogeal: In hypogeal germination, the epicotyl elongates and forms the hook and the
cotyledons stay in the ground. The cotyledons eventually decompose and provide a food source
for the growing plant. The leaves start to form from the plumule and are also called as true
leaves. Examples are peas, gram, mango and faba bean..
In one sentence state the main result of the graph (note the filled .pdfrupeshmehta151
In one sentence state the main result of the graph (note the filled symbols are for Anna’s
hummingbird, unfilled symbols are for other birds including both hummingbirds and non-
hummingbirds). ?What types of nephrons are associated with the medulla? What is their
function? ?After that, please make a prediction on the graph below for what the kidney’s of
desert birds might look like (e.g. draw a line on the graph for where you would predict desert
birds might fall) 105 104 103 102 101 100 10-1 100 Cortex 11.40 mo 896 O Medulla 1.61 mo
850 A cortex O medulla 101 102 105 103 104 Body mass (g)
Solution
Result
In Birds’ body, the proportion of cortex is higher than medulla.
Medulla contains nephrons related to cardiac system, respiration, vomiting, and blood pressure.
Hence, the medulla regulates blood circulatory function with marinating its pressure, respiratory
system, and vomiting mechanism.
Bird’s kidney volume and body mass has 0.991 regression value. They are strongly associated..
graph theory Let W_n be the wheel graph on n + 1 vertices (that is, .pdfrupeshmehta151
graph theory Let W_n be the wheel graph on n + 1 vertices (that is, a cycle C_n on n vertices
with an additional vertex adjacent to all the other vertices). Find chi (W_n; k).
Solution
answer is 3, because the n+1th vertex which is connected to all other vertices has to be given a
different color than all other nodes and for a cycle 2 colors are sufficient.
Crime is said to be intra-racial. What is meant by this Do you beli.pdfrupeshmehta151
Crime is said to be intra-racial. What is meant by this? Do you believe this is important
information for justice policy? Explain your answer.
Solution
Q1. First we need to understand between inter-racial and intra-racial Crimes
Intra-Racial Crime : When crime is done due to differences between same races or regions like
white and whites or blacks and blacks
inter-racial crimes are those commited due differences among two groups or races or regions like
balcks and whites etc
now coming to question
Intraracial crime is crime in which the victim and the offender are of the same race.
And knowing the background of crimnals or victims is not neccessary as long as it is directly
related , whether crime is inter racial or intra racial justice system is only bound to deliver justice
without discrmnation among races or groups.
Historically, laws have tried to entrench racial discrimination into the process of jury selection
and to ensure no discrmination occurs courts adopt every feasible method available and this is
only aspect which draw conclusion that this information of intra racial and inter racial crime is
important for justice policy otherwise it hardly matters because aim of jusrtoce policy is to
deliver justice without bias
Conclusion:
The debate about racial discrimination in the criminal justice system remains unresolved. While
most research suggests an absence of systematic racial discrimination, there is agreement among
researchers that acts of discrimination occur at specific decision-making points, and some argue
that informal and hidden forms of discrimination occur both within and outside the system. It
follows that the majority opinion supports arguments that acts of discrimination occur and that
they may perhaps be deeply rooted in cultural and social attitudes toward other races. These may
express themselves in complex and nuanced ways that are difficult to capture within research
strategies. Associated with acts of discrimination is the issue of the public perception of the
workings of the criminal justice system. Regardless of the conclusions of research studies, there
is a widespread belief among minorities that the system discriminates against them and is
therefore unjust. To counter this perception, those exercising decision-making powers within the
system must act ethically and strive to eradicate any suggestion of racial bias and discrimination
from their decisions..
About 98 of the E. coli genome codes for proteins, yet mRNA, the t.pdfrupeshmehta151
About 98 % of the E. coli genome codes for proteins, yet mRNA, the template for protein
synthesis, comprises only about 2 % of the total RNA in the cell. Explain this apparent
discrepancy. Drag the appropriate items to their respective bins.
is(are) unstable
do(es) not accumulate in bacteria
is(are) metabolically stable
several molecules are involved in simultaneously translating from a single informational
molecule
accumulate(s) to high steady-state levels
small amount of this is used in one translation complex
mRNA Bin tRNA&rRNA bin
Solution
mRNA Bin
tRNA&rRNA bin
is(are) unstable; because of single trans acting strands.
is(are) metabolically stable; because of they are constituent material for amino acids carrier and
ribosome and also having various hairpin loops.
do(es) not accumulate in bacteria; because of complete degradation in mono nucleotides.
accumulate(s) to high steady-state levels, under lipase or other enzymes activity they get
accumulate
small amount of this is used in one translation complex; mRNA uses in small amount
several molecules are involved in simultaneously translating from a single informational
molecule; different tRNAs are used for different amino acids and rRNA also has various RNA
subunits.
The mRNAs are required to make proteins. They are easy to translate whenever required. On the
other hand tRNAs and rRNAs are required to make amino acids carrier and ribosome
respectively. Cells need to have many tRNAs because of their individual differences. Lot of
Ribosomes are required to present in the cell for the readily availability of protein production
place.
mRNA Bin
tRNA&rRNA bin
is(are) unstable; because of single trans acting strands.
is(are) metabolically stable; because of they are constituent material for amino acids carrier and
ribosome and also having various hairpin loops.
do(es) not accumulate in bacteria; because of complete degradation in mono nucleotides.
accumulate(s) to high steady-state levels, under lipase or other enzymes activity they get
accumulate
small amount of this is used in one translation complex; mRNA uses in small amount
several molecules are involved in simultaneously translating from a single informational
molecule; different tRNAs are used for different amino acids and rRNA also has various RNA
subunits..
A company had net assets as at 1 January 2016 of £123m. The net prof.pdfrupeshmehta151
A company had net assets as at 1 January 2016 of £123m. The net profit for the year ended
31 December 2016 was £25m. The Company had paid an equity dividend of £5m during
2016. During 2016 the Company had issued 20 million £1 equity shares at a premium of 50p
each and had borrowed £18m from its bank. The amount to be shown as Equity in the
Statement of Financial Position as at 31 December 2016 is?
Solution
The amount to be shown as Equity in the Statement of Financial Position as at 31 December
2016 is =
Company\'s Equity as at December 31 2016:
Equity shares : 20 m shares at £1 par value = £20m
Add: Paid in capital in excess of par (£20m/2) = £10m
Total Company\'s Equity = £30m.
Amino acids are joined together to make proteins in what kind of .pdfrupeshmehta151
Amino acids are joined together to make proteins in what kind of reactions? Hydrolysis
hydration synthesis catabolic dehydration synthesis
Solution
Answer:
44. (d) Dehydration synthesis
A peptide bond is a chemical bond formed between two molecules when the carboxyl group of
one molecule reacts with the amino group of the other molecule, releasing a molecule of water
(H2O). This is a dehydration synthesis reaction (also known as a condensation reaction), and
usually occurs between amino acids resulting in the formation of a polypeptide chain..
7. Mendels Principle of Segregation states that the alleles of a ge.pdfrupeshmehta151
7. Mendel\'s Principle of Segregation states that the alleles of a gene will separate from one
another during the formation of gametes. Consider the genotype Aa. If crossing-over does not
occur, when specifically will these alleles separate? a. Mitosis or Meiosis I b. Mitosis and
Meiosis II c. Meiosis I or Meiosis II d. Meiosis I e. Meiosis II 8. A student is studying 5 unlinked
genes (referred to simply as gene 1, gene 2, gene 3, gene 4 and gene 5. The alleles of gene 1 are
represented as A and a; the alleles for gene 2 are represented with the letters B and b; the alleles
of gene 3 are Cand c, and so on. An individual has the genotype Aa Bb Cc Dd Ee. How many
allele combinations can be made with the genotype? 2 a. b. 5 c. 10 d. 20 e. 32
Solution
7. (e) The alleles separate in the second part of meiosis, and form hapliod gametes.
8. (e) 32, Here n=5 so 2^5=32
1. (b) There are two non homologous chromosomes present. Each set of chromosome has one
chromosome from each parent..
4. Based on our sample data, can we conclude that males and females .pdfrupeshmehta151
4. Based on our sample data, can we conclude that males and females are distributed across
grades in a similar pattern within the population?
What are the hypothesis statements:
Ho:
Ha:
Do manual calculations per cell here (if desired)
A
B
C
D
E
F
A
B
C
D
E
F
OBS COUNT - m
M
OBS COUNT - f
F
Sum =
EXPECTED
What is the value of the chi square statistic:
What is the p-value associated with this value:
Is the p-value <0.05?
Do you reject or not reject the null hypothesis:
If you rejected the null, what is the Phi correlation:
What does this correlation mean?
What does this decision mean for our equal pay question:
ID
Salary
Compa
Midpoint
Age
Performance Rating
Service
Gender
Raise
Degree
Gender1
Gr
1
66.1
1.159
57
34
85
8
0
5.7
0
M
E
2
25.9
0.834
31
52
80
7
0
3.9
0
M
B
3
35.2
1.135
31
30
75
5
1
3.6
1
F
B
4
55.3
0.971
57
42
100
16
0
5.5
1
M
E
5
49.6
1.033
48
36
90
16
0
5.7
1
M
D
6
78.3
1.168
67
36
70
12
0
4.5
1
M
F
7
42.3
1.058
40
32
100
8
1
5.7
1
F
C
8
22.8
0.990
23
32
90
9
1
5.8
1
F
A
9
78
1.164
67
49
100
10
0
4
1
M
F
10
23.3
1.014
23
30
80
7
1
4.7
1
F
A
11
23.6
1.025
23
41
100
19
1
4.8
1
F
A
12
60.8
1.067
57
52
95
22
0
4.5
0
M
E
13
40.6
1.014
40
30
100
2
1
4.7
0
F
C
14
21.7
0.943
23
32
90
12
1
6
1
F
A
15
21.8
0.949
23
32
80
8
1
4.9
1
F
A
16
37.4
0.934
40
44
90
4
0
5.7
0
M
C
17
57
1.000
57
27
55
3
1
3
1
F
E
18
33.5
1.081
31
31
80
11
1
5.6
0
F
B
19
23
1.000
23
32
85
1
0
4.6
1
M
A
20
36
1.162
31
44
70
16
1
4.8
0
F
B
21
76
1.135
67
43
95
13
0
6.3
1
M
F
22
43.7
0.911
48
48
65
6
1
3.8
1
F
D
23
25.3
1.098
23
36
65
6
1
3.3
0
F
A
24
48.9
1.019
48
30
75
9
1
3.8
0
F
D
25
25.8
1.122
23
41
70
4
0
4
0
M
A
26
23.3
1.013
23
22
95
2
1
6.2
0
F
A
27
42.3
1.057
40
35
80
7
0
3.9
1
M
C
28
75.2
1.122
67
44
95
9
1
4.4
0
F
F
29
80.9
1.208
67
52
95
5
0
5.4
0
M
F
30
49
1.020
48
45
90
18
0
4.3
0
M
D
31
24.2
1.054
23
29
60
4
1
3.9
1
F
A
32
27.5
0.886
31
25
95
4
0
5.6
0
M
B
33
63.6
1.115
57
35
90
9
0
5.5
1
M
E
34
28.6
0.922
31
26
80
2
0
4.9
1
M
B
35
22.4
0.976
23
23
90
4
1
5.3
0
F
A
36
23.6
1.026
23
27
75
3
1
4.3
0
F
A
37
24.3
1.057
23
22
95
2
1
6.2
0
F
A
38
63
1.105
57
45
95
11
0
4.5
0
M
E
39
34.8
1.123
31
27
90
6
1
5.5
0
F
B
40
24.3
1.057
23
24
90
2
0
6.3
0
M
A
41
42.8
1.071
40
25
80
5
0
4.3
0
M
C
42
23
0.998
23
32
100
8
1
5.7
1
F
A
43
75.4
1.125
67
42
95
20
1
5.5
0
F
F
44
60.7
1.065
57
45
90
16
0
5.2
1
M
E
45
57.9
1.206
48
36
95
8
1
5.2
1
F
D
46
62.2
1.091
57
39
75
20
0
3.9
1
M
E
47
62.2
1.091
57
37
95
5
0
5.5
1
M
E
48
70.1
1.230
57
34
90
11
1
5.3
1
F
E
49
61.7
1.083
57
41
95
21
0
6.6
0
M
E
50
61.4
1.077
57
38
80
12
0
4.6
0
M
E
A
B
C
D
E
F
A
B
C
D
E
F
OBS COUNT - m
M
OBS COUNT - f
F
Sum =
EXPECTED
Solution
Based on our sample data, can we conclude that males and females are distributed across grades
in a similar pattern within the population?
What are the hypothesis statements:
Ho: Males and females are distributed across grades in a similar pattern within the population
Ha: Males and females are distributed across grades in a different pattern within the population
Obs.
An unassuming single-celled organism called Toxoplasma gondii is one.pdfrupeshmehta151
An unassuming single-celled organism called Toxoplasma gondii is one of the most successful
parasites on Earth, infecting an estimated 11 percent of Americans and perhaps half of all people
worldwide. It’s just as prevalent in many other species of mammals and birds. In a recent study
in Ohio, scientists found the parasite in three-quarters of the white-tailed deer they studied.
One reason for Toxoplasma’s success is its ability to manipulate its hosts. The parasite can
influence their behavior, so much so that hosts can put themselves at risk of death. Scientists first
discovered this strange mind control in the 1990s, but it’s been hard to figure out how they
manage it. Now a new study suggests that Toxoplasma can turn its host’s genes on and off —
and it’s possible other parasites use this strategy, too.
Toxoplasma manipulates its hosts to complete its life cycle. Although it can infect any mammal
or bird, it can reproduce only inside of a cat. The parasites produce cysts that get passed out of
the cat with its feces; once in the soil, the cysts infect new hosts.
Toxoplasma returns to cats via their prey. But a host like a rat has evolved to avoid cats as much
as possible, taking evasive action from the very moment it smells feline odor.
Experiments on rats and mice have shown that Toxoplasma alters their response to cat smells.
Many infected rodents lose their natural fear of the scent. Some even seem to be attracted to it.
Manipulating the behavior of a host is a fairly common strategy among parasites, but it’s hard to
fathom how they manage it. A rat’s response to cat odor, for example, emerges from complex
networks of neurons that detect an odor, figure out its source and decide on the right response in
a given moment. Within each of the neurons in those networks, thousands of genes are producing
proteins and other molecules essential for relaying all of the necessary information throughout
the body. Simple Toxoplasma seems ill-equipped to take over such a complicated system. But a
new study published in the journal Molecular Ecology hints that the parasite can do so by relying
on an eerily elegant strategy. Think of the genes in a host as keys on a piano. Toxoplasma, it
seems, simply plays some of the keys differently to produce a new melody. A rat is made up of
lots of different kinds of cells, from the neurons in its brain to the bone-producing cells in its
skeleton to the insulin-making cells in its pancreas. Yet all of them carry the same 20,000 genes.
Depending on the function of a particular cell, some of its genes are switched on and others are
shut down. Genes may be switched off, or silenced, by the attachment of molecular caps called
methyl groups, a process called methylation. In order to switch a gene on again, the caps are
removed. Methylation does more than just allow cells to develop into a variety of organs. It lets
them change the way they work in response to signals from the outside. In the brain, for
example, neuron.
A boy with Klinefelter Syndrome (XXY) has colorblindness, which is a.pdfrupeshmehta151
A boy with Klinefelter Syndrome (XXY) has colorblindness, which is an X-linked recessive
trait. His mother and father both have normal vision.
Did nondisjunction occur during the formation of the egg or the sperm in this situation? How do
you know?
Solution
Color blindness is an X-recessive trait, there is no way that the father can have color-blindness
gene (let’s say Xc). Hence, the color blindness gene should come from mother (but only a single
copy of gene is present as it is not expressed).
Genotype
Mother: XXc
Father: XY
Child: XcXcY (for trait to be expressed, color blindness gene should be present on both the
copies of X)
Xc can be inherited only from mother (as father doesn’t have it) and both the copies of Xc should
come from her. The egg must have arisen from a nondisjunction in meiosis II. In meiosis I, the
homologous X chromosomes separate, so one cell has X and the other has Xc. Failure of
chromatids to separate in meiosis II would then result in an egg with two copies of Xc.
What is unrefined and refined foodsSolutionAnswerRefined f.pdfrupeshmehta151
What is unrefined and refined foods?
Solution
Answer:
Refined foods undergo undergone manufacturing or repackaging processes. They are the foods
altered from their original state. Foods are sometimes refined to enhance the texture, and/or to
increase their shelf life. Sometimes they are added with additives also. Example: Refined wheat
flour, which is polished to remove the bran. During this process a number of essential nutrients
are lost.
Unrefined foods are unprocessed, they are not entirely altered in their nutritional value. Whole
wheat flour will have everything that a wheat grain has. Fibers, carbohydrates and proteins. Also
Vitamins on the outer wheat bran also retained.
In comparison, unrefined foods absorbed slowly while refined foods quickly. Refined foods are
unhealthy since they are linked with diseases related to absorption and metabolism..
What is the function of CFTR (details are important) (5 points).pdfrupeshmehta151
What is the function of CFTR? (details are important) (5 points)
Solution
Ans:- Cystic fibrosis transmembrane conductance regulator (CFTR) is a membrane protein and
chloride channel in vertebrates that is encoded by the CFTR gene.CFTR functions as a ATP
gated anion channel increasing the conductance for certain anions to flow down their
electrochemical gradient.ATP driven conformational changes in CFTR open and close a gate to
allow transmembrane flow of anions down their electrochemical gradient. Essentially CFTR is
an ion channel that evolved as a broken ABC transporter that leaks when in open
conformation.The CFTR is found in the epithelial cells of many organs including the lungs,liver
,pancreas,digestive tract ,reproductive tract and skin.Normally the protein moves chloride and
thiocyanate ions out of an epithelial cell covering mucus.Positively chargedsodium ions follow
passively increasing the total electrolyte concentration in the mucus resulting in the movement of
water out of the cell via osmosis.In sweat glands defective CSTR results in reduced transport of
sodium chloride and sodium thiocyanate in the reabsorptive duct and therefore saltier sweat..
What are transgenic animalsSolutionTransgenic animals are tho.pdfrupeshmehta151
What are transgenic animals?
Solution
Transgenic animals are those animals in which there has been a deliberate modification in their
genome.Generally foreign DNA is inroduced into the animal using recombinant DNA
technology,it is mainly transmitted through germ line so that every cell must contain the
modified genetic material..
Urea concentration in the phospholipid bilayer is 0.02mM, 3.65mM in .pdfrupeshmehta151
Urea concentration in the phospholipid bilayer is 0.02mM, 3.65mM in cytoplasm, what is the
urea partition coefficient in these two liquids?
Solution
Partition coefficient of urea (relative solubility of urea in lipid to aqueous layer) = The
concentration in the phospholipid bilayer / The concentration in the cytoplasm
Partition coefficient of urea is = 0.02mM/ 3.65mM = 1:182.5 mM (phospholipid: cytoplasm)..
A diploid organism has a somatic chromosome number of 16. The centro.pdfrupeshmehta151
A diploid organism has a somatic chromosome number of 16. The centromeres of the 8
homologouspairs are designated as Aa, Bb, Cc, Dd, Ee, Ff, Gg and Hh, with uppercase letters
referring to the centromeres of maternal chromosomes and lowercase letters to the centromeres
of paternal chromosomes. Each centromere represents one chromosome. Where n = the haploid
chromosome number. How many different combinations of centromeres could be produced
during meiosis?
a.) 8
b.) 64
c.) 256
d.) 512
e.) 6561
Solution
At the meiosis, total number of chromosome is 16.
During the meiosis 1st spliting of homologous chromosome take place, so each cell has 8
chromosome and centromere..
the heights of a sample of 10 fatherson pairs of subjects were meas.pdfrupeshmehta151
the heights of a sample of 10 father/son pairs of subjects were measured. Minitab results are
shown below. Is there sufficient evidence to support the claim that there is a linear correlation
between the heights of fathers and the heights of their sons? explain (use significance level of
0.05)
Pearson correlation of FATHER and SON= 0.149
P-value=0.681
How do I begin to answer this problem? How do I use the values they give me to get the answer?
Solution.
Should the FCC regulate the media, and if yes, how far should you go.pdfrupeshmehta151
Should the FCC regulate the media, and if yes, how far should you go? Should it require toning
down sex and violence, airing the shows only later at night, or should it take down shows like
Sex and the City off air?
Solution
The FCC also acts as a police agency of the airwaves, and it can fine broadcasters for violating
public decency standards on the air.
Critics contend that media consolidation limits consumers’ choices because a small number of
companies own all the media outlets. They argue that consolidation is not competitive and that
corporate owners might restrict or manipulate news coverage. Some critics also lament the
homogenization of American culture due to media consolidation. Because radio and television
formats have become increasingly uniform, people throughout the country receive the same
broadcasts..
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Read carefully and follow exactly Java You are to write a Breakou.pdf
1. Read carefully and follow exactly Java:
You are to write a Breakout game, using Java applets for animation. The requirements for this
program are designed so that you will also use an ArrayList, Generics, an abstract class,
polymorphism, and file I/O. Please read the following instructions very carefully, as they attempt
to explain how the various parts of the animation work; then you can update the applet, using
your knowledge of ArrayLists, Generics, abstract classes, and polymorphism.
Existing classes: There are a number of existing classes that are already written and ready for
use. They are contained in the file Breakout.java (they are not defined as public so they don’t
have to be in a file that matches their name). Please look them over carefully to see what
functionality is available. The classes (implemented inside Breakout.java) are:
Ball: this is defined as a subclass of Rectangle (even though that is geometrically invalid!). The
reason for this is so Ball can inherit data for its x coordinate, y coordinate, width, and height. It
also adds some data of its own (see the code) and methods (among others) to:
bounceLeftRight() (which changes the angle at which it moves after bouncing off a left or right
side),
bounceTopBottom() (which changes the angle at which it moves after bouncing off a top or
bottom)
move() (change its coordinates),
freeze()/unfreeze() itself,
It also inherits important methods from the Rectangle class
translate – changes its x and y coordinates respectively by the 2 numbers that are passed in
intersects(Rectangle other) – returns true if it intersects another Rectangle
intersection(Rectangle other) – returns the Rectangle that is the intersection
Paddle: this is also defined as a subclass of Rectangle so it inherits the same data/methods that
are described above for the Ball class. The fact that Ball and Rectangle are both Rectangles
means that code can ask a Ball if it intersects a Paddle, so it can easily tell when to make things
happen.
Wall: this is not in its own file, but rather in the Breakout.java file. Wall is also a subclass of
Rectangle to it is easy to determine if the ball has collided a wall.
The Breakout class (which is an Applet): if you look at the code for the Breakout class, you will
notice it has a number of things:
It is a subclass of Applet, so it inherits data and methods as well as the ability to function as an
Applet. For example, if you want to know the height of the applet you can ask it through the
this.getHeight(); method.
It implements the KeyListener interface, which gives it the ability to “listen” for keystrokes
2. from the keyboard. If you were to look up the KeyListener interface in the documentation, you
would find that anything that implements it must have the KeyPressed, KeyReleased, and
KeyTyped methods. These are all there; KeyPressed and KeyReleased set/unset Boolean flags
which remember that the left or right arrow keys are or are not being pressed.
It has a method called init. For an Applet, the init method is called once when the Applet is
created and it is used to initialize things. In this sense, it works like a constructor. In the init
method, instances of 3 other classes are added to the Applet:
A KeyListener is added, but since it is a KeyListener itself, it defines itself to the the
KeyListener
A timer is also created, which is “set” to go off periodically and will set off an ActionListener
method. There is another class defined in the Breakout.java file called BounceActionListener,
which implements ActionListener. Its required method (actionPerformed) will simply tell the
Applet to repaint itself, thus providing the timing for the animation.
A MouseListener is added that will listen for mouse clicks. To be different, I defined a new class
(in the same Breakout.java file) called BounceMouseListener. If you find it and look at it, you
will see that it implements the MouseListener interface, which requires 5 methods and allows it
to listen for mouse events. All the methods are there but the only one that is actually used is
mouseClicked, which listens for when a button is clicked.
It has a method called update, which is actually called by paint and redraws the whole Applet. It
receives a Graphics object from whatever browser is calling and controlling the Applet; the
Graphics object is like a “pen” in that it has the ability to draw specific things and also change its
color to whatever is passed in. The update methods has code to use “double buffering” in which
an image is create (with its own Graphics object), everything is written to the image, and then the
whole image is written to the Applet. This eliminates flickering. In the update method, various
components are told to move and to draw themselves (passing a Graphics object). This is also
where we check if the ball intersects other things. See the Java documentation for the methods a
Graphics object can use to draw things.
What you need to code:
Create an abstract class called DrawableBrick, which should be a subclass of Rectangle (so it
also inherits the same data and methods defined above in the description of Ball; these will be
important). Also make it have an additional data item to store points (this will be used by its
subclasses). There should be a getPoints() method which returns the points. Finally, make it have
an abstract method called draw(Graphics g), which will have to be implemented by any class
which is a subclass of DrawableBrick.
The relationship between the classes that implement your bricks is shown below. See Create 4
subclasses of DrawableBrick. The details are listed below.
3. has data: has methods:
x, y, width, height (ints) boolean intersects(Rectangle r)
Rectangle intersection(Rectangle r)
has data: has method: color (a Color) getPoints()
points (an int)
has abstract method:
draw(Graphics g);
( all implement their own method: draw(Graphics g) )
The RedBrick class is given as an example. Change it so it is a subclass of DrawableBrick and
has no data (all will be inherited). Its constructor should only accept ints for x, y, width, and
height (not points). Its constructor should also “hard-code” the number of points that it is worth.
Its draw method draws it using the Graphics object that it receives. You should take out the
diagnonal line that is in the example one.
The XBrick class should be set up like the RedBrick class, except that when it draws itself, it
draws a white rectangle with diagonal lines in addition to the outline around the edge. You can
“hard-code” a different amount of points for it.
The StripeBrick class should be set up like the RedBrick class, except that when it draws itself,
it draws a white rectangle with some horizontal “stripes” in addition to the outline around the
edge. You can “hard-code” a different amount of points for it.
The OvalBrick should be set up like the RedBrick class, except that when it draws itself, it
draws 2 ovals inside itself. These ovals can be any color you want. Check the documentation for
the Graphics class to tell a Graphics object how to draw a filled oval. You can “hard-code” a
different amount of points for it.
See the image below for what the different bricks look like.
In Breakout’s data, declare an ArrayList that will hold DrawableBricks.
In Breakout’s init() method, actually create the ArrayList that will hold DrawableBricks. Then
open a file called bricklist.txt (OK to hardcode the name, but make sure it is correct). The file
might look something like what is shown below (FOR EXAMPLE – this is the file that would
produce the game shown above.).
2
3
OvalBrick
XBrick
OvalBrick
XBrick
RedBrick
4. StripeBrick
This file is telling you to have 2 rows, each with 3 columns. After the numbers should be 2x3 =
6 lines, each with a type of DrawableBrick. Create each type of DrawableBrick, carefully
calculating the x, y, width, and height. Put it into the ArrayList that you created.
(You should experiment with changing bricklist.txt to have different number and types of
bricks…)
The rows should exactly fit across the usable space (not including the walls). Their height can be
any number you want. The gap at the top should be at least 3 times the ball diameter.
NOTE: You can read the name of the brick type with a .next(). If you decide to use .nextLine(),
remember what happens when you try to read an int ( using nextInt() )and then a line ( using
nextLine() ).
In Breakout’s update() method, you will have to provide the actual logic that will make it all
work. After the ball is told to move, there is existing code which checks to see if the ball hit a
wall or a paddle. You have to add code to check if the ball it any one of the various bricks that
are in your ArrayList – if so, tell the ball to bounce (correctly – either a “side bounce” or a
“top/bottom bounce”), update the number of points (see the comment in the Breakout.java
update() code), and tell the ArrayList to remove that particular brick.
Remember:
When you are calculating coordinates, the x coordinate is the distance from the left and the y
coordinate is the distance from the top.
The x, y, width, and height data fields are all inherited from Rectangle. Do not redefined them;
if you do, the intersects() method will probably not work correctly.
Since Breakout is a subclass of Applet, it has access to all of the methods of an Applet. That is
how it can get its width and its height.
Comments and formatting: It is very important that you organize your code to use comments,
constants (when feasible) and correct indenting/whitespace. Please make your variable names
meaningful and use Java conventions for choosing their names (start with lower case).
Code, Applet, and Tester files here:
Tester:
//This program is a more sophisticated implemenation of animation in a Javaapplet.//It creates a
ball and has it bounce around the pane It has code that listens//for keyboard keyboard input (left
and right arrows) and mouse clicks//(left button). It also uses a Timer to control the speed of the
animation
import java.applet.*;import java.awt.*;import java.awt.event.*;import
java.awt.image.ImageObserver;import java.util.*;
import javax.swing.Timer;
5. public class BrickTester extends Applet implements KeyListener{
//constantsprivate final int PADDLE_HEIGHT = 5; //height of the paddleprivate final int
PADDLE_WIDTH = 150; //width of the paddleprivate final int PADDLE_MOVE = 20; //how
many pixels to move the
paddle at a time (speed)
private final int BALLDIAMETER = 30; //diameter of the ballprivate final Color
BALLCOLOR = Color.GREEN; //color of the ballprivate final int DELAY = 45;
//number of
milliseconds until timer goes off again
private final Color WALLCOLOR = Color.ORANGE; //Walls' color
private final int WALLWIDTH = 5; //Walls' width
private final int NUMROWS = 3;private final int BRICKSPERROW = 8;private final int
BRICKHEIGHT = 120;private final int TOPSPACE = 125;
//keeps track of whether or not left, right arrow keys are being pressed private boolean
leftPressed; //left arrow key pressed? private boolean rightPressed; //right arrow key pressed?
//graphical components private Paddle thePaddle; private Ball theBall; private Wall leftWall;
private Wall rightWall; private Wall topWall; private Wall bottomWall;
//TO TEST THE BRICKS...create 4 variables that will hold different bricks. //They are all
defined to hold DrawableBricks but we can put in subclasses. private DrawableBrick
testRedBrick; private DrawableBrick testStripedBrick; private DrawableBrick testXBrick;
private DrawableBrick testOvalBrick;
//timer to control the speed private Timer timer;
//init is called when the Applet is first executed - sets it up
public void init(){
//change the size of the applet to be 800 by 600 (minimum guaranteed
screen resolution)
setSize(1200, 800);//fillScreen();
// the next line is required for the keyboard input to work right away
setFocusable(true);
requestFocusInWindow(); // this line might not be necessary, but isgood practice.
//create a Paddle int paddleX = this.getWidth()/2 - PADDLE_WIDTH/2; //x coordinate
is middle of applet
int paddleY = this.getHeight()-WALLWIDTH-10; // y
coordinate is 10 pixels above bottom wall
thePaddle = new Paddle(paddleX, paddleY, PADDLE_WIDTH,
PADDLE_HEIGHT);
6. //create a Ball that starts in the middle of the appletint ballx = getWidth()/2 -
BALLDIAMETER/2;int bally = getHeight()-300;theBall = new Ball(ballx, bally,
BALLDIAMETER, BALLCOLOR);
//create 4 wallsleftWall = new Wall(0, 0, WALLWIDTH, getHeight(),
WALLCOLOR);rightWall = new Wall(getWidth()-WALLWIDTH, 0, WALLWIDTH,
getHeight(), WALLCOLOR);
topWall = new Wall(0, 0, getWidth(), WALLWIDTH, WALLCOLOR);bottomWall = new
Wall(0, getHeight()-WALLWIDTH, getWidth(),
WALLWIDTH, WALLCOLOR);
//TO TEST THE BRICKS...Create 4 different types of DrawableBricks //The variables hold
DrawableBricks but we can put in any subclass. //The x, y, width, height are just made up for this
example... testRedBrick = new RedBrick(5, 300, 275, 100); testStripedBrick = new
StripedBrick(280, 400, 275, 100); testXBrick = new XBrick(555, 500, 275, 100); testOvalBrick
= new OvalBrick(830, 600, 275, 100);
//add a key listener that will respond to key events//(note - since this applet implements
KeyListener, "this" instancecan do it itself)addKeyListener (this); //so it is its own KeyListener
//add a mouse listener that will respond to mouse events
//(note - it will be a new instance of the class defined below)addMouseListener (new
BounceMouseListener());
//create a new Timer to control things and tell it to starttimer = new Timer(DELAY, new
BounceActionListener());timer.start();
//set the background color of this appletthis.setBackground(Color.WHITE);
}
//paint is automatically called with a Graphics object as its argument.
It will
//tell the Graphics object to actually paint things on the pane.//public void paint(Graphics g)//lets
delegate this to the update method instead to fix double buffering
and input issues
public void update(Graphics g){Dimension size = getSize();
Image frameBuffer = createImage(size.width, size.height);Graphics graphicsBuffer =
frameBuffer.getGraphics();
//if left arrow is pressed, move paddle left by 10 pixelsif(leftPressed)
{
if (!thePaddle.intersects(leftWall)){
thePaddle.translate(-1*PADDLE_MOVE, 0);
}
7. }//else if right arrow is pressed, move paddle right by 10 pixelselse if (rightPressed){
if (!thePaddle.intersects(rightWall)){thePaddle.translate(PADDLE_MOVE, 0);}
}//tell each of the walls to set their dimensions (in case the applet
has been resized)
leftWall.setDimensions(0, 0, WALLWIDTH, getHeight());rightWall.setDimensions(getWidth()-
WALLWIDTH, 0, WALLWIDTH,
getHeight());
topWall.setDimensions(0, 0, getWidth(), WALLWIDTH);bottomWall.setDimensions(0,
getHeight()-WALLWIDTH, getWidth(),
WALLWIDTH);
//tell the paddle to set its y coordinate to 10 pixels above bottom
wall
//(in case applet has been resized; note that x coordinate should
not change since paddle
// could be moving).thePaddle.setY(getHeight()-WALLWIDTH-10);
//if the ball hit the left or right wall, tell it to bounce (change
direction)
//if (theBall.intersects(topWall) || theBall.intersects(bottomWall))// theBall.bounce();if
(theBall.intersects(leftWall) || theBall.intersects(rightWall))
theBall.bounceOffSide();else if (theBall.intersects(topWall) ||
theBall.intersects(thePaddle))
theBall.bounceOffTopBottom();else if
(theBall.intersects(bottomWall))theBall.freeze();elsetheBall.recordNotBouncing();
//FOR TESTING THE BRICKS AND A DEMO...//If the ball has intersected any one of the test
bricks (check them
one by one)
//then change its color to be MAGENTA. If not, change it back to
the original
//colorif (theBall.intersects(testRedBrick) ||
theBall.intersects(testStripedBrick) ||
theBall.intersects(testXBrick) ||
theBall.intersects(testOvalBrick))
theBall.setColor(Color.MAGENTA); else theBall.setColor(BALLCOLOR);
//tell the ball to movetheBall.move();
//tell each of the walls to draw themselves using Graphics object
gleftWall.draw(graphicsBuffer);
8. rightWall.draw(graphicsBuffer);topWall.draw(graphicsBuffer);bottomWall.draw(graphicsBuffer
);
//tell the paddle to draw itself using Graphics object gthePaddle.draw(graphicsBuffer);
//tell all 4 test bricks to draw themselves. Even though the
variables are
//originally defined to hold DrawableBricks, they hold different
subclasses
//and Java will wait until runtime to decide the correct .draw
method to call. testRedBrick.draw(graphicsBuffer); testStripedBrick.draw(graphicsBuffer);
testXBrick.draw(graphicsBuffer); testOvalBrick.draw(graphicsBuffer);
//tell the Ball to draw itself using Graphics object gtheBall.draw(graphicsBuffer);
//draw the buffered image on the "real" Applet (this)g.drawImage(frameBuffer, 0, 0, this);
}
//resizes the applet to fill the entire screenprivate void fillScreen(){ Dimension ScreenSize =
Toolkit.getDefaultToolkit().getScreenSize(); Dimension FrameSize = this.getSize(); int xheight
= ScreenSize.height; int xwidth = ScreenSize.width; resize(xwidth, xheight);
//setResizable(false); ///int x = (ScreenSize.width - FrameSize.width)/2; //int y =
(ScreenSize.height - FrameSize.height)/2; //this.setLocation(x, y);
}
//if a key is pressed, see if it is left or right arrow.public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_LEFT)
leftPressed = true;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
rightPressed = true;
}
//if a key is released, see if it was left or right arrowpublic void keyReleased(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_LEFT)
leftPressed = false;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
rightPressed = false;
}
//only here because its required by interface...public void keyTyped(KeyEvent e) { }
//Represents the mouse listener for the applet private class BounceMouseListener implements
MouseListener {
public void mouseClicked (MouseEvent event)
{
9. if (timer.isRunning()){
if (theBall.isFrozen()){
int ballx = getWidth()/2 - BALLDIAMETER/2;int bally = getHeight()-100;
theBall.reset(ballx, bally, -1*Math.PI/6); theBall.unfreeze();
}
} }
//these are empty definitions for unused event methods public void mouseEntered (MouseEvent
event) { } //
{setBackground(Color.yellow);}
public void mouseExited (MouseEvent event) { } //
{setBackground(Color.magenta);}
public void mousePressed (MouseEvent event) {} public void mouseReleased (MouseEvent
event) {}
}
//represents the action listener for the timer private class BounceActionListener implements
ActionListener
{
public void actionPerformed (ActionEvent event)
{
//repaint the screen repaint();
}
}
//-----------------------------------------------------------------------//Wall - represents a "Wall,"
which is around the edge of the appletclass Wall extends Rectangle{
//data - most inherited from Rectangleprivate Color color; //its color
//constructorpublic Wall(int x, int y, int theWidth, int theHeight, Color
theColor){
this.x = x;this.y = y;this.width = theWidth;this.height = theHeight;this.color = theColor;
}
//setDimensions - sets the dimensions to whatever is passed inpublic void setDimensions(int x,
int y, int theWidth, int theHeight){
this.x = x;this.y = y;this.width = theWidth;this.height = theHeight;
}//draw - tells the Ball to draw itself, using the Graphics object
received
public void draw(Graphics g){
Color prevColor = g.getColor(); //save previous color
10. associated with g
g.setColor(this.color);g.fillRect(x, y, width, height);g.setColor(prevColor);
//restore
previous color }}
}
Applet:
//This program is a more sophisticated implemenation of animation in a Javaapplet.//It creates a
ball and has it bounce around the pane It has code that listens//for keyboard keyboard input (left
and right arrows) and mouse clicks//(left button). It also uses a Timer to control the speed of the
animation
import java.applet.*;import java.awt.*;import java.awt.event.*;import
java.awt.image.ImageObserver;import java.util.*;
import javax.swing.Timer;
public class Breakout extends Applet implements KeyListener{
//constantsprivate final int PADDLE_HEIGHT = 5; //height of the paddleprivate final int
PADDLE_WIDTH = 150; //width of the paddleprivate final int PADDLE_MOVE = 20; //how
many pixels to move the
paddle at a time (speed)
private final int BALLDIAMETER = 40; //diameter of the ballprivate final Color
BALLCOLOR = Color.GREEN; //color of the ballprivate final int DELAY = 35;
//number of
milliseconds until timer goes off again
private final Color WALLCOLOR = Color.ORANGE; //Walls' color
private final int WALLWIDTH = 5; //Walls' width
//keeps track of whether or not left, right arrow keys are being pressed private boolean
leftPressed; //left arrow key pressed? private boolean rightPressed; //right arrow key pressed?
//graphical components private Paddle thePaddle; private Ball theBall; private Wall leftWall;
private Wall rightWall; private Wall topWall; private Wall bottomWall;
//timer to control the speed private Timer timer;
//init is called when the Applet is first executed - sets it up
public void init(){
//change the size of the applet to be 800 by 600 (minimum guaranteed
screen resolution)
setSize(1200, 800);//fillScreen();
// the next line is required for the keyboard input to work right
away
11. setFocusable(true);
requestFocusInWindow(); // this line might not be necessary, but isgood practice.
//create a Paddle int paddleX = this.getWidth()/2 - PADDLE_WIDTH/2; //x coordinate
is middle of applet
int paddleY = this.getHeight()-WALLWIDTH-10; // y
coordinate is 10 pixels above bottom wall
thePaddle = new Paddle(paddleX, paddleY, PADDLE_WIDTH,
PADDLE_HEIGHT);
//create a Ball that starts in the middle of the appletint ballx = getWidth()/2 -
BALLDIAMETER/2;int bally = getHeight()-300;theBall = new Ball(ballx, bally,
BALLDIAMETER, BALLCOLOR);
//create 4 wallsleftWall = new Wall(0, 0, WALLWIDTH, getHeight(),
WALLCOLOR);rightWall = new Wall(getWidth()-WALLWIDTH, 0, WALLWIDTH,
getHeight(), WALLCOLOR);
topWall = new Wall(0, 0, getWidth(), WALLWIDTH, WALLCOLOR);bottomWall = new
Wall(0, getHeight()-WALLWIDTH, getWidth(),
WALLWIDTH, WALLCOLOR);
//add a key listener that will respond to key events//(note - since this applet implements
KeyListener, "this" instance
can do it itself)
addKeyListener (this); //so it is its own KeyListener
//add a mouse listener that will respond to mouse events//(note - it will be a new instance of the
class defined below)addMouseListener (new BounceMouseListener());
//create a new Timer to control things and tell it to starttimer = new Timer(DELAY, new
BounceActionListener());timer.start();
//set the background color of this appletthis.setBackground(Color.WHITE);
}
//paint is automatically called with a Graphics object as its argument.
It will
//tell the Graphics object to actually paint things on the pane.//public void paint(Graphics g)//lets
delegate this to the update method instead to fix double buffering
and input issues
public void update(Graphics g){Dimension size = getSize();
Image frameBuffer = createImage(size.width, size.height);Graphics graphicsBuffer =
frameBuffer.getGraphics();
//if left arrow is pressed, move paddle left by 10 pixelsif(leftPressed){
12. if (!thePaddle.intersects(leftWall)){
thePaddle.translate(-1*PADDLE_MOVE, 0);
}
}//else if right arrow is pressed, move paddle right by 10 pixelselse if (rightPressed){
if (!thePaddle.intersects(rightWall)){thePaddle.translate(PADDLE_MOVE, 0);}
}//tell each of the walls to set their dimensions (in case the applet
has been resized)
leftWall.setDimensions(0, 0, WALLWIDTH, getHeight());rightWall.setDimensions(getWidth()-
WALLWIDTH, 0, WALLWIDTH,
getHeight());
topWall.setDimensions(0, 0, getWidth(), WALLWIDTH);bottomWall.setDimensions(0,
getHeight()-WALLWIDTH, getWidth(),
WALLWIDTH);
//tell the paddle to set its y coordinate to 10 pixels above bottom
wall
//(in case applet has been resized; note that x coordinate should
not change since paddle
// could be moving).thePaddle.setY(getHeight()-WALLWIDTH-10);
//if the ball hit the left or right wall, tell it to bounce (change
direction)
//if (theBall.intersects(topWall) || theBall.intersects(bottomWall))// theBall.bounce();if
(theBall.intersects(leftWall) || theBall.intersects(rightWall))
theBall.bounceOffSide();else if (theBall.intersects(topWall) ||
theBall.intersects(bottomWall))
theBall.bounceOffTopBottom();else if
(theBall.intersects(thePaddle))theBall.freeze();elsetheBall.recordNotBouncing();
//tell the ball to movetheBall.move();
//tell each of the walls to draw themselves using Graphics object
gleftWall.draw(graphicsBuffer);rightWall.draw(graphicsBuffer);topWall.draw(graphicsBuffer);b
ottomWall.draw(graphicsBuffer);
//tell the paddle to draw itself using Graphics object gthePaddle.draw(graphicsBuffer);
//tell the Ball to draw itself using Graphics object gtheBall.draw(graphicsBuffer);
//drawing the buffered image into the appletg.drawImage(frameBuffer, 0, 0, this);
}
//resizes the applet to fill the entire screenprivate void fillScreen(){ Dimension ScreenSize =
Toolkit.getDefaultToolkit().getScreenSize(); Dimension FrameSize = this.getSize(); int xheight
13. = ScreenSize.height; int xwidth = ScreenSize.width; resize(xwidth, xheight);
//setResizable(false); ///int x = (ScreenSize.width - FrameSize.width)/2; //int y =
(ScreenSize.height - FrameSize.height)/2; //this.setLocation(x, y);
}
//if a key is pressed, see if it is left or right arrow.public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_LEFT)
leftPressed = true;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
rightPressed = true;
}
//if a key is released, see if it was left or right arrowpublic void keyReleased(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_LEFT)
leftPressed = false;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
rightPressed = false;
}
//only here because its required by interface...public void keyTyped(KeyEvent e) { }
//Represents the mouse listener for the applet private class BounceMouseListener implements
MouseListener {
public void mouseClicked (MouseEvent event) {
if (timer.isRunning()) timer.stop(); else timer.start();
}
//these are empty definitions for unused event methods public void mouseEntered (MouseEvent
event) { } public void mouseExited (MouseEvent event) { }
//setBackground(Color.magenta);}
public void mousePressed (MouseEvent event) {} public void mouseReleased (MouseEvent
event) {}
}
//represents the action listener for the timer private class BounceActionListener implements
ActionListener
{
public void actionPerformed (ActionEvent event)
{
//repaint the screen repaint();
}
}
14. //-----------------------------------------------------------------------//Wall - represents a "Wall,"
which is around the edge of the appletclass Wall extends Rectangle{
//data - most inherited from Rectangleprivate Color color; //its color
//constructorpublic Wall(int x, int y, int theWidth, int theHeight, Color
theColor){
this.x = x;this.y = y;this.width = theWidth;this.height = theHeight;this.color = theColor;
}//setDimensions - sets the dimensions to whatever is passed in
public void setDimensions(int x, int y, int theWidth, int theHeight){
this.x = x;this.y = y;this.width = theWidth;this.height = theHeight;
}//draw - tells the Ball to draw itself, using the Graphics object
received
public void draw(Graphics g){
Color prevColor = g.getColor(); //save previous color
associated with g
g.setColor(this.color);g.fillRect(x, y, width, height);g.setColor(prevColor);
//restore
previous color }}
}
Ball Code:
//Ball - represents a "Ball" (which is a subclass of Rectangle so it candetermine .intersects)
import java.awt.*;
public class Ball extends Rectangle{
//data - most inherited from Rectangleprivate double angle; //will determine what angle it
travelsprivate Color color; //its colorprivate boolean frozen; //whether or not it is
"frozen"private boolean currentlyBouncing; //remember if it is in a bounce;
otherwise can get "stuck"//constructor
public Ball(int x, int y, int diameter, Color theColor){
this.x = x;this.y = y;this.width = diameter;this.height = diameter;this.color = theColor;this.angle
= -1*Math.PI/7; //add to position each time (so
travelling diagonally)
this.frozen = false; //not frozen
}
//draw - tells the Ball to draw itself, using the Graphics object receivedpublic void
draw(Graphics g){Color prevColor = g.getColor(); //save previous color associated
with g
g.setColor(this.color);g.fillOval(x, y, width, height);g.setColor(prevColor);
15. //restore previous
color }
//bounce - tells it to reverse direction if it hits the top or the bottom public void
bounceOffSide(){
if (!currentlyBouncing){
this.angle = Math.PI - this.angle;
currentlyBouncing = true;}
}
//bounceInverse - tells it to reverse directionpublic void bounceOffTopBottom(){
if (!currentlyBouncing){
this.angle = -1 * this.angle;currentlyBouncing = true;
}
}
//recordNotBouncing - this is necessary because a Ball can become//"stuck" bouncing against a
wall because of timing issues. The program//rechecks to see if has intersected with a wall before
it has "cleared"//the wall from the previous bouncepublic void recordNotBouncing()
{
currentlyBouncing = false;
}
//move - changes its coordinate(s) if its not "frozen"public void move(){
if (!frozen) {
//translates itself by r*cos in the x direction, r*sin in the
Y direction
translate( (int)((10*Math.cos(angle))),
(int)((10*Math.sin(angle))) ); //x = (int)(x + (10*Math.cos(angle))); //equivalent to
these (translate is inherited method)
//y = (int)(y + (10*Math.sin(angle)));
}
}
//setColor - sets its color to whatever is passed in public void setColor(Color newColor) {
this.color = newColor;
}
//freeze() - tells the ball to "freeze" (stops movement). public void freeze() {
frozen = true;
}
//unfreeze() - tells the ball to "unfreeze" (movement is continued) public void unfreeze() {
16. frozen = false;
}
//isFrozen() - returns true if the ball is currently frozen public boolean isFrozen() {
return frozen;
}
//reset - resets its x, y, and angle public void reset(int newX, int newY, double newAngle) {
x = newX; y = newY; angle = newAngle;
}
}
Paddle Code:
//Paddle is the paddle that goes with breakout import java.awt.*; public class Paddle extends
Rectangle
{ //data - all is inherited from Rectangle
//constructor public Paddle(int x, int y, int width, int height) {
this.x = x; this.y = y; this.width = width; this.height = height;
} //setY - sets its Y value to whatever is passed in (in case applet was
resized)
public void setY(int newY) { this.y = newY; }
//draw - tells the Paddle to draw itself, using the Graphics object
received
public void draw(Graphics g) {
Color prevColor = g.getColor(); g.setColor(Color.BLACK); g.fillRect(x, y, width, height);
g.setColor(prevColor);
}
}
Red Brick Code:
import java.awt.*;import java.util.*;
public class RedBrickEXAMPLE extends DrawableBrick{
//data - all is inherited
//constructorpublic RedBrick(int initX, int initY, int initWidth, int initHeight){
this.x = initX;this.y = initY;this.width = initWidth;this.height = initHeight;//super(initX, initY,
initWidth, initHeight);Random gen = new Random();int redpart = gen.nextInt(155) + 100;
//some shade of red
(generates 100-255)
color = new Color(redpart, 0, 0);
}
17. //methodspublic void draw(Graphics g){
Color prevColor = g.getColor(); //save previous color associated
with g
g.setColor(this.color);g.fillRect(x, y, width, height);g.setColor(Color.BLACK);g.drawRect(x, y,
width, height);g.drawLine(x, y, x+width, y+height); //draws a diagonal line -
just as an example...
g.setColor(prevColor);
//restore previous
color}}
Solution
import java.awt.*;
import java.applet.*;
import java.lang.Math;
import java.net.InetAddress;
public class Breakout extends Applet implements Runnable {
public static final int HEIGHT=320, WIDTH=320, SLEEPTIME = 5, //5
BALLRADIUS=5, BLOCKWIDTH = 40, BLOCKHEIGHT = 10,
PADDLEWIDTH = 40, PADDLEHEIGHT=10, PADDLEALTITUDE=HEIGHT-20,
PADDLESPEED=3, BLOCKSPACING_Y=2, BLOCKSPACING_X=2,
MAXBALLS=3;
public static final double INITSPEED_X=2.5, INITSPEED_Y=-2.5, //2.5
XHIT_CHANGE=0.4, YHIT_CHANGE=0.2;
public static final Color PADDLECOLOR=Color.black,
BALLCOLOR=Color.red;
public static final Color BACKGROUND = new Color(0xcccccc);
public static final String BEEP_SOUND = "beep.au";
private boolean paused=false;
private int numberlost=0;
private Graphics gContext;
private Image buffer;
private Thread animate;
private boolean leftArrow = false, rightArrow = false, ballready = true;
private Ball ball;
private BlockHolder blocks;
18. private AudioClip hitsound;
private Paddle paddle;
public void init() {
hitsound = getAudioClip(getDocumentBase(), BEEP_SOUND);
hitsound.play();
buffer = createImage(WIDTH, HEIGHT);
gContext = buffer.getGraphics();
gContext.setColor(BACKGROUND);
blocks = new BlockHolder();
paddle = new Paddle();
ball = new Ball(blocks, hitsound);
gContext.fillRect(0, 0, WIDTH, HEIGHT);
paddle.draw(gContext);
ball.draw(gContext);
blocks.draw(gContext);
}
public void start() {
if(animate == null) {
animate = new Thread(this);
animate.start();
}
}
public void restart() { }
public void stop() {
if(animate != null) {
animate.stop();
animate = null;
}}
public void paint(Graphics g) {
try {
g.drawImage(buffer, 0, 0, this);
}
catch(Exception e) {}
}
public void run() {
try {
22. prepareBlocks();
}
public void restart() {
blockCount=0;
for(int i = 0; i= y && lines[i].top <= y) {
Block hit=lines[i].whohit(x);
if(hit!=null)
blockCount-=1;
return hit;
}
}
return null;
}
public void draw(Graphics g) {
for(int i = 0; i numberblocks)
numhit = numberblocks;
if(exists[numhit]) {
exists[numhit] = false;
return blocks[numhit];
}
return null;
}
}
class Block {
public int x, y;
protected Color color;
protected int width, height;
public Block(int x0, int y0, Color color0) {
x = x0;
y = y0;
color = color0;
width = Breakout.BLOCKWIDTH-Breakout.BLOCKSPACING_X/2;
height = Breakout.BLOCKHEIGHT-Breakout.BLOCKSPACING_Y/2;
}
23. public void clear(Graphics g) {
g.setColor(Breakout.BACKGROUND);
g.fillRect(x,y,width,height);
}
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(x,y, width, height);
}
public int getTop() {
return y;
}
public int getBottom() {
return y+height;
}
public int getleftx() {
return x;
}
public int getrightx() {
return x + width;
}
}
class Paddle extends Block {
public boolean moved = false;
public Paddle() {
super(Breakout.WIDTH/2-Breakout.PADDLEWIDTH/2,
Breakout.PADDLEALTITUDE,
Breakout.PADDLECOLOR);
width = Breakout.PADDLEWIDTH;
height = Breakout.PADDLEHEIGHT;
}
/* Place block on (x0, y0) */
public void go(int x0, int y0) {
x=x0;
y=y0;
}
24. public void move(int change) {
if((x+width < Breakout.WIDTH || change < 0) && (x > 0 || change > 0)) {
x = x + change;
moved = true;
}
else
moved = false;
}
}
class Ball {
public double xchange, ychange;
private double x, y;
private int radius;
private Color color;
private BlockHolder blocks;
private AudioClip beep;
public Ball(BlockHolder blocks0, AudioClip beep0) {
xchange = 0;
ychange = 0;
radius = Breakout.BALLRADIUS;
x = Breakout.WIDTH/2-radius;
y = Breakout.PADDLEALTITUDE-5;
color = Breakout.BALLCOLOR;
blocks = blocks0;
beep = beep0;
}
public void go(int x0, int y0) {
x= (double) x0;
y= (double) y0;
xchange=0.0;
ychange=0.0;
}
public void selfMove(Graphics g, Block paddle, Breakout ap) {
if(x+xchange>=Breakout.WIDTH)
xchange=-Math.abs(xchange);