Assignments 1 through 6

This commit is contained in:
Nathan Howard 2025-11-21 18:46:19 -08:00
parent 7f78cdd7e0
commit 5641a77589
40 changed files with 2635 additions and 0 deletions

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/javalib.jar"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/tester.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Assn01</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=11
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=11

View File

@ -0,0 +1,20 @@
class Dog {
String name;
String breed;
int yob;
String state; // 2 letter abbreviation
boolean hypoallergenic;
Dog(String name, String breed, int yob, String state, boolean hypoallergenic) {
this.name = name;
this.breed = breed;
this.yob = yob;
this.state = state;
this.hypoallergenic = hypoallergenic;
}
}
class ExamplesDogs {
Dog hufflepuff = new Dog("Hufflepuff", "Wheaton Terrior", 2012, "TX", true);
Dog pearl = new Dog("Pearl", "Labrador Retriever", 2016, "MA", false);
}

View File

@ -0,0 +1,27 @@
interface IIceCream {
}
class EmptyServing implements IIceCream {
boolean cone;
EmptyServing(boolean cone) {
this.cone = cone;
}
}
class Scooped implements IIceCream {
String firstFlavor;
IIceCream more;
Scooped(String firstFlavor, IIceCream more) {
this.firstFlavor = firstFlavor;
this.more = more;
}
}
class ExamplesIceCream {
IIceCream order1 = new Scooped("mint chip", new Scooped("coffee",
new Scooped("black raspberry", new Scooped("caramel swirl", new EmptyServing(false)))));
IIceCream order2 = new Scooped("chocolate",
new Scooped("vanilla", new Scooped("strawberry", new EmptyServing(true))));
}

View File

@ -0,0 +1,83 @@
interface IHousing {
}
class Hut implements IHousing {
int capacity;
int population;
Hut(int capacity, int population) {
this.capacity = capacity;
this.population = population;
}
}
class Inn implements IHousing {
String name;
int capacity;
int population;
int stalls;
Inn(String name, int capacity, int population, int stalls) {
this.name = name;
this.capacity = capacity;
this.population = population;
this.stalls = stalls;
}
}
class Castle implements IHousing {
String name;
String familyName;
int population;
int carriageHouse;
Castle(String name, String familyName, int population, int carriageHouse) {
this.name = name;
this.familyName = familyName;
this.population = population;
this.carriageHouse = carriageHouse;
}
}
interface ITransportation {
}
abstract class ATransportation implements ITransportation {
IHousing from;
IHousing to;
ATransportation(IHousing from, IHousing to) {
this.from = from;
this.to = to;
}
}
class Horse extends ATransportation {
String name;
String color;
Horse(IHousing from, IHousing to, String name, String color) {
super(from, to);
this.name = name;
this.color = color;
}
}
class Carriage extends ATransportation {
int tonnage;
Carriage(IHousing from, IHousing to, int tonnage) {
super(from, to);
this.tonnage = tonnage;
}
}
class ExamplesTravel {
IHousing hovel1 = new Hut(5, 1);
IHousing hovel2 = new Hut(4, 2);
IHousing hovel3 = new Hut(6, 6);
IHousing winterfell = new Castle("Winterfell", "Stark", 500, 6);
IHousing crossroads = new Inn("Inn at the Crossroads", 40, 20, 12);
IHousing pony = new Inn("Prancing Pony", 50, 45, 13);
ITransportation horse1 = new Horse(this.hovel1, this.pony, "Bill", "Chessnut");
ITransportation horse2 = new Horse(this.pony, this.hovel2, "Fairy", "White");
ITransportation carriage1 = new Carriage(this.hovel3, this.winterfell, 100);
ITransportation carriage2 = new Carriage(this.winterfell, this.crossroads, 150);
}

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/javalib.jar"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/tester.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Assn02</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=11
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=11

View File

@ -0,0 +1,128 @@
import tester.Tester;
class EmbroideryPiece {
String name;
ILoMotif motif;
EmbroideryPiece(String name, ILoMotif motif) {
this.name = name;
this.motif = motif;
}
public double averageDifficulty() {
return this.motif.averageDifficulty();
}
public String embroideryInfo() {
return this.motif.embroideryInfo(this.name + ":");
}
}
interface IMotif {
double getDifficulty();
String getDescription();
String getType();
}
abstract class AMotif implements IMotif {
String description;
double difficulty;
AMotif(String description, double difficulty) {
this.description = description;
this.difficulty = difficulty;
}
public String getDescription() {
return this.description;
}
public double getDifficulty() {
return this.difficulty;
}
}
class CrossStitch extends AMotif {
CrossStitch(String description, double difficulty) {
super(description, difficulty);
}
public String getType() {
return "cross stitch";
}
}
class ChainStitch extends AMotif {
ChainStitch(String description, double difficulty) {
super(description, difficulty);
}
public String getType() {
return "chain stitch";
}
}
interface ILoMotif {
//returns a double of the average difficulty of all of the cross-stitch and
// chain-stitch motifs in an EmbroideryPiece
double averageDifficulty();
double averageDifficultyHelp(double sum, int cnt);
//returns one String that has in it all names of cross-stitch and chain-stitch
//motifs in an EmbroideryPiece, their stitch types in parentheses, and each motif
//separated by comma and space.
String embroideryInfo(String prefix);
String embroideryInfoHelp(String prefix);
}
class MtLoMotif implements ILoMotif {
MtLoMotif() {}
public double averageDifficulty() {
return 0;
}
public double averageDifficultyHelp(double sum, int cnt) {
return sum / cnt;
}
public String embroideryInfo(String prefix) {
return prefix + " empty."; //should only be called on an empty motif in EmbroideryPiece
}
public String embroideryInfoHelp(String prefix) {
return prefix + ".";
}
}
//Group Motif
class ConsLoMotif implements ILoMotif {
IMotif first;
ILoMotif rest;
ConsLoMotif(IMotif first, ILoMotif rest) {
this.first = first;
this.rest = rest;
}
public double averageDifficulty() {
return this.averageDifficultyHelp(0, 0);
}
public double averageDifficultyHelp(double sum, int cnt) {
return this.rest.averageDifficultyHelp(sum + first.getDifficulty(), cnt + 1);
}
public String embroideryInfo(String prefix) {
return rest.embroideryInfoHelp(
prefix + " " + this.first.getDescription() + " (" + this.first.getType() + ")");
}
public String embroideryInfoHelp(String prefix) {
return rest.embroideryInfoHelp(
prefix + ", " + this.first.getDescription() + " (" + this.first.getType() + ")");
}
}
class ExamplesEmbroidery {
IMotif rose = new CrossStitch("rose", 5.0);
IMotif poppy = new ChainStitch("poppy", 4.75);
IMotif daisy = new CrossStitch("daisy", 3.2);
ILoMotif flowers = new ConsLoMotif(this.rose, new ConsLoMotif(this.poppy,
new ConsLoMotif(this.daisy, new MtLoMotif())));
IMotif bird = new CrossStitch("bird", 4.5);
IMotif tree = new ChainStitch("tree", 3.0);
ILoMotif nature = new ConsLoMotif(this.bird, new ConsLoMotif(this.tree, this.flowers));
EmbroideryPiece pillow = new EmbroideryPiece("Pillow Cover", this.nature);
boolean testAverageDifficulty(Tester t) {
return t.checkInexact(this.flowers.averageDifficulty(), (5.0 + 4.75 + 3.2) / 3, 0.01) &&
t.checkInexact(this.pillow.averageDifficulty(), (5 + 4.74 + 3.2 + 4.5 + 3) / 5, 0.01);
}
boolean testEmbroideryInfo(Tester t) {
return t.checkExpect(pillow.embroideryInfo(),
"Pillow Cover: bird (cross stitch), tree (chain stitch), rose (cross stitch), poppy (chain stitch), daisy (cross stitch).");
}
}

View File

@ -0,0 +1,237 @@
import tester.Tester;
interface IPicture {
int getWidth();
int countShapes();
int comboDepth();
int comboDepthHelp(int rsf);
IPicture mirror();
String pictureRecipe(int depth);
}
abstract class APicture implements IPicture {}
class Shape extends APicture {
String kind;
int size;
Shape(String kind, int size) {
this.kind = kind;
this.size = size;
}
public int getWidth() {
return this.size;
}
public int countShapes() {
return 1;
}
public int comboDepth() {
return 0;
}
public int comboDepthHelp(int rsf) {
return rsf;
}
public IPicture mirror() {
return this;
}
public String pictureRecipe(int depth) {
return this.kind;
}
}
class Combo extends APicture {
String name;
IOperation operation;
Combo(String name, IOperation operation) {
this.name = name;
this.operation = operation;
}
public int getWidth() {
return this.operation.getWidth();
}
public int countShapes() {
return this.operation.countShapes();
}
public int comboDepth() {
return this.operation.comboDepthHelp(0);
}
public int comboDepthHelp(int rsf) {
return this.operation.comboDepthHelp(rsf);
}
public IPicture mirror() {
return new Combo(this.name, this.operation.mirror());
}
public String pictureRecipe(int depth) {
if (depth == 0) {
return this.name;
} else {
return this.operation.pictureRecipe(depth);
}
}
}
interface IOperation {
int getWidth();
int countShapes();
int comboDepth();
int comboDepthHelp(int rsf);
IOperation mirror();
String pictureRecipe(int depth);
}
abstract class AOperation implements IOperation {
IPicture pic1;
AOperation(IPicture pic1) {
this.pic1 = pic1;
}
}
class Scale extends AOperation {
Scale(IPicture pic1) {
super(pic1);
}
public int getWidth() {
return pic1.getWidth() * 2;
}
public int countShapes() {
return 1;
}
public int comboDepth() {
return this.pic1.comboDepthHelp(1);
}
public int comboDepthHelp(int rsf) {
return this.pic1.comboDepthHelp(rsf + 1);
}
public IOperation mirror() {
return new Scale(pic1);
}
public String pictureRecipe(int depth) {
return "scale(" + pic1.pictureRecipe(depth - 1) + ")";
}
}
class Beside extends AOperation {
IPicture pic2;
Beside(IPicture pic1, IPicture pic2) {
super(pic1);
this.pic2 = pic2;
}
public int getWidth() {
return pic1.getWidth() + pic2.getWidth();
}
public int countShapes() {
return this.pic1.countShapes() + this.pic2.countShapes();
}
public int comboDepth() {
if (this.pic1.comboDepthHelp(1) > this.pic2.comboDepthHelp(1)) {
return this.pic1.comboDepthHelp(1);
} else {
return this.pic2.comboDepthHelp(1);
}
}
public int comboDepthHelp(int rsf) {
if (this.pic1.comboDepthHelp(rsf + 1) > this.pic2.comboDepthHelp(rsf + 1)) {
return this.pic1.comboDepthHelp(rsf + 1);
} else {
return this.pic2.comboDepthHelp(rsf + 1);
}
}
public IOperation mirror() {
return new Beside(pic2, pic1);
}
public String pictureRecipe(int depth) {
return "beside(" + pic1.pictureRecipe(depth - 1) + ", " + pic2.pictureRecipe(depth - 1) + ")";
}
}
class Overlay extends AOperation {
IPicture pic2;
Overlay(IPicture pic1, IPicture pic2) {
super(pic1);
this.pic2 = pic2;
}
public int getWidth() {
if (pic1.getWidth() > pic2.getWidth()) {
return pic1.getWidth();
} else {
return pic2.getWidth();
}
}
public int countShapes() {
return this.pic1.countShapes() + this.pic2.countShapes();
}
public int comboDepth() {
if (this.pic1.comboDepthHelp(1) > this.pic2.comboDepthHelp(1)) {
return this.pic1.comboDepthHelp(1);
} else {
return this.pic2.comboDepthHelp(1);
}
}
public int comboDepthHelp(int rsf) {
if (this.pic1.comboDepthHelp(rsf + 1) > this.pic2.comboDepthHelp(rsf + 1)) {
return this.pic1.comboDepthHelp(rsf + 1);
} else {
return this.pic2.comboDepthHelp(rsf + 1);
}
}
public IOperation mirror() {
return new Overlay(pic1, pic2);
}
public String pictureRecipe(int depth) {
return "overlay(" + pic1.pictureRecipe(depth - 1) + ", " + pic2.pictureRecipe(depth - 1) + ")";
}
}
class ExamplesPicture {
IPicture circ1 = new Shape("circle", 20);
IPicture sq1 = new Shape("square", 30);
IPicture cbo1 = new Combo("big circle", new Scale(circ1));
IPicture cbo2 = new Combo("square on circle", new Overlay(sq1, cbo1));
IPicture cbo3 = new Combo("doubled square on circle", new Beside(cbo2, cbo2));
IPicture cbo4 = new Combo("square beside circle", new Beside(circ1, sq1));
boolean testGetWidth(Tester t) {
return t.checkExpect(this.circ1.getWidth(), 20) &&
t.checkExpect(this.sq1.getWidth(), 30) &&
t.checkExpect(this.cbo1.getWidth(), 20 * 2) &&
t.checkExpect(this.cbo2.getWidth(), 40) &&
t.checkExpect(this.cbo3.getWidth(), 80);
}
boolean testCountShapes(Tester t) {
return t.checkExpect(this.circ1.countShapes(), 1) &&
t.checkExpect(this.sq1.countShapes(), 1) &&
t.checkExpect(this.cbo1.countShapes(), 1) &&
t.checkExpect(this.cbo2.countShapes(), 2) &&
t.checkExpect(this.cbo3.countShapes(), 4);
}
boolean testComboDepth(Tester t) {
return t.checkExpect(this.circ1.comboDepth(), 0) &&
t.checkExpect(this.sq1.comboDepth(), 0) &&
t.checkExpect(this.cbo1.comboDepth(), 1) &&
t.checkExpect(this.cbo2.comboDepth(), 2) &&
t.checkExpect(this.cbo3.comboDepth(), 3);
}
boolean testMirror(Tester t) {
return t.checkExpect(this.circ1.mirror(), this.circ1) &&
t.checkExpect(this.sq1.mirror(), this.sq1) &&
t.checkExpect(this.cbo1.mirror(), this.cbo1) &&
t.checkExpect(this.cbo2.mirror(), this.cbo2) &&
t.checkExpect(this.cbo4.mirror(),
new Combo("square beside circle", new Beside(sq1, circ1)));
}
boolean testPictureRecipe(Tester t) {
return t.checkExpect(this.circ1.pictureRecipe(0), "circle") &&
t.checkExpect(this.cbo3.pictureRecipe(0),
"doubled square on circle") &&
t.checkExpect(this.cbo3.pictureRecipe(1),
"beside(square on circle, square on circle)") &&
t.checkExpect(this.cbo3.pictureRecipe(2),
"beside(overlay(square, big circle), overlay(square, big circle))") &&
t.checkExpect(this.cbo3.pictureRecipe(3),
"beside(overlay(square, scale(circle)), overlay(square, scale(circle)))") &&
t.checkExpect(this.cbo3.pictureRecipe(4),
"beside(overlay(square, scale(circle)), overlay(square, scale(circle)))");
}
}

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/javalib.jar"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/tester.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Assn03</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=11
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=11

View File

@ -0,0 +1,243 @@
// CS 2510, Assignment 3
import tester.Tester;
// to represent a list of Strings
interface ILoString {
// combine all Strings in this list into one
String combine();
// returns a new list, sorted in alphabetical order, treating all Strings
// as if they were given in all lowercase.
ILoString sort();
ILoString sortHelp(String that);
// returns if this list is sorted in alphabetical order, in a case-insensitive way.
boolean isSorted();
boolean isSortedHelp(String that);
// returns a list where the first, third, fifth... elements are from this
// list, and the second, fourth, sixth... elements are from the given list.
// When one list is longer than the other extras will be left at the end.
ILoString interleave(ILoString that);
ILoString interleaveHelp(String prefix, ILoString that);
// returns a sorted list of Strings that contains all items in both original
// lists, including duplicates.
ILoString merge(ILoString that);
// returns a list of Strings containing the list of string in reverse order.
ILoString reverse();
ILoString reverseHelp(ILoString rsf);
// returns if this list contains pairs of identical strings, that is, the first
// and second strings are the same, the third and fourth are the same, etc.
boolean isDoubledList();
boolean isDoubledListHelp(String check);
// returns whether this list contains the same words reading the list in either order.
boolean isPalindromeList();
}
// to represent an empty list of Strings
class MtLoString implements ILoString {
MtLoString() {}
// combine all Strings in this list into one
public String combine() {
return "";
}
public ILoString sort() {
return this;
}
public ILoString sortHelp(String that) {
return new ConsLoString(that, this);
}
public boolean isSorted() {
return true;
}
public boolean isSortedHelp(String that) {
return true;
}
public ILoString interleave(ILoString that) {
return that;
}
public ILoString interleaveHelp(String prefix, ILoString that) {
return new ConsLoString(prefix, that);
}
public ILoString merge(ILoString that) {
return that.sort();
}
public ILoString reverse() {
return this;
}
public ILoString reverseHelp(ILoString rsf) {
return rsf;
}
public boolean isDoubledList() {
return true;
}
public boolean isDoubledListHelp(String check) {
return false;
}
public boolean isPalindromeList() {
return false;
}
}
// to represent a nonempty list of Strings
class ConsLoString implements ILoString {
String first;
ILoString rest;
ConsLoString(String first, ILoString rest) {
this.first = first;
this.rest = rest;
}
/*
TEMPLATE
FIELDS:
... this.first ... -- String
... this.rest ... -- ILoString
METHODS
... this.combine() ... -- String
METHODS FOR FIELDS
... this.first.concat(String) ... -- String
... this.first.compareTo(String) ... -- int
... this.rest.combine() ... -- String
*/
// combine all Strings in this list into one
public String combine() {
return this.first.concat(this.rest.combine());
}
public ILoString sort() {
return this.rest.sort().sortHelp(this.first);
}
public ILoString sortHelp(String that) {
if (this.first.compareTo(that) < 0) {
return new ConsLoString(this.first, rest.sortHelp(that));
} else {
return new ConsLoString(that, rest.sortHelp(this.first));
}
}
public boolean isSorted() {
return this.rest.isSortedHelp(this.first);
}
public boolean isSortedHelp(String that) {
return this.first.compareTo(that) > 0 && this.rest.isSortedHelp(this.first);
}
public ILoString interleave(ILoString that) {
return that.interleaveHelp(this.first, this.rest);
}
public ILoString interleaveHelp(String prefix, ILoString that) {
return new ConsLoString(prefix, that.interleaveHelp(this.first, this.rest));
}
public ILoString merge(ILoString that) {
return this.interleave(that).sort();
}
public ILoString reverse() {
return this.rest.reverseHelp(new ConsLoString(this.first, new MtLoString()));
}
public ILoString reverseHelp(ILoString rsf) {
return this.rest.reverseHelp(new ConsLoString(this.first, rsf));
}
public boolean isDoubledList() {
return this.rest.isDoubledListHelp(this.first);
}
public boolean isDoubledListHelp(String check) {
return check == this.first && rest.isDoubledList();
}
public boolean isPalindromeList() {
return this.interleave(this.reverse()).isDoubledList();
}
}
// to represent examples for lists of strings
class ExamplesStrings {
ILoString mary = new ConsLoString("Mary ",
new ConsLoString("had ",
new ConsLoString("a ",
new ConsLoString("little ",
new ConsLoString("lamb.", new MtLoString())))));
ILoString marySorted = new ConsLoString("Mary ",
new ConsLoString("a ",
new ConsLoString("had ",
new ConsLoString("lamb.",
new ConsLoString("little ", new MtLoString())))));
ILoString maryReverse = new ConsLoString("lamb.",
new ConsLoString("little ",
new ConsLoString("a ",
new ConsLoString("had ",
new ConsLoString("Mary ", new MtLoString())))));
ILoString abcLower = new ConsLoString("a",
new ConsLoString("b", new ConsLoString("c", new MtLoString())));
ILoString cbaLower = new ConsLoString("c",
new ConsLoString("b", new ConsLoString("a", new MtLoString())));
ILoString defghLower = new ConsLoString("d", new ConsLoString("e",
new ConsLoString("f", new ConsLoString("g", new ConsLoString("h", new MtLoString())))));
ILoString abcdefghLower = new ConsLoString("a", new ConsLoString("b",
new ConsLoString("c", new ConsLoString("d",
new ConsLoString("e", new ConsLoString("f",
new ConsLoString("g", new ConsLoString("h", new MtLoString()))))))));
ILoString abcUpper = new ConsLoString("A",
new ConsLoString("B", new ConsLoString("C", new MtLoString())));
ILoString acbMixed = new ConsLoString("A",
new ConsLoString("C", new ConsLoString("b", new MtLoString())));
ILoString bcaLower = new ConsLoString("b",
new ConsLoString("c", new ConsLoString("a", new MtLoString())));
ILoString bcaMixed = new ConsLoString("b",
new ConsLoString("C", new ConsLoString("A", new MtLoString())));
ILoString abcInterleave = new ConsLoString("a", new ConsLoString("A",
new ConsLoString("b", new ConsLoString("B",
new ConsLoString("c", new ConsLoString("C", new MtLoString()))))));
ILoString adbecfghInterleave = new ConsLoString("a", new ConsLoString("d",
new ConsLoString("b", new ConsLoString("e",
new ConsLoString("c", new ConsLoString("f",
new ConsLoString("g", new ConsLoString("h", new MtLoString()))))))));
ILoString daedfcghInterleave = new ConsLoString("d", new ConsLoString("a",
new ConsLoString("e", new ConsLoString("b",
new ConsLoString("f", new ConsLoString("c",
new ConsLoString("g", new ConsLoString("h", new MtLoString()))))))));
ILoString abcbaLower = new ConsLoString("a", new ConsLoString("b",
new ConsLoString("c", new ConsLoString("b", new ConsLoString("a", new MtLoString())))));
ILoString abccbaLower = new ConsLoString("a", new ConsLoString("b",
new ConsLoString("c", new ConsLoString("c",
new ConsLoString("b", new ConsLoString("a", new MtLoString()))))));
boolean testCombine(Tester t) {
return t.checkExpect(this.mary.combine(), "Mary had a little lamb.");
}
boolean testSort(Tester t) {
return t.checkExpect(this.bcaLower.sort(), this.abcLower) &&
t.checkExpect(this.bcaMixed.sort(), this.acbMixed) &&
t.checkExpect(this.mary.sort(), this.marySorted);
}
boolean testIsSorted(Tester t) {
return t.checkExpect(this.abcLower.isSorted(), true) &&
t.checkExpect(this.bcaLower.isSorted(), false) &&
t.checkExpect(this.mary.isSorted(), false) &&
t.checkExpect(this.marySorted.isSorted(), true);
}
boolean testInterleave(Tester t) {
return t.checkExpect(this.abcLower.interleave(abcUpper), this.abcInterleave) &&
t.checkExpect(this.abcLower.interleave(defghLower), this.adbecfghInterleave) &&
t.checkExpect(this.defghLower.interleave(abcLower), this.daedfcghInterleave);
}
boolean testMerge(Tester t) {
return t.checkExpect(this.abcLower.merge(abcUpper), this.abcInterleave.sort()) &&
t.checkExpect(this.abcLower.merge(defghLower), this.abcdefghLower) &&
t.checkExpect(this.defghLower.merge(abcLower), this.abcdefghLower);
}
boolean testReverse(Tester t) {
return t.checkExpect(this.abcLower.reverse(), this.cbaLower) &&
t.checkExpect(this.mary.reverse(), this.maryReverse);
}
boolean testIsDoubledList(Tester t) {
return t.checkExpect(this.abcLower.merge(this.abcLower).isDoubledList(), true) &&
t.checkExpect(this.mary.isDoubledList(), false);
}
boolean testIsPalindromeList(Tester t) {
return t.checkExpect(this.abcbaLower.isPalindromeList(), true) &&
t.checkExpect(this.abccbaLower.isPalindromeList(), true) &&
t.checkExpect(this.mary.isPalindromeList(), false);
}
}

View File

@ -0,0 +1,183 @@
import tester.*;
import javalib.worldimages.*;
import javalib.funworld.*;
import javalib.worldcanvas.*;
import java.awt.Color;
interface ITree {
WorldImage draw();
boolean isDrooping();
boolean isDroopingHelp(double rotation);
ITree combine(int leftLength, int rightLength, double leftTheta, double rightTheta,
ITree otherTree);
double getWidth();
}
class Leaf implements ITree {
int size; // represents the radius of the leaf
Color color; // the color to draw it
Leaf(int size, Color color) {
this.size = size;
this.color = color;
}
public WorldImage draw() {
return new CircleImage(this.size, OutlineMode.SOLID, this.color);
}
public boolean isDrooping() {
return false;
}
public boolean isDroopingHelp(double rotation) {
return false;
}
public ITree combine(int leftLength, int rightLength, double leftTheta, double rightTheta,
ITree otherTree) {
return this;
}
public double getWidth() {
return 0;
}
}
class Stem implements ITree {
Color COLORSTEM = Color.BLACK;
// How long this stick is
int length;
// The angle (in degrees) of this stem, relative to the +x axis
double theta;
// The rest of the tree
ITree tree;
Stem(int length, double theta, ITree tree) {
this.length = length;
this.theta = theta;
this.tree = tree;
}
public WorldImage draw() {
Utils u = new Utils();
return u.drawTreeonLinePinhole(this.length, this.theta - 90, this.tree, 0, this.length,
this.COLORSTEM);
// new RotateImage(new OverlayOffsetImage(this.tree.draw(), 0, this.length,
// new LineImage(new Posn(0, this.length), this.COLORSTEM)), this.theta - 90);
}
public boolean isDrooping() {
return (this.theta % 360) > 180 && (this.theta % 360) < 360;
}
public boolean isDroopingHelp(double rotation) {
return ((this.theta + rotation) % 360) > 180 && ((this.theta + rotation) % 360) < 360;
}
public ITree combine(int leftLength, int rightLength, double leftTheta, double rightTheta,
ITree otherTree) {
return this;
}
public double getWidth() {
return length;
}
}
class Branch implements ITree {
Color COLORBRANCH = Color.BLACK;
// How long the left and right branches are
int leftLength;
int rightLength;
// The angle (in degrees) of the two branches, relative to the +x axis,
double leftTheta;
double rightTheta;
// The remaining parts of the tree
ITree left;
ITree right;
Branch(int leftLength, int rightLength, double leftTheta, double rightTheta, ITree left,
ITree right) {
this.leftLength = leftLength;
this.rightLength = rightLength;
this.leftTheta = leftTheta - 180;
this.rightTheta = rightTheta;
this.left = left;
this.right = right;
}
public WorldImage draw() {
Utils u = new Utils();
return new BesideAlignImage(AlignModeY.BOTTOM,
u.drawTreeonLinePinhole(this.leftLength, this.leftTheta, this.left, 0, this.leftLength / 2,
this.COLORBRANCH),
u.drawTreeonLinePinhole(this.rightLength, this.rightTheta, this.right, 0,
this.rightLength / 2,
this.COLORBRANCH));
// this.drawHalfBranch(this.leftLength, this.leftTheta, this.left),
// this.drawHalfBranch(this.rightLength, this.rightTheta, this.right));
}
public WorldImage drawHalfBranch(int l, double theta, ITree tree) {
return new RotateImage(new OverlayOffsetImage(
tree.draw(), 0, l / 2,
new LineImage(new Posn(0, l), this.COLORBRANCH)), theta);
}
public boolean isDrooping() {
return this.leftTheta % 360 > 180 && this.leftTheta % 360 < 360 ||
this.rightTheta % 360 > 180 && this.rightTheta % 360 < 360 ||
this.left.isDrooping() ||
this.right.isDrooping();
}
public boolean isDroopingHelp(double rotation) {
return (this.leftTheta + rotation) % 360 > 180 && (this.leftTheta + rotation) % 360 < 360 ||
(this.rightTheta + rotation) % 360 > 180 && (this.rightTheta + rotation) % 360 < 360 ||
this.left.isDroopingHelp(this.leftTheta + rotation) ||
this.right.isDroopingHelp(this.rightTheta + rotation);
}
public ITree combine(int leftLength, int rightLength, double leftTheta, double rightTheta,
ITree otherTree) {
return this;
}
public double getWidth() {
return this.left.getWidth() + this.right.getWidth();
}
}
class Utils {
Utils() {}
public WorldImage drawTreeonLine(int l, double theta, ITree tree, double offsetX, double offsetY,
Color color) {
return new RotateImage(new OverlayOffsetImage(
tree.draw(), offsetX, offsetY,
new LineImage(new Posn(0, l), color)), theta);
}
public WorldImage drawTreeonLinePinhole(int l, double theta, ITree tree, double offsetX,
double offsetY,
Color color) {
return new RotateImage(new OverlayImage(
tree.draw(),
new VisiblePinholeImage(new LineImage(new Posn(0, l), color).movePinhole(0, l))), theta);
}
}
class ExamplesTree {
WorldImage testImage = new CircleImage(30, OutlineMode.OUTLINE, Color.RED);
ITree tree1 = new Branch(30, 30, 135, 40, new Leaf(10, Color.RED), new Leaf(15, Color.BLUE));
ITree tree2 = new Branch(30, 30, 115, 65, new Leaf(15, Color.GREEN), new Leaf(8, Color.ORANGE));
ITree tree3 = new Branch(30, 30, 181, 40, new Leaf(10, Color.RED), new Leaf(15, Color.BLUE));
ITree tree4 = new Branch(30, 30, 135, 719, new Leaf(10, Color.RED), new Leaf(15, Color.BLUE));
ITree stem1 = new Stem(40, 90, tree1);
ITree stem2 = new Stem(50, 90, tree2);
ITree stem3 = new Stem(50, 181, tree1);
ITree stem4 = new Stem(50, 719, tree1);
ITree combine = tree1.combine(40, 50, 150, 30, tree2);
boolean testDrawTree(Tester t) {
WorldCanvas c = new WorldCanvas(500, 500);
WorldScene s = new WorldScene(500, 500);
return c.drawScene(s.placeImageXY(stem2.draw(), 250, 250)) && c.show();
}
// boolean testIsDrooping(Tester t) {
// return t.checkExpect(this.tree1.isDrooping(), false) &&
// t.checkExpect(this.tree3.isDrooping(), true) &&
// t.checkExpect(this.tree4.isDrooping(), true) &&
// t.checkExpect(this.stem1.isDrooping(), false) &&
// t.checkExpect(this.stem3.isDrooping(), true) &&
// t.checkExpect(this.stem4.isDrooping(), true);
// }
// boolean testCombine(Tester t) {
// return false;
// }
// boolean testGetWidth(Tester t) {
// return false;
// }
}

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/javalib.jar"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/tester.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Assn04</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=11
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=11

View File

@ -0,0 +1,93 @@
import tester.Tester;
class BagelRecipe {
double MARGIN = 0.001; // needed for double approximations
double flour;
double water;
double yeast;
double salt;
double malt;
//maximal constructor
BagelRecipe(double flour, double water, double yeast, double salt, double malt) {
Utils u = new Utils();
this.flour = u.checkRatios(flour, flour, water, 1, this.MARGIN,
"Flour: " + Double.toString(flour) + " & Water: " + Double.toString(water) + " be equal");
this.water = water;
this.yeast = u.checkRatios(yeast, yeast, malt, 1, this.MARGIN,
"Yeast: " + Double.toString(yeast) + " & Malt: " + Double.toString(malt) + " be equal");
this.salt = u.checkRatios(salt, flour, salt + yeast, 20, this.MARGIN,
"Flour: " + Double.toString(flour) + " to Yeast: " + Double.toString(yeast) + " + Salt: "
+ Double.toString(salt)
+ " ratio must be 20 times greater");
this.malt = malt;
}
//minimal constructor
BagelRecipe(double flour, double yeast) {
this.flour = flour;
this.water = flour;
this.yeast = yeast;
this.malt = yeast;
this.salt = (flour / 20) - yeast;
}
//weight constructor
BagelRecipe(double flour, double yeast, double salt) {
this.flour = flour * 4.25;
this.water = this.flour;
this.yeast = yeast * 48 / 5;
this.salt = salt * 48 / 10;
this.malt = this.yeast;
}
public boolean sameRecipe(BagelRecipe that) {
Utils u = new Utils();
return u.checkDouble(this.flour, that.flour, 1, this.MARGIN) &&
u.checkDouble(this.water, that.water, 1, this.MARGIN) &&
u.checkDouble(this.yeast, that.yeast, 1, this.MARGIN) &&
u.checkDouble(this.malt, that.malt, 1, this.MARGIN) &&
u.checkDouble(this.salt, that.salt, 1, this.MARGIN);
}
}
class Utils {
public boolean checkDouble(double d1, double d2, double ratio, double margin) {
return Math.abs(d1 - d2 * ratio) < margin;
}
public double checkRatios(double value, double i1, double i2, double ratio, double margin,
String msg) {
if (checkDouble(i1, i2, ratio, margin)) {
return value;
} else {
throw new IllegalArgumentException(msg);
}
}
public boolean sameRecipe(BagelRecipe r1, BagelRecipe r2) {
return r1.sameRecipe(r2);
}
}
class ExamplesBagel {
Utils u = new Utils();
BagelRecipe b1 = new BagelRecipe(100, 100, 1, 4, 1);
BagelRecipe b2 = new BagelRecipe(100, 1);
BagelRecipe b3 = new BagelRecipe(101, 2);
BagelRecipe b4 = new BagelRecipe(23.5, 0.10, 0.83);
boolean testConstructorException(Tester t) {
return t.checkConstructorException(
new IllegalArgumentException("Flour: 101.0 & Water: 100.0 be equal"),
"BagelRecipe", 101.0, 100.0, 1.0, 4.0, 1.1) &&
t.checkConstructorException(
new IllegalArgumentException("Yeast: 2.0 & Malt: 1.0 be equal"),
"BagelRecipe", 100.0, 100.0, 2.0, 4.0, 1.0) &&
t.checkConstructorException(
new IllegalArgumentException(
"Flour: 100.0 to Yeast: 1.0 + Salt: 5.0 ratio must be 20 times greater"),
"BagelRecipe", 100.0, 100.0, 1.0, 5.0, 1.0);
}
boolean testMinConstructor(Tester t) {
return t.checkExpect(u.sameRecipe(b2, b1), true) &&
t.checkExpect(u.sameRecipe(b2, b3), false) &&
t.checkExpect(u.sameRecipe(b2, b1), true) &&
t.checkExpect(b1.sameRecipe(b2), true);
}
}

View File

@ -0,0 +1,165 @@
import tester.*;
interface IEntertainment {
//compute the total price of this Entertainment
double totalPrice();
//computes the minutes of entertainment of this IEntertainment
int duration();
//produce a String that shows the name and price of this IEntertainment
String format();
//is this IEntertainment the same as that one?
boolean sameEntertainment(IEntertainment that);
boolean sameMagazine(String name, double price, String genre, int pages, int installments);
boolean sameTvSeries(String name, double price, int installments, String corporation);
boolean samePodcast(String name, double price, int installments);
}
abstract class AEntertainment implements IEntertainment {
String name;
double price;
int installments;
AEntertainment(String name, double price, int installments) {
this.name = name;
this.price = price;
this.installments = installments;
}
//computes the price of a yearly subscription
public double totalPrice() {
return this.price * this.installments;
}
public int duration() {
return this.installments * 50;
}
public String format() {
return this.name + ": " + Double.toString(this.price);
}
public abstract boolean sameEntertainment(IEntertainment that);
public boolean sameMagazine(String name, double price, String genre, int pages,
int installments) {
return false;
}
public boolean sameTvSeries(String name, double price, int installments, String corporation) {
return false;
}
public boolean samePodcast(String name, double price, int installments) {
return false;
}
}
class Magazine extends AEntertainment {
String genre;
int pages;
Magazine(String name, double price, String genre, int pages, int installments) {
super(name, price, installments);
this.genre = genre;
this.pages = pages;
}
@Override
public int duration() {
return this.pages * 5;
}
public boolean sameEntertainment(IEntertainment that) {
return that.sameMagazine(this.name, this.price, this.genre, this.pages, this.installments);
}
@Override
public boolean sameMagazine(String name, double price, String genre, int pages,
int installments) {
return this.name == name &&
this.price == price &&
this.genre == genre &&
this.pages == pages &&
this.installments == installments;
}
}
class TVSeries extends AEntertainment {
String corporation;
TVSeries(String name, double price, int installments, String corporation) {
super(name, price, installments);
this.corporation = corporation;
}
public boolean sameEntertainment(IEntertainment that) {
return that.sameTvSeries(this.name, this.price, this.installments, this.corporation);
}
@Override
public boolean sameTvSeries(String name, double price, int installments, String corporation) {
return this.name == name &&
this.price == price &&
this.installments == installments &&
this.corporation == corporation;
}
}
class Podcast extends AEntertainment {
Podcast(String name, double price, int installments) {
super(name, price, installments);
}
public boolean sameEntertainment(IEntertainment that) {
return that.samePodcast(this.name, this.price, this.installments);
}
@Override
public boolean samePodcast(String name, double price, int installments) {
return this.name == name &&
this.price == price &&
this.installments == installments;
}
}
class ExamplesEntertainment {
IEntertainment rollingStone = new Magazine("Rolling Stone", 2.55, "Music", 60, 12);
IEntertainment houseOfCards = new TVSeries("House of Cards", 5.25, 13, "Netflix");
IEntertainment serial = new Podcast("Serial", 0.0, 8);
IEntertainment highlights = new Magazine("Highlights", 1.99, "Kids", 50, 12);
IEntertainment taskmaster = new TVSeries("Taskmaster", .99, 10, "Youtube");
IEntertainment dearHank = new Podcast("Dear Hank and John", 0.0, 45);
IEntertainment highlights2 = new Magazine("Highlights", 1.99, "Kids", 50, 12);
IEntertainment taskmaster2 = new TVSeries("Taskmaster", .99, 10, "Youtube");
IEntertainment dearHank2 = new Podcast("Dear Hank and John", 0.0, 45);
//testing total price method
boolean testTotalPrice(Tester t) {
return t.checkInexact(this.rollingStone.totalPrice(), 2.55 * 12, .0001) &&
t.checkInexact(this.houseOfCards.totalPrice(), 5.25 * 13, .0001) &&
t.checkInexact(this.serial.totalPrice(), 0.0, .0001) &&
t.checkInexact(this.highlights.totalPrice(), 1.99 * 12, .0001) &&
t.checkInexact(this.taskmaster.totalPrice(), .99 * 10, .0001) &&
t.checkInexact(this.dearHank.totalPrice(), 0.0, .0001);
}
boolean testDuration(Tester t) {
return t.checkExpect(this.rollingStone.duration(), 5 * 60) &&
t.checkExpect(this.houseOfCards.duration(), 13 * 50) &&
t.checkExpect(this.serial.duration(), 8 * 50) &&
t.checkExpect(this.highlights.duration(), 5 * 50) &&
t.checkExpect(this.taskmaster.duration(), 10 * 50) &&
t.checkExpect(this.dearHank.duration(), 45 * 50);
}
boolean testFormat(Tester t) {
return t.checkExpect(this.rollingStone.format(), "Rolling Stone: 2.55") &&
t.checkExpect(this.houseOfCards.format(), "House of Cards: 5.25") &&
t.checkExpect(this.serial.format(), "Serial: 0.0");
}
boolean testSameEntertainment(Tester t) {
return t.checkExpect(this.rollingStone.sameEntertainment(this.rollingStone), true) &&
t.checkExpect(this.houseOfCards.sameEntertainment(this.houseOfCards), true) &&
t.checkExpect(this.serial.sameEntertainment(this.serial), true) &&
t.checkExpect(this.highlights.sameEntertainment(this.highlights), true) &&
t.checkExpect(this.taskmaster.sameEntertainment(this.taskmaster), true) &&
t.checkExpect(this.dearHank.sameEntertainment(this.dearHank), true) &&
t.checkExpect(this.highlights.sameEntertainment(this.highlights2), true) &&
t.checkExpect(this.taskmaster.sameEntertainment(this.taskmaster2), true) &&
t.checkExpect(this.dearHank.sameEntertainment(this.dearHank2), true) &&
t.checkExpect(this.rollingStone.sameEntertainment(this.highlights), false) &&
t.checkExpect(this.highlights.sameEntertainment(this.rollingStone), false) &&
t.checkExpect(this.houseOfCards.sameEntertainment(this.taskmaster), false) &&
t.checkExpect(this.serial.sameEntertainment(this.dearHank), false) &&
t.checkExpect(this.rollingStone.sameEntertainment(this.taskmaster), false) &&
t.checkExpect(this.rollingStone.sameEntertainment(this.dearHank), false) &&
t.checkExpect(this.houseOfCards.sameEntertainment(this.highlights), false) &&
t.checkExpect(this.houseOfCards.sameEntertainment(this.serial), false) &&
t.checkExpect(this.serial.sameEntertainment(this.highlights), false) &&
t.checkExpect(this.serial.sameEntertainment(this.dearHank), false);
}
}

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/javalib.jar"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/tester.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Assn05</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=11
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=11

View File

@ -0,0 +1,320 @@
import java.awt.Color;
import javalib.worldimages.*;
import javalib.funworld.*;
import java.util.Random;
interface IEntity {
int getX();
int getY();
int getDx();
int getDy();
int getSize();
int getGen();
int getSpeed();
boolean isCollided(ILoEntity that);
boolean isCollidedEntities(IEntity that);
ILoEntity explode(int i, double theta, ILoEntity rest);
WorldImage getImage();
}
abstract class AEntity implements IEntity {
int BULLETSPEED = -8; // pixels/tick
int SHIPSPEED = -1 * BULLETSPEED / 2; // pixels/tick
int XPLAYER = 0;
int YPLAYER = 0;
int x;
int y;
int dx;
int dy;
AEntity(int x, int y, int dx, int dy) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
}
// Constructor needed for creating with default Speed
AEntity(int x, int y, boolean isBullet) {
this.x = x;
this.y = y;
if (isBullet) {
this.dx = 0;
this.dy = BULLETSPEED;
} else {
if (x <= 0) {
this.dx = SHIPSPEED;
this.dy = 0;
} else {
this.dx = SHIPSPEED * -1;
this.dy = 0;
}
}
}
// Constructor for player firing bullet
AEntity(boolean isBullet) {
this.x = XPLAYER;
this.y = YPLAYER;
if (isBullet) {
this.dx = 0;
this.dy = BULLETSPEED;
} else {
throw new IllegalArgumentException("Only Bullets can be created by default constructor");
}
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getDx() {
return this.dx;
}
public int getDy() {
return this.dy;
}
public int getGen() {
throw new IllegalArgumentException("Gen only defined for Bullets");
}
public boolean isCollided(ILoEntity that) {
return that.isCollided(this);
}
public boolean isCollidedEntities(IEntity that) {
return Math.abs(this.getX() - that.getX()) < this.getSize() + that.getSize() &&
Math.abs(this.getY() - that.getY()) < this.getSize() + that.getSize();
}
public ILoEntity explode(int i, double theta, ILoEntity rest) {
return rest;
}
public WorldScene drawEntity(WorldScene scene) {
return scene;
}
}
class Ship extends AEntity {
int SHIPRADIUS = 10;
Color SHIPCOLOR = Color.CYAN;
WorldImage SHIPIMAGE = new CircleImage(this.SHIPRADIUS, OutlineMode.SOLID, this.SHIPCOLOR);
Ship(int x, int y, int dx, int dy) {
super(x, y, dx, dy);
}
Ship(int x, int y) {
super(x, y, false);
}
public int getSize() {
return this.SHIPRADIUS;
}
public int getSpeed() {
return this.SHIPSPEED;
}
public WorldImage getImage() {
return this.SHIPIMAGE;
}
}
class Bullet extends AEntity {
int RADIUS = 2; // pixels
int MAXRADIUS = 10; // pixels
int RADIUSINC = 2; // pixels
Color COLOR = Color.PINK;
int size;
int gen;
Bullet(int x, int y, int dx, int dy, int size, int gen) {
super(x, y, dx, dy);
this.size = size;
this.gen = gen;
}
Bullet(int x, int y, int dx, int dy, int gen) {
super(x, y, dx, dy);
this.size = Math.min(gen * this.RADIUSINC, this.MAXRADIUS);
this.gen = gen;
}
Bullet(int x, int y, int dx, int dy) {
super(x, y, dx, dy);
this.size = this.RADIUS;
this.gen = 0;
}
Bullet(int x, int y) {
super(x, y, true);
this.size = this.RADIUS;
this.gen = 0;
}
Bullet() {
super(true);
this.size = this.RADIUS;
this.gen = 0;
}
@Override
public int getSize() {
return this.size;
}
@Override
public int getGen() {
return this.gen;
}
public int getSpeed() {
return this.BULLETSPEED;
}
@Override
public ILoEntity explode(int i, double theta, ILoEntity rest) {
if (i == 0) {
return rest;
} else {
return new ConsLoBullets(new Bullet(this.x, this.y,
(int) Math.round(this.getSpeed() * Math.sin(theta * i)),
(int) Math.round(this.getSpeed() * Math.cos(theta * i)),
this.gen + 1),
this.explode(i - 1, theta, rest));
}
}
public WorldImage getImage() {
return new CircleImage(this.size, OutlineMode.SOLID, this.COLOR);
}
}
interface ILoEntity {
ILoEntity move();
ILoEntity removeOffscreen(int width, int height);
boolean isCollided(IEntity that);
int countHits(ILoEntity bullets, int shipsDestroyed);
ILoEntity resolveCollisions(ILoEntity loEntities);
ILoEntity fireBullet();
ILoEntity spawnNShips(int n, int width, int height, Random rand);
WorldScene drawEntities(WorldScene scene);
boolean isEmpty();
}
class MtLoEntity implements ILoEntity {
public ILoEntity move() {
return this;
}
public ILoEntity removeOffscreen(int width, int height) {
return this;
}
public boolean isCollided(IEntity that) {
return false;
}
public int countHits(ILoEntity bullets, int shipsDestroyed) {
return shipsDestroyed;
}
public ILoEntity resolveCollisions(ILoEntity loEntities) {
return this;
}
public ILoEntity fireBullet() {
return new ConsLoBullets(new Bullet(), this);
}
public ILoEntity spawnNShips(int n, int width, int height, Random rand) {
return this;
}
public WorldScene drawEntities(WorldScene scene) {
return scene;
}
public boolean isEmpty() {
return true;
}
}
abstract class ALoEntity implements ILoEntity {
IEntity first;
ILoEntity rest;
ALoEntity(IEntity first, ILoEntity rest) {
this.first = first;
this.rest = rest;
}
public int countHits(ILoEntity bullets, int shipsDestroyed) {
throw new IllegalArgumentException("Hit only counted for Ships");
}
public boolean isCollided(IEntity that) {
return this.first.isCollidedEntities(that) || this.rest.isCollided(that);
}
public ILoEntity fireBullet() {
throw new IllegalArgumentException("Can only create new bullet with ConsLoBullet class");
}
public ILoEntity spawnNShips(int n, int width, int height, Random rand) {
throw new IllegalArgumentException("Can only create new ship with ConsLoShips class");
}
public WorldScene drawEntities(WorldScene scene) {
return this.rest.drawEntities(scene.placeImageXY(first.getImage(), first.getX(), first.getY()));
}
public boolean isEmpty() {
return false;
}
}
class ConsLoShips extends ALoEntity {
ConsLoShips(IEntity first, ILoEntity rest) {
super(first, rest);
}
public ILoEntity move() {
return new ConsLoShips(
new Ship(first.getX() + first.getDx(), first.getY() + first.getDy()),
rest.move());
}
public ILoEntity removeOffscreen(int width, int height) {
int x = this.first.getX();
int y = this.first.getY();
if (x > 0 && x < width &&
y > 0 &&
y < height) {
return new ConsLoShips(this.first, rest.removeOffscreen(width, height));
}
return rest.removeOffscreen(width, height);
}
@Override
public int countHits(ILoEntity bullets, int shipsDestroyed) {
if (first.isCollided(bullets)) {
return this.rest.countHits(bullets, shipsDestroyed + 1);
} else {
return this.rest.countHits(bullets, shipsDestroyed);
}
}
public ILoEntity resolveCollisions(ILoEntity loEntities) {
if (this.first.isCollided(loEntities)) {
return this.rest;
} else {
return new ConsLoShips(this.first, this.rest.resolveCollisions(loEntities));
}
}
@Override
public ILoEntity spawnNShips(int n, int x, int y) {
if (n <= 0) {
return this;
} else {
return new ConsLoShips(new Ship(x, y), this);
}
}
}
class ConsLoBullets extends ALoEntity {
ConsLoBullets(IEntity first, ILoEntity rest) {
super(first, rest);
}
public ILoEntity move() {
return new ConsLoBullets(new Bullet(first.getX() + first.getDx(), first.getY() + first.getDy(),
first.getDx(), first.getDy(),
first.getSize(), first.getGen()),
rest.move());
}
public ILoEntity removeOffscreen(int width, int height) {
int x = this.first.getX();
int y = this.first.getY();
if (x > 0 && x < width &&
y > 0 &&
y < height) {
return new ConsLoBullets(this.first, rest.removeOffscreen(width, height));
}
return rest.removeOffscreen(width, height);
}
public ILoEntity resolveCollisions(ILoEntity loEntities) {
if (this.first.isCollided(loEntities)) {
return this.first.explode(this.first.getGen() + 1,
(2 * Math.PI) / (1 + this.first.getGen()),
this.rest);
} else {
return new ConsLoBullets(this.first, this.rest.resolveCollisions(loEntities));
}
}
@Override
public ILoEntity fireBullet() {
return new ConsLoBullets(new Bullet(), this);
}
}

View File

@ -0,0 +1,214 @@
import tester.Tester;
import javalib.worldimages.*;
import java.awt.Color;
import javalib.funworld.*;
class ExamplesNBullets {
NBullets world = new NBullets(10, 0, 314, new MtLoEntity(), new MtLoEntity());
//** Test Entities.java **//
//** Test IEntity components **//
IEntity cShip1 = new Ship(250, 150);
IEntity cBullet1 = new Bullet(250, 150);
IEntity cBullet2 = new Bullet(200, 150);
IEntity cBullet3 = new Bullet(300, 150);
IEntity cBullet4 = new Bullet(250, 100);
IEntity cBullet5 = new Bullet(250, 200);
IEntity cBullet6 = new Bullet(250 + 11, 150);
IEntity cBullet7 = new Bullet(250 - 11, 150);
IEntity cBullet8 = new Bullet(250, 150 + 11);
IEntity cBullet9 = new Bullet(250, 150 - 11);
IEntity cBullet10 = new Bullet(250 + 12, 150);
IEntity cBullet11 = new Bullet(250 - 12, 150);
IEntity cBullet12 = new Bullet(250, 150 + 12);
IEntity cBullet13 = new Bullet(250, 150 - 12);
boolean testIsCollidedEntities(Tester t) {
return t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet1), true) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet2), false) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet3), false) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet4), false) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet5), false) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet6), true) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet7), true) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet8), true) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet9), true) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet10), false) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet11), false) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet12), false) &&
t.checkExpect(this.cShip1.isCollidedEntities(this.cBullet13), false);
}
IEntity gBullet1 = new Bullet(250, 150, 0, 8, 1);
IEntity gBullet2 = new Bullet(250, 150, 0, 8, 2);
IEntity gBullet3 = new Bullet(250, 150, 0, 8, 3);
IEntity gBullet4 = new Bullet(250, 150, 0, 8, 4);
IEntity gBullet6 = new Bullet(250, 150, 0, 8, 6);
ILoEntity gLoBullets1 = new ConsLoBullets(new Bullet(250, 150, 0, -8, 2),
new ConsLoBullets(new Bullet(250, 150, 0, 8, 2), new MtLoEntity()));
ILoEntity gLoBullets2 = new ConsLoBullets(new Bullet(250, 150, 0, -8, 3),
new ConsLoBullets(new Bullet(250, 150, 7, 4, 3),
new ConsLoBullets(new Bullet(250, 150, -7, 4, 3), new MtLoEntity())));
ILoEntity gLoBullets3 = new ConsLoBullets(new Bullet(250, 150, 0, -8, 4),
new ConsLoBullets(new Bullet(250, 150, 8, 0, 4),
new ConsLoBullets(new Bullet(250, 150, 0, 8, 4),
new ConsLoBullets(new Bullet(250, 150, -8, 0, 4), new MtLoEntity()))));
ILoEntity gLoBullets6 = new ConsLoBullets(new Bullet(250, 150, 0, -8, 10, 7),
new ConsLoBullets(new Bullet(250, 150, 6, -5, 10, 7),
new ConsLoBullets(new Bullet(250, 150, 8, 2, 10, 7),
new ConsLoBullets(new Bullet(250, 150, 3, 7, 10, 7),
new ConsLoBullets(new Bullet(250, 150, -3, 7, 10, 7),
new ConsLoBullets(new Bullet(250, 150, -8, 2, 10, 7),
new ConsLoBullets(new Bullet(250, 150, -6, -5, 10, 7),
new MtLoEntity())))))));
boolean testBulletExplode(Tester t) {
return t.checkExpect(
gBullet1.explode(gBullet1.getGen() + 1, (2 * Math.PI) / (1 + gBullet1.getGen()),
new MtLoEntity()),
this.gLoBullets1) &&
t.checkExpect(
gBullet2.explode(gBullet2.getGen() + 1, (2 * Math.PI) / (1 + gBullet2.getGen()),
new MtLoEntity()),
this.gLoBullets2) &&
t.checkExpect(
gBullet3.explode(gBullet3.getGen() + 1, (2 * Math.PI) / (1 + gBullet3.getGen()),
new MtLoEntity()),
this.gLoBullets3) &&
t.checkExpect(
gBullet6.explode(gBullet6.getGen() + 1, (2 * Math.PI) / (1 + gBullet6.getGen()),
new MtLoEntity()),
this.gLoBullets6);
}
//** Test ILoEntity components **//
IEntity bullet1 = new Bullet(250, 100, 0, -8, 4, 1);
IEntity bullet2 = new Bullet(250, 150, 0, -8);
IEntity bullet3 = new Bullet(250, 200);
IEntity bullet4 = new Bullet(250, 92, 0, -8, 4, 1);
IEntity bullet5 = new Bullet(250, 142, 0, -8);
IEntity bullet6 = new Bullet(250, 192);
IEntity bullet7 = new Bullet(world.WIDTH / 2, world.HEIGHT + 8);
IEntity bullet8 = new Bullet(100, 0, 0, -8);
IEntity bullet9 = new Bullet(250, 310);
IEntity ship1 = new Ship(200, 150, 4, 0);
IEntity ship2 = new Ship(250, 150);
IEntity ship3 = new Ship(300, 150);
IEntity ship4 = new Ship(204, 150, 4, 0);
IEntity ship5 = new Ship(254, 150);
IEntity ship6 = new Ship(304, 150);
IEntity ship7 = new Ship(world.WIDTH, world.HEIGHT / 2);
IEntity ship8 = new Ship(0, world.HEIGHT / 2, -4, 0);
IEntity ship9 = new Ship(300, 250);
ILoEntity loBullets1 = new ConsLoBullets(this.bullet1,
new ConsLoBullets(this.bullet2,
new ConsLoBullets(this.bullet3, new MtLoEntity())));
ILoEntity loBullets2 = new ConsLoBullets(this.bullet4,
new ConsLoBullets(this.bullet5,
new ConsLoBullets(this.bullet6, new MtLoEntity())));
ILoEntity loBullets3 = new ConsLoBullets(this.bullet8,
new ConsLoBullets(this.bullet7, this.loBullets1));
ILoEntity loShips1 = new ConsLoShips(this.ship1,
new ConsLoShips(this.ship2,
new ConsLoShips(this.ship3, new MtLoEntity())));
ILoEntity loShips2 = new ConsLoShips(this.ship4,
new ConsLoShips(this.ship5,
new ConsLoShips(this.ship6, new MtLoEntity())));
ILoEntity loShips3 = new ConsLoShips(this.ship8,
new ConsLoShips(this.ship7, this.loShips1));
boolean testMove(Tester t) {
return t.checkExpect(this.loBullets1.move(), this.loBullets2) &&
t.checkExpect(this.loShips1.move(), this.loShips2);
}
boolean testRemoveOffscreen(Tester t) {
return t.checkExpect(this.loBullets3.removeOffscreen(world.WIDTH, world.HEIGHT),
this.loBullets1) &&
t.checkExpect(this.loShips3.removeOffscreen(world.WIDTH, world.HEIGHT),
this.loShips1);
}
ILoEntity loShips4 = new ConsLoShips(this.ship1, new ConsLoShips(this.ship3, new MtLoEntity()));
ILoEntity loBullets4 = new ConsLoBullets(this.bullet1,
this.bullet2.explode(this.bullet2.getGen() + 1, (2 * Math.PI) / (1 + this.bullet2.getGen()),
new ConsLoBullets(this.bullet3, new MtLoEntity())));
boolean testIsCollidedILoEntity(Tester t) {
return t.checkExpect(this.loShips1.isCollided(this.bullet2), true) &&
t.checkExpect(this.loBullets1.isCollided(this.ship2), true) &&
t.checkExpect(this.loShips1.isCollided(this.bullet9), false) &&
t.checkExpect(this.loBullets1.isCollided(this.ship9), false);
}
boolean testCounthits(Tester t) {
return t.checkExpect(new MtLoEntity().countHits(loBullets1, 0), 0) &&
t.checkExpect(this.loShips1.countHits(loBullets1, 0), 1) &&
t.checkExpect(this.loShips1.countHits(loBullets1, 1), 2) &&
t.checkExpect(this.loShips4.countHits(loBullets4, 0), 0) &&
t.checkExpect(this.loShips4.countHits(loBullets4, 1), 1);
}
boolean testResolveCollision(Tester t) {
return t.checkExpect(this.loBullets1.resolveCollisions(this.loShips1), this.loBullets4) &&
t.checkExpect(this.loShips1.resolveCollisions(this.loBullets1), this.loShips4) &&
t.checkExpect(this.loBullets1.resolveCollisions(this.loShips4), this.loBullets1) &&
t.checkExpect(this.loShips4.resolveCollisions(this.loBullets1), this.loShips4);
}
boolean testFireBullet(Tester t) {
return t.checkExpect(new MtLoEntity().fireBullet(),
new ConsLoBullets(new Bullet(), new MtLoEntity())) &&
t.checkExpect(loBullets1.fireBullet(), new ConsLoBullets(new Bullet(), loBullets1));
}
// boolean testSpawnShip(Tester t) {
// return t.checkExpect(new MtLoEntity().spawnShip(this.world.rand),
// new ConsLoShips(new Ship(0, 0), new MtLoEntity())) &&
// t.checkExpect(this.loShips1.spawnShip(this.world.rand),
// new ConsLoShips(new Ship(0, 0), this.loShips1));
// // !!! need a new constructor?
// // how do i make multiple ships and randomize start loc and dir?
// }
//** Test NBullets.java **//
//** Test makeScene Components **//
NBullets world0_noEntities = new NBullets(10, 0, 314, new MtLoEntity(), new MtLoEntity());
NBullets world1_baseTest = new NBullets(10, 0, 314, this.loShips1, this.loBullets1);
WorldScene scene0_blank = new WorldScene(this.world.WIDTH, this.world.HEIGHT);
WorldScene scene0_playerOnly = this.scene0_blank.placeImageXY(world.CHARACTERIMAGE,
this.world.WIDTH / 2, this.world.HEIGHT);
boolean testAddPlayer(Tester t) {
return t.checkExpect(this.world0_noEntities.addPlayer(scene0_blank), this.scene0_playerOnly);
}
//** Test onTick Components **//
NBullets world1_postMove = new NBullets(10, 0, 314, this.loShips2, this.loBullets2); // World1 post move
NBullets world1_wOffscreen = new NBullets(10, 0, 314, this.loShips3, this.loBullets3); // World1 /w offscreen entities
NBullets world1_postHit = new NBullets(10, 1, 314, this.loShips4, this.loBullets4); // World1 post hit
NBullets world2_noHits = new NBullets(10, 0, 314, this.loShips4, this.loBullets4); // no hits
NBullets world3_1bullet = new NBullets(10, 0, 314, new MtLoEntity(),
new ConsLoBullets(new Bullet(), new MtLoEntity()));
NBullets world1_postFire = new NBullets(10, 0, 314, this.loShips1,
new ConsLoBullets(new Bullet(), this.loBullets1));
boolean testMoveEntities(Tester t) {
return t.checkExpect(this.world0_noEntities.moveEntities(), this.world0_noEntities) &&
t.checkExpect(this.world1_baseTest.moveEntities(), this.world1_postMove) &&
t.checkExpect(this.world1_wOffscreen.moveEntities(), this.world1_postMove);
}
boolean testExplodeEntities(Tester t) {
return t.checkExpect(this.world0_noEntities.explodeEntities(), this.world0_noEntities) &&
t.checkExpect(this.world1_baseTest.explodeEntities(), this.world1_postHit) &&
t.checkExpect(this.world2_noHits.explodeEntities(), this.world2_noHits);
}
//** Test onKeyEvents Components **//
boolean testOnKeyEvents(Tester t) {
return t.checkExpect(this.world0_noEntities.onKeyEvent(" "), this.world3_1bullet) &&
t.checkExpect(this.world1_baseTest.onKeyEvent(" "), this.world1_postFire);
}
boolean testBigBang(Tester t) {
// NBullets world = new NBullets(10, 0, 314, new MtLoEntity(), new MtLoEntity());
return this.world1_baseTest.start();
}
}

View File

@ -0,0 +1,153 @@
import tester.*;
import javalib.worldimages.*;
import javalib.funworld.*;
import java.awt.Color;
import java.util.Random;
class MyGame extends World {
int WIDTH;
int HEIGHT;
int currentTick;
int finalTick;
boolean randomText;
boolean randomCircles;
boolean welcomeScreen;
MyGame(int width, int height, int currentTick, int endTick) {
if (width < 0 || height < 0 ||
endTick < 2) {
throw new IllegalArgumentException("Invalid arguments passed to constructor.");
}
this.WIDTH = width;
this.HEIGHT = height;
this.currentTick = currentTick;
this.finalTick = endTick;
this.randomText = false;
this.randomCircles = false;
this.welcomeScreen = true;
}
MyGame(int width, int height, int currentTick, int endTick, boolean randomText,
boolean randomCircles) {
if (width < 0 || height < 0 ||
endTick < 2) {
throw new IllegalArgumentException("Invalid arguments passed to constructor.");
}
this.WIDTH = width;
this.HEIGHT = height;
this.currentTick = currentTick;
this.finalTick = endTick;
this.randomText = randomText;
this.randomCircles = randomCircles;
this.welcomeScreen = false;
}
@Override
public WorldScene makeScene() {
//Make a new scene.
WorldScene scene = new WorldScene(this.WIDTH, this.HEIGHT);
if (this.welcomeScreen) {
scene = this.addWelcomeMessage(scene);
}
if (this.randomText) {
scene = this.addRandomTextToScene(scene);
}
if (this.randomCircles) {
scene = this.addRandomCirclesToScene(scene);
}
scene = this.addInfoToScene(scene);
return scene;
}
WorldScene addWelcomeMessage(WorldScene scene) {
return scene.placeImageXY(new TextImage("Game will start shortly.", Color.green), 250, 250);
}
WorldScene addRandomTextToScene(WorldScene scene) {
//Generate random coordinates between 0 and this.WIDTH (non inclusive)
int randX = (new Random()).nextInt(this.WIDTH);
int randY = (new Random()).nextInt(this.HEIGHT);
//Create a String displaying the random coordinates
String randomText = Integer.toString(randX) + "," + Integer.toString(randY);
//Add it to the scene and return the scene.
return scene.placeImageXY(new TextImage(randomText, Color.blue), randX, randY);
}
WorldScene addRandomCirclesToScene(WorldScene scene) {
//Generate random coordinates between 0 and this.WIDTH (non inclusive)
int randX = (new Random()).nextInt(this.WIDTH);
int randY = (new Random()).nextInt(this.HEIGHT);
//Add a circle to the scene and return the scene.
return scene.placeImageXY(new CircleImage(20, OutlineMode.SOLID, Color.green), randX, randY);
}
WorldScene addInfoToScene(WorldScene scene) {
return scene.placeImageXY(new TextImage("Final tick: " + Integer.toString(this.finalTick)
+ " Current tick: " + Integer.toString(this.currentTick), Color.black), 100, 20);
}
@Override
//This method gets called every tickrate seconds ( see bellow in example class).
public MyGame onTick() {
return this.addRandomText().addRandomCircles().incrementGameTick();
}
public MyGame addRandomText() {
return new MyGame(this.WIDTH, this.HEIGHT, this.currentTick, this.finalTick, true,
this.randomCircles);
}
public MyGame addRandomCircles() {
return new MyGame(this.WIDTH, this.HEIGHT, this.currentTick, this.finalTick, this.randomText,
true);
}
public MyGame incrementGameTick() {
return new MyGame(this.WIDTH, this.HEIGHT, this.currentTick + 1, this.finalTick,
this.randomText, this.randomCircles);
}
public MyGame onKeyEvent(String key) {
//did we press the space update the final tick of the game by 10.
if (key.equals(" ")) {
return new MyGame(this.WIDTH, this.HEIGHT, this.currentTick, this.finalTick + 10, true,
false);
} else {
return this;
}
}
//Check to see if we need to end the game.
@Override
public WorldEnd worldEnds() {
if (this.currentTick == this.finalTick) {
return new WorldEnd(true, this.makeEndScene());
} else {
return new WorldEnd(false, this.makeEndScene());
}
}
public WorldScene makeEndScene() {
WorldScene endScene = new WorldScene(this.WIDTH, this.HEIGHT);
return endScene.placeImageXY(new TextImage("Game Over", Color.red), 250, 250);
}
}
class ExamplesMyWorldProgram {
boolean testBigBang(Tester t) {
MyGame world = new MyGame(500, 500, 1, 20);
//width, height, tickrate = 0.5 means every 0.5 seconds the onTick method will get called.
return world.bigBang(500, 500, 7.0 / 28.0);
}
}

View File

@ -0,0 +1,136 @@
import javalib.worldimages.*;
import javalib.funworld.*;
import java.awt.Color;
import java.util.Random;
class NBullets extends World {
int WIDTH = 500;
int HEIGHT = 300;
double TICKRATE = 1.0 / 28.0;
int SPAWNRATE = 1; // average ticks / spawn
int SPAWNMAX = 3;
Color FONTCOLOR = Color.BLACK;
int FONTSPACING = 10;
WorldImage CHARACTERIMAGE = new OverlayImage(
new EquilateralTriangleImage(40, OutlineMode.SOLID, Color.BLACK),
new RectangleImage(40, 15, OutlineMode.SOLID, Color.DARK_GRAY));
int ammoAvailable;
int shipsDestroyed;
ILoEntity loShips;
ILoEntity loBullets;
Random rand;
// Default Constructor
NBullets(int ammoAvailabe) {
this(ammoAvailabe, 0, new Random(), new MtLoEntity(), new MtLoEntity());
}
// Testing Constructor
NBullets(int ammoAvailabe, int shipsDestroyed, int seed, ILoEntity loShips, ILoEntity loBullets) {
this(ammoAvailabe, shipsDestroyed, new Random(seed), loShips, loBullets);
}
NBullets(int ammoAvailabe, int shipsDestroyed, Random rand, ILoEntity loShips,
ILoEntity loBullets) {
this.ammoAvailable = ammoAvailabe;
this.shipsDestroyed = shipsDestroyed;
this.rand = rand;
this.loShips = loShips;
this.loBullets = loBullets;
}
public boolean start() {
return this.bigBang(WIDTH, HEIGHT, TICKRATE);
}
@Override
public WorldScene makeScene() {
//Make a new scene.
// ** REMEMBER IMAGEXY COUNTS FROM TOP LEFT **
WorldScene scene = new WorldScene(this.WIDTH, this.HEIGHT);
scene = this.addPlayer(scene);
scene = this.addShips(scene);
scene = this.addBullets(scene);
scene = this.addBulletsAvailable(scene);
scene = this.addShipsDowned(scene);
return scene;
}
public WorldScene addPlayer(WorldScene scene) {
// returns scene with player art added
return scene.placeImageXY(this.CHARACTERIMAGE, this.WIDTH / 2, this.HEIGHT);
}
public WorldScene addShips(WorldScene scene) {
// returns scene with all ship art added
return this.loShips.drawEntities(scene);
}
public WorldScene addBullets(WorldScene scene) {
// returns scene with all bullet art added
return this.loBullets.drawEntities(scene);
}
public WorldScene addBulletsAvailable(WorldScene scene) {
// returns scene text of bullets remaining
return scene.placeImageXY(
new TextImage("Bullets Remaining: " + Integer.toString(this.ammoAvailable), this.FONTCOLOR),
this.WIDTH / 2, this.FONTSPACING);
}
public WorldScene addShipsDowned(WorldScene scene) {
// returns scene with text of ships downed so far
return scene.placeImageXY(
new TextImage("Ships Downed: " + Integer.toString(this.shipsDestroyed), this.FONTCOLOR),
this.WIDTH / 2, this.FONTSPACING * 2);
}
@Override
public NBullets onTick() {
return this.moveEntities().explodeEntities().spawnships();
}
public NBullets moveEntities() {
return new NBullets(this.ammoAvailable,
this.shipsDestroyed,
this.rand,
this.loShips.move().removeOffscreen(this.WIDTH, this.HEIGHT),
this.loBullets.move().removeOffscreen(this.WIDTH, this.HEIGHT));
}
public NBullets explodeEntities() {
return new NBullets(this.ammoAvailable,
this.loShips.countHits(this.loBullets, this.shipsDestroyed),
this.rand,
this.loShips.resolveCollisions(this.loBullets),
this.loBullets.resolveCollisions(this.loShips));
}
public NBullets spawnships() {
if (this.rand.nextInt(this.SPAWNRATE) == 0) {
return new NBullets(this.ammoAvailable,
this.shipsDestroyed,
this.rand,
this.loShips.spawnNShips(rand.nextInt(this.SPAWNMAX), this.WIDTH, this.HEIGHT, this.rand),
this.loBullets);
} else {
return this;
}
}
public NBullets onKeyEvent(String key) {
if (key.equals(" ")) {
return new NBullets(this.ammoAvailable,
this.shipsDestroyed,
this.rand,
this.loShips,
this.loBullets.fireBullet());
} else {
return this;
}
}
@Override
public WorldEnd worldEnds() {
if (this.isGameOver()) {
return new WorldEnd(true, this.makeEndScene());
} else {
return new WorldEnd(false, this.makeEndScene());
}
}
public boolean isGameOver() {
return this.ammoAvailable <= 0 && this.loShips.isEmpty() &&
this.loBullets.isEmpty();
}
public WorldScene makeEndScene() {
WorldScene endScene = new WorldScene(this.WIDTH, this.HEIGHT);
return endScene.placeImageXY(new TextImage("Game Over", this.FONTCOLOR), this.WIDTH / 2,
this.HEIGHT / 2);
}
}

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/javalib.jar"/>
<classpathentry kind="lib" path="/Users/nathanhoward/Documents/Code/OSSU-CS/completedwork/core_programming/02_classbased_design/Jars/tester.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Assn06</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=11
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=11

View File

@ -0,0 +1,234 @@
class Book {
String title;
String author;
int price;
Book(String title, String author, int price) {
this.title = title;
this.author = author;
this.price = price;
}
public boolean isSame(Book that) {
return this.title.compareTo(that.title) == 0 &&
this.author.compareTo(that.author) == 0 &&
this.price == that.price;
}
}
interface IComparator<T> {
public int compare(T t1, T t2);
}
class BooksByTitle implements IComparator<Book> {
public int compare(Book b1, Book b2) {
return b1.title.compareTo(b2.title);
}
}
class BooksByAuthor implements IComparator<Book> {
public int compare(Book b1, Book b2) {
return b1.author.compareTo(b2.author);
}
}
class BooksByPrice implements IComparator<Book> {
public int compare(Book b1, Book b2) {
return b1.price - b2.price;
}
}
abstract class ABST<T> {
public T getData() {
throw new RuntimeException("No data item in an empty tree");
}
public ABST<T> getLeft() {
return this;
}
public ABST<T> getRight() {
return this;
}
public ABST<T> order(IComparator<T> comp) {
return this;
}
public ABST<T> insert(T t, IComparator<T> comp) {
return new Node<T>(t, new Leaf<T>(), new Leaf<T>());
}
public boolean present(T t, IComparator<T> comp) {
return false;
}
public T getLeftMost(IComparator<T> comp) {
throw new RuntimeException("No leftmost item of an empty tree");
}
public T getRightMost(IComparator<T> comp) {
throw new RuntimeException("No rightmost item of an empty tree");
}
public T getLeftMostHelper(T rsf, IComparator<T> comp) {
return rsf;
}
public T getRighttMostHelper(T rsf, IComparator<T> comp) {
return rsf;
}
public ABST<T> removeLeftMost(IComparator<T> comp) {
throw new RuntimeException("No left item of an empty tree");
}
public ABST<T> removeRightMost(IComparator<T> comp) {
throw new RuntimeException("No right item of an empty tree");
}
public ABST<T> removeLeftMostHelper(T t, IComparator<T> comp) {
return this;
}
public ABST<T> removeRightMostHelper(T t, IComparator<T> comp) {
return this;
}
public boolean sameTree(ABST<T> that, IComparator<T> comp) {
return that.sameLeaf();
}
public boolean sameNode(T t, ABST<T> that, IComparator<T> comp) {
return false;
}
public boolean sameLeaf() {
return false;
}
public boolean sameData(ABST<T> that, IComparator<T> thisComp, IComparator<T> thatComp) {
return that.sameLeaf();
}
public boolean sameDataHelper(ABST<T> that, IComparator<T> comp) {
return true;
}
public IList<T> buildList(IComparator<T> comp) {
return new MtList<T>();
}
}
class Leaf<T> extends ABST<T> {
Leaf() {}
@Override
public boolean sameLeaf() {
return true;
}
}
class Node<T> extends ABST<T> {
T data;
ABST<T> left;
ABST<T> right;
Node(T data, ABST<T> left, ABST<T> right) {
this.data = data;
this.left = left;
this.right = right;
}
@Override
public ABST<T> getLeft() {
return this.left;
}
@Override
public ABST<T> getRight() {
return this.right;
}
@Override
public T getData() {
return this.data;
}
@Override
public ABST<T> insert(T t, IComparator<T> comp) {
if (comp.compare(this.data, t) > 0) {
return new Node<T>(this.data, this.left.insert(t, comp), this.right);
} else {
return new Node<T>(this.data, this.left, this.right.insert(t, comp));
}
}
@Override
public boolean present(T t, IComparator<T> comp) {
int r = comp.compare(this.data, t);
if (r == 0) {
return true;
} else if (r > 0) {
return this.left.present(t, comp);
} else {
return this.right.present(t, comp);
}
}
@Override
public T getLeftMost(IComparator<T> comp) {
return this.left.getLeftMostHelper(this.data, comp);
}
@Override
public T getRightMost(IComparator<T> comp) {
return this.right.getRighttMostHelper(this.data, comp);
}
@Override
public T getLeftMostHelper(T rsf, IComparator<T> comp) {
return this.left.getLeftMostHelper(this.data, comp);
}
@Override
public T getRighttMostHelper(T rsf, IComparator<T> comp) {
return this.right.getRighttMostHelper(this.data, comp);
}
@Override
public ABST<T> removeRightMost(IComparator<T> comp) {
T rightMost = this.getRightMost(comp);
if (comp.compare(this.data, rightMost) == 0) {
return this.left;
} else {
return new Node<T>(this.data,
this.left,
this.right.removeRightMostHelper(rightMost, comp));
}
}
@Override
public ABST<T> removeLeftMost(IComparator<T> comp) {
T leftMost = this.getLeftMost(comp);
if (comp.compare(this.data, leftMost) == 0) {
return this.right;
} else {
return new Node<T>(this.data,
this.left.removeLeftMostHelper(leftMost, comp),
this.right);
}
}
@Override
public ABST<T> removeRightMostHelper(T t, IComparator<T> comp) {
if (comp.compare(this.data, t) == 0) {
return this.left;
} else {
return new Node<T>(this.data,
this.left,
this.right.removeRightMostHelper(t, comp));
}
}
@Override
public ABST<T> removeLeftMostHelper(T t, IComparator<T> comp) {
if (comp.compare(this.data, t) == 0) {
return this.right;
} else {
return new Node<T>(this.data,
this.left.removeLeftMostHelper(t, comp),
this.right);
}
}
@Override
public boolean sameTree(ABST<T> that, IComparator<T> comp) {
return that.sameNode(this.data, this, comp);
}
@Override
public boolean sameNode(T t, ABST<T> that, IComparator<T> comp) {
return comp.compare(this.data, t) == 0 &&
this.left.sameTree(that.getLeft(), comp) &&
this.right.sameTree(that.getRight(), comp);
}
@Override
public boolean sameData(ABST<T> that, IComparator<T> thisComp, IComparator<T> thatComp) {
return this.sameDataHelper(that, thatComp) &&
that.sameDataHelper(this, thisComp);
}
@Override
public boolean sameDataHelper(ABST<T> that, IComparator<T> comp) {
return that.present(this.getData(), comp) &&
this.left.sameDataHelper(that, comp) &&
this.right.sameDataHelper(that, comp);
}
public IList<T> buildList(IComparator<T> comp) {
return new ConsList<T>(this.getLeftMost(comp),
this.removeLeftMost(comp).buildList(comp));
}
}

View File

@ -0,0 +1,102 @@
import tester.Tester;
class Examples {
Book eragon = new Book("Eragon", "CP", 12);
Book gatsby = new Book("Great Gatsby, The", "FSF", 16);
Book hp = new Book("HP & the search for more money", "JKR", 9000);
Book htdp = new Book("HtDP", "MF", 0);
Book lotr = new Book("Lord of the Rings", "JRRT", 10);
Book pippi = new Book("Pippi Longstocking", "AL", 4);
ABST<Book> leaf = new Leaf<Book>();
ABST<Book> bst_bbt = new Node<Book>(htdp,
new Node<Book>(gatsby, new Node<Book>(eragon, leaf, leaf), new Node<Book>(hp, leaf, leaf)),
new Node<Book>(lotr, leaf, new Node<Book>(pippi, leaf, leaf)));
ABST<Book> bst_bba = new Node<Book>(hp,
new Node<Book>(eragon, new Node<Book>(pippi, leaf, leaf), new Node<Book>(gatsby, leaf, leaf)),
new Node<Book>(lotr, leaf, new Node<Book>(htdp, leaf, leaf)));
ABST<Book> bstPart_bbt = new Node<Book>(htdp,
new Node<Book>(hp, leaf, leaf), new Node<Book>(lotr, leaf, leaf));
BooksByTitle bbt = new BooksByTitle();
BooksByAuthor bba = new BooksByAuthor();
BooksByPrice bbp = new BooksByPrice();
boolean testInsert(Tester t) {
return t.checkExpect(leaf.insert(htdp, bbt),
new Node<Book>(this.htdp, leaf, leaf)) &&
t.checkExpect(leaf.insert(htdp, bbt)
.insert(gatsby, bbt)
.insert(eragon, bbt)
.insert(hp, bbt)
.insert(lotr, bbt)
.insert(pippi, bbt),
this.bst_bbt) &&
t.checkExpect(leaf.insert(hp, bba)
.insert(eragon, bba)
.insert(pippi, bba)
.insert(gatsby, bba)
.insert(lotr, bba)
.insert(htdp, bba),
this.bst_bba);
}
boolean testPresent(Tester t) {
return t.checkExpect(leaf.present(gatsby, bba), false) &&
t.checkExpect(this.bst_bbt.present(gatsby, bbt), true) &&
t.checkExpect(this.bst_bbt.present(pippi, bbt), true) &&
t.checkExpect(this.bst_bba.present(eragon, bba), true) &&
t.checkExpect(this.bst_bba.present(lotr, bba), true) &&
t.checkExpect(this.bst_bba.present(htdp, bba), true) &&
t.checkExpect(this.bst_bba.present(hp, bba), true) &&
t.checkExpect(this.bstPart_bbt.present(gatsby, bbt), false) &&
t.checkExpect(this.bstPart_bbt.present(pippi, bbt), false);
}
ABST<Book> bst_bbt_noEragon = new Node<Book>(htdp,
new Node<Book>(gatsby, leaf, new Node<Book>(hp, leaf, leaf)),
new Node<Book>(lotr, leaf, new Node<Book>(pippi, leaf, leaf)));
boolean testGetDirMost(Tester t) {
return t.checkExpect(this.bst_bbt.getLeftMost(bbt), eragon) &&
t.checkExpect(this.bst_bbt.getRightMost(bbt), pippi) &&
t.checkExpect(this.bst_bbt_noEragon.getLeftMost(bbt), gatsby);
}
ABST<Book> bst_bbt_noEragonGatsby = new Node<Book>(htdp,
new Node<Book>(hp, leaf, leaf),
new Node<Book>(lotr, leaf, new Node<Book>(pippi, leaf, leaf)));
ABST<Book> bst_bbt_noEragonGatsbyHp = new Node<Book>(htdp,
leaf,
new Node<Book>(lotr, leaf, new Node<Book>(pippi, leaf, leaf)));
ABST<Book> bst_bbt_noEragonGatsbyHpHtdp = new Node<Book>(lotr, leaf,
new Node<Book>(pippi, leaf, leaf));
boolean testRemoveDirMost(Tester t) {
return t.checkExpect(this.bst_bbt.removeLeftMost(bbt), this.bst_bbt_noEragon) &&
t.checkExpect(this.bst_bbt_noEragon.removeLeftMost(bbt), this.bst_bbt_noEragonGatsby) &&
t.checkExpect(this.bst_bbt_noEragonGatsby.removeLeftMost(bbt),
this.bst_bbt_noEragonGatsbyHp) &&
t.checkExpect(this.bst_bbt_noEragonGatsbyHp.removeLeftMost(bbt),
this.bst_bbt_noEragonGatsbyHpHtdp);
}
boolean testSameTree(Tester t) {
return t.checkExpect(this.bst_bbt.sameTree(this.bst_bbt, bbt), true) &&
t.checkExpect(this.bst_bba.sameTree(this.bst_bba, bba), true) &&
t.checkExpect(this.bst_bbt.sameTree(this.bst_bba, bbt), false) &&
t.checkExpect(this.leaf.sameTree(this.bst_bbt, bbt), false) &&
t.checkExpect(this.bst_bba.sameTree(leaf, bba), false) &&
t.checkExpect(this.leaf.sameTree(leaf, bba), true);
}
boolean testSameData(Tester t) {
return t.checkExpect(this.bst_bbt.sameData(bst_bbt, bbt, bbt), true) &&
t.checkExpect(this.bst_bba.sameData(bst_bba, bba, bba), true) &&
t.checkExpect(this.bst_bbt.sameData(bst_bba, bbt, bba), true) &&
t.checkExpect(this.bst_bba.sameData(bst_bbt, bba, bbt), true) &&
t.checkExpect(this.bstPart_bbt.sameData(bst_bbt, bbt, bbt), false) &&
t.checkExpect(this.bst_bbt.sameData(bstPart_bbt, bbt, bbt), false);
}
IList<Book> list_bbt = new ConsList<Book>(this.eragon,
new ConsList<Book>(this.gatsby, new ConsList<Book>(hp,
new ConsList<Book>(this.htdp, new ConsList<Book>(this.lotr,
new ConsList<Book>(this.pippi, new MtList<Book>()))))));
boolean testBuildList(Tester t) {
return t.checkExpect(this.bst_bbt.buildList(bbt), this.list_bbt);
}
}

View File

@ -0,0 +1,45 @@
interface IList<T> {
IList<T> sort(IComparator<T> comp);
IList<T> insertBy(IComparator<T> comp, T t);
int length();
int lengthHelper(int sum);
}
class MtList<T> implements IList<T> {
public IList<T> sort(IComparator<T> comp) {
return this;
}
public IList<T> insertBy(IComparator<T> comp, T t) {
return new ConsList<T>(t, this);
}
public int length() {
return 0;
}
public int lengthHelper(int sum) {
return sum;
}
}
class ConsList<T> implements IList<T> {
T first;
IList<T> rest;
ConsList(T first, IList<T> rest) {
this.first = first;
this.rest = rest;
}
public IList<T> sort(IComparator<T> comp) {
return this.rest.sort(comp).insertBy(comp, this.first);
}
public IList<T> insertBy(IComparator<T> comp, T t) {
if (comp.compare(this.first, t) < 0) {
return new ConsList<T>(this.first, this.rest.insertBy(comp, t));
}
return new ConsList<T>(t, this);
}
public int length() {
return this.lengthHelper(0);
}
public int lengthHelper(int sum) {
return this.rest.lengthHelper(1 + sum);
}
}