Changes a bunch of code
All checks were successful
EpicKnarvik97/Rogue101/pipeline/head This commit looks good

Renames some badly named interfaces and classes
Changes a bunch of packages for better structure
Adds some missing comments
Improves path finding performance somewhat
Adds an NPC death sound
Makes fake walls noticeable
Makes all NPCs drop their items when they die (as the NPCs may steal items from a player)
This commit is contained in:
Kristian Knarvik 2023-08-13 14:24:53 +02:00
parent 74e03006c4
commit 5c19c3133c
118 changed files with 10314 additions and 10155 deletions

View File

@ -1,2 +1,3 @@
# Rogue101
Originally a programming assignment in INF101. Added here for archival.

View File

@ -1,38 +1,38 @@
package inf101.v18.gfx;
public interface IPaintLayer {
/**
* Clear the layer.
*
* <p>
* Everything on the layer is removed, leaving only transparency.
*/
void clear();
/**
* Clear the layer.
*
* <p>
* Everything on the layer is removed, leaving only transparency.
*/
void clear();
/**
* Send this layer to the back, so it will be drawn behind any other layers.
*
* <p>
* There will still be background behind this layer. You may clear it or draw to
* it using {@link Screen#clearBackground()},
* {@link Screen#setBackground(javafx.scene.paint.Color)} and
* {@link Screen#getBackgroundContext()}.
*/
void layerToBack();
/**
* Send this layer to the back, so it will be drawn behind any other layers.
*
* <p>
* There will still be background behind this layer. You may clear it or draw to
* it using {@link Screen#clearBackground()},
* {@link Screen#setBackground(javafx.scene.paint.Color)} and
* {@link Screen#getBackgroundContext()}.
*/
void layerToBack();
/**
* Send this layer to the front, so it will be drawn on top of any other layers.
*/
void layerToFront();
/**
* Send this layer to the front, so it will be drawn on top of any other layers.
*/
void layerToFront();
/**
* @return Width (in pixels) of graphics layer
*/
double getWidth();
/**
* @return Width (in pixels) of graphics layer
*/
double getWidth();
/**
* @return Height (in pixels) of graphics layer
*/
double getHeight();
/**
* @return Height (in pixels) of graphics layer
*/
double getHeight();
}

File diff suppressed because it is too large Load Diff

View File

@ -2,204 +2,196 @@ package inf101.v18.gfx.gfxmode;
/**
* @author anya
*
*/
public class Direction {
/**
* Construct direction from an angle
*
* @param degrees
* Angle in degrees, where 0 is (1,0)
*/
public static Direction fromDegrees(double degrees) {
return new Direction(degrees);
}
/**
* Construct direction from a vector
*
* @param x
* X direction
* @param y
* Y direction
*/
public static Direction fromVector(double x, double y) {
return new Direction(x, y);
}
/**
* Construct direction from an angle
*
* @param degrees Angle in degrees, where 0 is (1,0)
*/
public static Direction fromDegrees(double degrees) {
return new Direction(degrees);
}
private double xDir;
/**
* Construct direction from a vector
*
* @param x X direction
* @param y Y direction
*/
public static Direction fromVector(double x, double y) {
return new Direction(x, y);
}
private double yDir;
private double xDir;
/**
* Create a new direction.
*
* The direction vector will be normalised to a vector of length 1.
*
* @param degrees
* Angle of direction in degrees
*/
public Direction(double degrees) {
double radians = Math.toRadians(degrees);
this.xDir = Math.cos(radians);
this.yDir = Math.sin(radians);
normalize();
}
private double yDir;
/**
* Create a new direction.
*
* The direction vector will be normalised to a vector of length 1.
*
* @param xDir
* X-component of direction vector
* @param yDir
* Y-component of direction vector
*/
public Direction(double xDir, double yDir) {
this.xDir = xDir;
this.yDir = yDir;
normalize();
}
/**
* Create a new direction.
* <p>
* The direction vector will be normalised to a vector of length 1.
*
* @param degrees Angle of direction in degrees
*/
public Direction(double degrees) {
double radians = Math.toRadians(degrees);
this.xDir = Math.cos(radians);
this.yDir = Math.sin(radians);
normalize();
}
/**
* Multiply direction by distance
*
* @param distance
* @return Position delta
*/
public Point getMovement(double distance) {
return new Point(xDir * distance, -yDir * distance);
}
/**
* Create a new direction.
* <p>
* The direction vector will be normalised to a vector of length 1.
*
* @param xDir X-component of direction vector
* @param yDir Y-component of direction vector
*/
public Direction(double xDir, double yDir) {
this.xDir = xDir;
this.yDir = yDir;
normalize();
}
/**
* @return X-component of direction vector
*
* Same as the Math.cos(toRadians())
*/
public double getX() {
return xDir;
}
/**
* Multiply direction by distance
*
* @param distance
* @return Position delta
*/
public Point getMovement(double distance) {
return new Point(xDir * distance, -yDir * distance);
}
/**
* @return Y-component of direction vector
*
* Same as the Math.sin(toRadians())
*/
public double getY() {
return yDir;
}
/**
* @return X-component of direction vector
* <p>
* Same as the Math.cos(toRadians())
*/
public double getX() {
return xDir;
}
private void normalize() {
double l = Math.sqrt(xDir * xDir + yDir * yDir);
if (l >= 0.00001) {
xDir = xDir / l;
yDir = yDir / l;
} else if (xDir > 0) {
xDir = 1;
yDir = 0;
} else if (xDir < 0) {
xDir = -1;
yDir = 0;
} else if (yDir > 0) {
xDir = 0;
yDir = 1;
} else if (yDir < 0) {
xDir = 0;
yDir = -1;
} else {
xDir = 1;
yDir = 0;
}
/**
* @return Y-component of direction vector
* <p>
* Same as the Math.sin(toRadians())
*/
public double getY() {
return yDir;
}
}
private void normalize() {
double l = Math.sqrt(xDir * xDir + yDir * yDir);
if (l >= 0.00001) {
xDir = xDir / l;
yDir = yDir / l;
} else if (xDir > 0) {
xDir = 1;
yDir = 0;
} else if (xDir < 0) {
xDir = -1;
yDir = 0;
} else if (yDir > 0) {
xDir = 0;
yDir = 1;
} else if (yDir < 0) {
xDir = 0;
yDir = -1;
} else {
xDir = 1;
yDir = 0;
}
/**
* Translate to angle (in degrees)
*
* @return Angle in degrees, -180 .. 180
*/
public double toDegrees() {
return Math.toDegrees(Math.atan2(yDir, xDir));
}
}
/**
* Translate to angle (in radians)
*
* @return Angle in radians, - ..
*/
public double toRadians() {
return Math.atan2(yDir, xDir);
}
/**
* Translate to angle (in degrees)
*
* @return Angle in degrees, -180 .. 180
*/
public double toDegrees() {
return Math.toDegrees(Math.atan2(yDir, xDir));
}
@Override
public String toString() {
return String.format("%.2f", toDegrees());
}
/**
* Translate to angle (in radians)
*
* @return Angle in radians, - ..
*/
public double toRadians() {
return Math.atan2(yDir, xDir);
}
/**
* Turn (relative)
*
* @param deltaDir
*/
public Direction turn(Direction deltaDir) {
return new Direction(xDir + deltaDir.xDir, yDir + deltaDir.yDir);
}
@Override
public String toString() {
return String.format("%.2f", toDegrees());
}
/**
* Turn angle degrees
*
* @param angle
*/
public Direction turn(double angle) {
return turnTo(toDegrees() + angle);
}
/**
* Turn (relative)
*
* @param deltaDir
*/
public Direction turn(Direction deltaDir) {
return new Direction(xDir + deltaDir.xDir, yDir + deltaDir.yDir);
}
/**
* Turn around 180 degrees
*/
public Direction turnBack() {
return turn(180.0);
}
/**
* Turn angle degrees
*
* @param angle
*/
public Direction turn(double angle) {
return turnTo(toDegrees() + angle);
}
/**
* Turn left 90 degrees
*/
public Direction turnLeft() {
return turn(90.0);
}
/**
* Turn around 180 degrees
*/
public Direction turnBack() {
return turn(180.0);
}
/**
* Turn right 90 degrees
*/
public Direction turnRight() {
return turn(-90.0);
}
/**
* Turn left 90 degrees
*/
public Direction turnLeft() {
return turn(90.0);
}
/**
* Absolute turn
*
* @param degrees
* Angle in degrees, where 0 is (1,0)
*/
public Direction turnTo(double degrees) {
return new Direction(degrees);
}
/**
* Turn right 90 degrees
*/
public Direction turnRight() {
return turn(-90.0);
}
/**
* Absolute turn
*
* @param degrees Angle in degrees, where 0 is (1,0)
*/
public Direction turnTo(double degrees) {
return new Direction(degrees);
}
/**
* Turn slightly towards a directions
*
* @param dir A direction
* @param percent How much to turn (100.0 is the same as turnTo())
*/
public Direction turnTowards(Direction dir, double percent) {
return new Direction(xDir * (1.00 - percent / 100.0) + dir.xDir * (percent / 100.0),
yDir * (1.00 - percent / 100.0) + dir.yDir * (percent / 100.0));
// double thisAngle = toAngle();
// double otherAngle = dir.toAngle();
// turnTo(thisAngle*(1.00 - percent/100.0) +
// otherAngle*(percent/100.0));
}
/**
* Turn slightly towards a directions
*
* @param dir
* A direction
* @param percent
* How much to turn (100.0 is the same as turnTo())
*/
public Direction turnTowards(Direction dir, double percent) {
return new Direction(xDir * (1.00 - percent / 100.0) + dir.xDir * (percent / 100.0),
yDir * (1.00 - percent / 100.0) + dir.yDir * (percent / 100.0));
// double thisAngle = toAngle();
// double otherAngle = dir.toAngle();
// turnTo(thisAngle*(1.00 - percent/100.0) +
// otherAngle*(percent/100.0));
}
}

View File

@ -1,5 +1,15 @@
package inf101.v18.gfx.gfxmode;
public enum Gravity {
NORTH, NORTHWEST, WEST, SOUTHWEST, SOUTH, SOUTHEAST, EAST, NORTHEAST, CENTER
NORTH,
NORTHWEST,
WEST,
SOUTHWEST,
SOUTH,
SOUTHEAST,
EAST,
NORTHEAST,
CENTER
}

View File

@ -5,45 +5,45 @@ import javafx.scene.paint.Paint;
public interface IPainter extends IPaintLayer {
/**
* Restore graphics settings previously stored by {@link #save()}.
*
* @return {@code this}, for sending more draw commands
*/
IPainter restore();
/**
* Restore graphics settings previously stored by {@link #save()}.
*
* @return {@code this}, for sending more draw commands
*/
IPainter restore();
/**
* Store graphics settings.
*
* @return {@code this}, for sending more draw commands
*/
IPainter save();
/**
* Store graphics settings.
*
* @return {@code this}, for sending more draw commands
*/
IPainter save();
/**
* Set colour used to drawing and filling.
*
* @param ink A colour or paint
* @return {@code this}, for sending more draw commands
*/
IPainter setInk(Paint ink);
/**
* Set colour used to drawing and filling.
*
* @param ink A colour or paint
* @return {@code this}, for sending more draw commands
*/
IPainter setInk(Paint ink);
/**
* Start drawing a shape.
*
* @return An IShape for sending shape drawing commands
*/
IShape shape();
/**
* Start drawing a shape.
*
* @return An IShape for sending shape drawing commands
*/
IShape shape();
/**
* Start drawing with a turtle.
*
* @return An ITurtle for sending turtle drawing commands
*/
ITurtle turtle();
/**
* @return Current ink, as set by {@link #setInk(Paint)}
*/
Paint getInk();
/**
* Start drawing with a turtle.
*
* @return An ITurtle for sending turtle drawing commands
*/
ITurtle turtle();
/**
* @return Current ink, as set by {@link #setInk(Paint)}
*/
Paint getInk();
}

View File

@ -6,234 +6,226 @@ import javafx.scene.shape.Shape;
public interface IShape {
/**
* Add another point to the line path
*
* @param xy
* @return
*/
IShape addPoint(double x, double y);
/**
* Add another point to the line path
*
* @param x
* @param y
* @return
*/
IShape addPoint(double x, double y);
/**
* Add another point to the line path
*
* @param xy
* @return
*/
IShape addPoint(Point xy);
/**
* Add another point to the line path
*
* @param xy
* @return
*/
IShape addPoint(Point xy);
/**
* Set the arc angle for the subsequent draw commands
*
* <p>
* For use with {@link #arc()}
*
* @param a
* The angle, in degrees
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape angle(double a);
/**
* Set the arc angle for the subsequent draw commands
*
* <p>
* For use with {@link #arc()}
*
* @param a The angle, in degrees
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape angle(double a);
/**
* Draw an arc with the current drawing parameters
*
* <p>
* Relevant parameters:
* <li>{@link #at(Point)}, {@link #x(double)}, {@link #gravity(double)}
* <li>{@link #length(double)}
* <li>{@link #angle(double)}
* <li>{@link #gravity(Gravity)}
* <li>{@link #stroke(Paint)}, {@link #fill(Paint)}
* <li>{@link #rotation(double)}
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape arc();
/**
* Draw an arc with the current drawing parameters
*
* <p>
* Relevant parameters:
* <li>{@link #at(Point)}, {@link #x(double)}, {@link #gravity(double)}
* <li>{@link #length(double)}
* <li>{@link #angle(double)}
* <li>{@link #gravity(Gravity)}
* <li>{@link #stroke(Paint)}, {@link #fill(Paint)}
* <li>{@link #rotation(double)}
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape arc();
/**
* Set the (x,y)-coordinates of the next draw command
*
* @param p
* Coordinates
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape at(Point p);
/**
* Set the (x,y)-coordinates of the next draw command
*
* @param p Coordinates
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape at(Point p);
/**
* Close the line path, turning it into a polygon.
*
* @return
*/
IShape close();
/**
* Close the line path, turning it into a polygon.
*
* @return
*/
IShape close();
void draw();
void draw();
void draw(GraphicsContext context);
void draw(GraphicsContext context);
/**
* Draw an ellipse with the current drawing parameters
*
* <p>
* Relevant parameters:
* <li>{@link #at(Point)}, {@link #x(double)}, {@link #gravity(double)}
* <li>{@link #width(double)}, {@link #height(double)}
* <li>{@link #gravity(Gravity)}
* <li>{@link #stroke(Paint)}, {@link #fill(Paint)}
* <li>{@link #rotation(double)}
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape ellipse();
/**
* Draw an ellipse with the current drawing parameters
*
* <p>
* Relevant parameters:
* <li>{@link #at(Point)}, {@link #x(double)}, {@link #gravity(double)}
* <li>{@link #width(double)}, {@link #height(double)}
* <li>{@link #gravity(Gravity)}
* <li>{@link #stroke(Paint)}, {@link #fill(Paint)}
* <li>{@link #rotation(double)}
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape ellipse();
/**
* Fill the current shape
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape fill();
/**
* Fill the current shape
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape fill();
/**
* Set fill colour for the subsequent draw commands
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape fillPaint(Paint p);
/**
* Set fill colour for the subsequent draw commands
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape fillPaint(Paint p);
/**
* Set gravity for the subsequent draw commands
*
* Gravity determines the point on the shape that will be used for positioning
* and rotation.
*
* @param g
* The gravity
* @return
*/
IShape gravity(Gravity g);
/**
* Set gravity for the subsequent draw commands
* <p>
* Gravity determines the point on the shape that will be used for positioning
* and rotation.
*
* @param g The gravity
* @return
*/
IShape gravity(Gravity g);
/**
* Set the height of the next draw command
*
* @param h
* The height
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape height(double h);
/**
* Set the height of the next draw command
*
* @param h The height
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape height(double h);
/**
* Set the length of the following draw commands
*
* <p>
* For use with {@link #line()} and {@link #arc()}
*
* @param l
* The length
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape length(double l);
/**
* Set the length of the following draw commands
*
* <p>
* For use with {@link #line()} and {@link #arc()}
*
* @param l The length
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape length(double l);
/**
* Draw a line with the current drawing parameters
*
* <p>
* Relevant parameters:
* <li>{@link #at(Point)}, {@link #x(double)}, {@link #gravity(double)}
* <li>{@link #length(double)}
* <li>{@link #angle(double)}
* <li>{@link #gravity(Gravity)} (flattened to the horizontal axis, so, e.g.,
* {@link Gravity#NORTH} = {@link Gravity#SOUTH} = {@link Gravity#CENTER})
* <li>{@link #stroke(Paint)}
* <li>{@link #rotation(double)}
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape line();
/**
* Draw a line with the current drawing parameters
*
* <p>
* Relevant parameters:
* <li>{@link #at(Point)}, {@link #x(double)}, {@link #gravity(double)}
* <li>{@link #length(double)}
* <li>{@link #angle(double)}
* <li>{@link #gravity(Gravity)} (flattened to the horizontal axis, so, e.g.,
* {@link Gravity#NORTH} = {@link Gravity#SOUTH} = {@link Gravity#CENTER})
* <li>{@link #stroke(Paint)}
* <li>{@link #rotation(double)}
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape line();
/**
* Draw a rectangle with the current drawing parameters
*
* <p>
* Relevant parameters:
* <li>{@link #at(Point)}, {@link #x(double)}, {@link #gravity(double)}
* <li>{@link #width(double)}, {@link #height(double)}
* <li>{@link #gravity(Gravity)}
* <li>{@link #stroke(Paint)}, {@link #fill(Paint)}
* <li>{@link #rotation(double)}
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape rectangle();
/**
* Draw a rectangle with the current drawing parameters
*
* <p>
* Relevant parameters:
* <li>{@link #at(Point)}, {@link #x(double)}, {@link #gravity(double)}
* <li>{@link #width(double)}, {@link #height(double)}
* <li>{@link #gravity(Gravity)}
* <li>{@link #stroke(Paint)}, {@link #fill(Paint)}
* <li>{@link #rotation(double)}
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape rectangle();
/**
* Sets rotation for subsequent draw commands.
*
* <p>
* Shapes will be rotate around the {@link #gravity(Gravity)} point.
*
* @param angle
* Rotation in degrees
* @return
*/
IShape rotation(double angle);
/**
* Sets rotation for subsequent draw commands.
*
* <p>
* Shapes will be rotate around the {@link #gravity(Gravity)} point.
*
* @param angle Rotation in degrees
* @return
*/
IShape rotation(double angle);
/**
* Stroke the current shape
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape stroke();
/**
* Stroke the current shape
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape stroke();
/**
* Set stroke colour for the subsequent draw commands
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape strokePaint(Paint p);
/**
* Set stroke colour for the subsequent draw commands
*
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape strokePaint(Paint p);
Shape toFXShape();
Shape toFXShape();
String toSvg();
String toSvg();
/**
* Set the width of the next draw command
*
* @param w
* The width
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape width(double w);
/**
* Set the width of the next draw command
*
* @param w The width
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape width(double w);
/**
* Set the x-coordinate of the next draw command
*
* @param x
* Coordinate
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape x(double x);
/**
* Set the x-coordinate of the next draw command
*
* @param x Coordinate
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape x(double x);
/**
* Set the y-coordinate of the next draw command
*
* @param y
* Coordinate
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape y(double y);
/**
* Set the y-coordinate of the next draw command
*
* @param y Coordinate
* @return <code>this</code>, for adding more drawing parameters or issuing the
* draw command
*/
IShape y(double y);
}

View File

@ -2,269 +2,253 @@ package inf101.v18.gfx.gfxmode;
public interface ITurtle extends IPainter {
/**
* This method is used to convert the turtle to an other type, determined by the
* class object given as an argument.
* <p>
* This can be used to access extra functionality not provided by this
* interface, such as direct access to the underlying graphics context.
*
* @param clazz
* @return This object or an appropriate closely related object of the given
* time; or <code>null</code> if no appropriate object can be found
*/
<T> T as(Class<T> clazz);
/**
* This method is used to convert the turtle to another type, determined by the
* class object given as an argument.
* <p>
* This can be used to access extra functionality not provided by this
* interface, such as direct access to the underlying graphics context.
*
* @param clazz
* @return This object or an appropriate closely related object of the given
* time; or <code>null</code> if no appropriate object can be found
*/
<T> T as(Class<T> clazz);
/**
* Move to the given position while drawing a curve
*
* <p>
* The resulting curve is a cubic Bézier curve with the control points located
* at <code>getPos().move(getDirection, startControl)</code> and
* <code>to.move(Direction.fromDegrees(endAngle+180), endControl)</code>.
* <p>
* The turtle is left at point <code>to</code>, facing <code>endAngle</code>.
* <p>
* The turtle will start out moving in its current direction, aiming for a point
* <code>startControl</code> pixels away, then smoothly turning towards its
* goal. It will approach the <code>to</code> point moving in the direction
* <code>endAngle</code> (an absolute bearing, with 0° pointing right and 90°
* pointing up).
*
* @param to
* Position to move to
* @param startControl
* Distance to the starting control point.
* @return {@code this}, for sending more draw commands
*/
ITurtle curveTo(Point to, double startControl, double endAngle, double endControl);
/**
* Move to the given position while drawing a curve
*
* <p>
* The resulting curve is a cubic Bézier curve with the control points located
* at <code>getPos().move(getDirection, startControl)</code> and
* <code>to.move(Direction.fromDegrees(endAngle+180), endControl)</code>.
* <p>
* The turtle is left at point <code>to</code>, facing <code>endAngle</code>.
* <p>
* The turtle will start out moving in its current direction, aiming for a point
* <code>startControl</code> pixels away, then smoothly turning towards its
* goal. It will approach the <code>to</code> point moving in the direction
* <code>endAngle</code> (an absolute bearing, with 0° pointing right and 90°
* pointing up).
*
* @param to Position to move to
* @param startControl Distance to the starting control point.
* @return {@code this}, for sending more draw commands
*/
ITurtle curveTo(Point to, double startControl, double endAngle, double endControl);
void debugTurtle();
void debugTurtle();
/**
* Move forward the given distance while drawing a line
*
* @param dist
* Distance to move
* @return {@code this}, for sending more draw commands
*/
ITurtle draw(double dist);
/**
* Move forward the given distance while drawing a line
*
* @param dist Distance to move
* @return {@code this}, for sending more draw commands
*/
ITurtle draw(double dist);
/**
* Move to the given position while drawing a line
*
* @param x
* X-position to move to
* @param y
* Y-position to move to
* @return {@code this}, for sending more draw commands
*/
ITurtle drawTo(double x, double y);
/**
* Move to the given position while drawing a line
*
* @param x X-position to move to
* @param y Y-position to move to
* @return {@code this}, for sending more draw commands
*/
ITurtle drawTo(double x, double y);
/**
* Move to the given position while drawing a line
*
* @param to
* Position to move to
* @return {@code this}, for sending more draw commands
*/
ITurtle drawTo(Point to);
/**
* Move to the given position while drawing a line
*
* @param to Position to move to
* @return {@code this}, for sending more draw commands
*/
ITurtle drawTo(Point to);
/**
* @return The current angle of the turtle, with 0° pointing to the right and
* 90° pointing up. Same as {@link #getDirection()}.getAngle()
*/
double getAngle();
/**
* @return The current angle of the turtle, with 0° pointing to the right and
* 90° pointing up. Same as {@link #getDirection()}.getAngle()
*/
double getAngle();
/**
* @return The current direction of the turtle. Same as calling
* <code>new Direction(getAngle())</code>
*/
Direction getDirection();
/**
* @return The current direction of the turtle. Same as calling
* <code>new Direction(getAngle())</code>
*/
Direction getDirection();
/**
* @return The current position of the turtle.
*/
Point getPos();
/**
* @return The current position of the turtle.
*/
Point getPos();
/**
* Move a distance without drawing.
*
* @param dist
* Distance to move
* @return {@code this}, for sending more draw commands
*/
ITurtle jump(double dist);
/**
* Move a distance without drawing.
*
* @param dist Distance to move
* @return {@code this}, for sending more draw commands
*/
ITurtle jump(double dist);
/**
* Move a position without drawing.
*
* @param x
* X position to move to
* @param y
* Y position to move to
* @return {@code this}, for sending more draw commands
*/
ITurtle jumpTo(double x, double y);
/**
* Move a position without drawing.
*
* @param x X position to move to
* @param y Y position to move to
* @return {@code this}, for sending more draw commands
*/
ITurtle jumpTo(double x, double y);
/**
* Move a position without drawing.
*
* @param to
* X,Y position to move to
* @return {@code this}, for sending more draw commands
*/
ITurtle jumpTo(Point to);
/**
* Move a position without drawing.
*
* @param to X,Y position to move to
* @return {@code this}, for sending more draw commands
*/
ITurtle jumpTo(Point to);
/**
* Draw a line from the current position to the given position.
*
* <p>
* This method does not change the turtle position.
*
* @param to
* Other end-point of the line
* @return {@code this}, for sending more draw commands
*/
ITurtle line(Point to);
/**
* Draw a line from the current position to the given position.
*
* <p>
* This method does not change the turtle position.
*
* @param to Other end-point of the line
* @return {@code this}, for sending more draw commands
*/
ITurtle line(Point to);
/**
* Set the size of the turtle's pen
*
* @param pixels
* Line width, in pixels
* @return {@code this}, for sending more draw commands
* @requires pixels >= 0
*/
ITurtle setPenSize(double pixels);
/**
* Set the size of the turtle's pen
*
* @param pixels Line width, in pixels
* @return {@code this}, for sending more draw commands
* @requires pixels >= 0
*/
ITurtle setPenSize(double pixels);
/**
* Start drawing a shape at the current turtle position.
*
* <p>
* The shape's default origin and rotation will be set to the turtle's current
* position and direction, but can be modified with {@link IShape#at(Point)} and
* {@link IShape#rotation(double)}.
* <p>
* The turtle's position and attributes are unaffected by drawing the shape.
*
* @return An IDrawParams object for setting up and drawing the shape
*/
@Override
IShape shape();
/**
* Start drawing a shape at the current turtle position.
*
* <p>
* The shape's default origin and rotation will be set to the turtle's current
* position and direction, but can be modified with {@link IShape#at(Point)} and
* {@link IShape#rotation(double)}.
* <p>
* The turtle's position and attributes are unaffected by drawing the shape.
*
* @return An IDrawParams object for setting up and drawing the shape
*/
@Override
IShape shape();
/**
* Change direction the given number of degrees (relative to the current
* direction).
*
* <p>
* Positive degrees turn <em>left</em> while negative degrees turn
* <em>right</em>.
*
* @param degrees
* @return {@code this}, for sending more draw commands
*/
ITurtle turn(double degrees);
/**
* Change direction the given number of degrees (relative to the current
* direction).
*
* <p>
* Positive degrees turn <em>left</em> while negative degrees turn
* <em>right</em>.
*
* @param degrees
* @return {@code this}, for sending more draw commands
*/
ITurtle turn(double degrees);
/**
* Turn 180°.
*
* <p>
* Same as <code>turn(180)</code> and <code>turn(-180)</code>.
*
* @return {@code this}, for sending more draw commands
*/
ITurtle turnAround();
/**
* Turn 180°.
*
* <p>
* Same as <code>turn(180)</code> and <code>turn(-180)</code>.
*
* @return {@code this}, for sending more draw commands
*/
ITurtle turnAround();
/**
* Turn left 90°.
*
* <p>
* Same as <code>turn(90)</code>.
*
* @return {@code this}, for sending more draw commands
*/
ITurtle turnLeft();
/**
* Turn left 90°.
*
* <p>
* Same as <code>turn(90)</code>.
*
* @return {@code this}, for sending more draw commands
*/
ITurtle turnLeft();
/**
* Turn left.
*
* <p>
* Same as <code>turn(degrees)</code>.
*
* @return {@code this}, for sending more draw commands
* @requires degrees >= 0
*/
ITurtle turnLeft(double degrees);
/**
* Turn left.
*
* <p>
* Same as <code>turn(degrees)</code>.
*
* @return {@code this}, for sending more draw commands
* @requires degrees >= 0
*/
ITurtle turnLeft(double degrees);
/**
* Turn right 90°.
*
* <p>
* Same as <code>turn(-90)</code>.
*
* @return {@code this}, for sending more draw commands
*/
ITurtle turnRight();
/**
* Turn right 90°.
*
* <p>
* Same as <code>turn(-90)</code>.
*
* @return {@code this}, for sending more draw commands
*/
ITurtle turnRight();
/**
* Turn left.
*
* <p>
* Same as <code>turn(-degrees)</code>.
*
* @return {@code this}, for sending more draw commands
* @requires degrees >= 0
*/
ITurtle turnRight(double degrees);
/**
* Turn left.
*
* <p>
* Same as <code>turn(-degrees)</code>.
*
* @return {@code this}, for sending more draw commands
* @requires degrees >= 0
*/
ITurtle turnRight(double degrees);
/**
* Turn to the given bearing.
*
* <p>
* 0° is due right, 90° is up.
*
* @param degrees
* Bearing, in degrees
* @return {@code this}, for sending more draw commands
*/
ITurtle turnTo(double degrees);
/**
* Turn to the given bearing.
*
* <p>
* 0° is due right, 90° is up.
*
* @param degrees Bearing, in degrees
* @return {@code this}, for sending more draw commands
*/
ITurtle turnTo(double degrees);
/**
* Turn towards the given bearing.
*
* <p>
* Use this method to turn slightly towards something.
*
* <p>
* 0° is due right, 90° is up.
*
* @param degrees
* Bearing, in degrees
* @param percent
* How far to turn, in degrees.
* @return {@code this}, for sending more draw commands
*/
ITurtle turnTowards(double degrees, double percent);
/**
* Turn towards the given bearing.
*
* <p>
* Use this method to turn slightly towards something.
*
* <p>
* 0° is due right, 90° is up.
*
* @param degrees Bearing, in degrees
* @param percent How far to turn, in degrees.
* @return {@code this}, for sending more draw commands
*/
ITurtle turnTowards(double degrees, double percent);
/**
* Jump (without drawing) to the given relative position.
* <p>
* The new position will be equal to getPos().move(relPos).
*
* @param relPos
* A position, interpreted relative to current position
* @return {@code this}, for sending more draw commands
*/
ITurtle jump(Point relPos);
/**
* Jump (without drawing) to the given relative position.
* <p>
* The new position will be equal to getPos().move(relPos).
*
* @param relPos A position, interpreted relative to current position
* @return {@code this}, for sending more draw commands
*/
ITurtle jump(Point relPos);
/**
* Move to the given relative position while drawing a line
* <p>
* The new position will be equal to getPos().move(relPos).
*
* @return {@code this}, for sending more draw commands
*/
ITurtle draw(Point relPos);
/**
* Move to the given relative position while drawing a line
* <p>
* The new position will be equal to getPos().move(relPos).
*
* @return {@code this}, for sending more draw commands
*/
ITurtle draw(Point relPos);
}

View File

@ -1,116 +1,113 @@
package inf101.v18.gfx.gfxmode;
public class Point {
private final double x;
private final double y;
private final double x;
private final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Calculate direction towards other position
*
* @param otherPos
* @return
*/
public Direction directionTo(Point otherPos) {
return new Direction(otherPos.x - x, otherPos.y - y);
}
/**
* Calculate direction towards other position
*
* @param otherPos
* @return
*/
public Direction directionTo(Point otherPos) {
return new Direction(otherPos.x - x, otherPos.y - y);
}
/**
* Calculate distance to other position
*
* @param otherPos
* @return
*/
public double distanceTo(Point otherPos) {
return Math.sqrt(Math.pow(x - otherPos.x, 2) + Math.pow(y - otherPos.y, 2));
}
/**
* Calculate distance to other position
*
* @param otherPos
* @return
*/
public double distanceTo(Point otherPos) {
return Math.sqrt(Math.pow(x - otherPos.x, 2) + Math.pow(y - otherPos.y, 2));
}
/**
* @return The X coordinate
*/
public double getX() {
return x;
}
/**
* @return The X coordinate
*/
public double getX() {
return x;
}
/**
* @return The Y coordinate
*/
public double getY() {
return y;
}
/**
* @return The Y coordinate
*/
public double getY() {
return y;
}
/**
* Relative move
*
* @param dir
* Direction
* @param distance
* Distance to move
*/
public Point move(Direction dir, double distance) {
return new Point(x + dir.getX() * distance, y - dir.getY() * distance);
}
/**
* Relative move
*
* @param dir Direction
* @param distance Distance to move
*/
public Point move(Direction dir, double distance) {
return new Point(x + dir.getX() * distance, y - dir.getY() * distance);
}
/**
* Relative move
*
* @param deltaX
* @param deltaY
* @return A new point at x+deltaX, y+deltaY
*/
public Point move(double deltaX, double deltaY) {
return new Point(x + deltaX, y + deltaY);
}
/**
* Relative move
*
* @param deltaX
* @param deltaY
* @return A new point at x+deltaX, y+deltaY
*/
public Point move(double deltaX, double deltaY) {
return new Point(x + deltaX, y + deltaY);
}
/**
* Relative move
*
* @param deltaPos
*/
public Point move(Point deltaPos) {
return new Point(x + deltaPos.x, y + deltaPos.y);
}
/**
* Relative move
*
* @param deltaPos
*/
public Point move(Point deltaPos) {
return new Point(x + deltaPos.x, y + deltaPos.y);
}
/**
* Change position
*
* @param newX
* the new X coordinate
* @param newY
* the new Y coordinate
* @return A new point at newX, newY
*/
public Point moveTo(double newX, double newY) {
return new Point(newX, newY);
}
/**
* Change position
*
* @param newX the new X coordinate
* @param newY the new Y coordinate
* @return A new point at newX, newY
*/
public Point moveTo(double newX, double newY) {
return new Point(newX, newY);
}
@Override
public String toString() {
return String.format("(%.2f,%.2f)", x, y);
}
@Override
public String toString() {
return String.format("(%.2f,%.2f)", x, y);
}
/**
* Multiply this point by a scale factor.
*
* @param factor A scale factor
* @return A new Point, (getX()*factor, getY()*factor)
*/
public Point scale(double factor) {
return new Point(x*factor, y*factor);
}
/**
* Multiply this point by a scale factor.
*
* @param factor A scale factor
* @return A new Point, (getX()*factor, getY()*factor)
*/
public Point scale(double factor) {
return new Point(x * factor, y * factor);
}
/**
* Find difference between points.
* <p>
* The returned value will be such that <code>this.move(deltaTo(point)).equals(point)</code>.
* @param point Another point
* @return A new Point, (point.getX()-getX(), point.getY()-getY())
*/
public Point deltaTo(Point point) {
return new Point(point.x-x, point.y-y);
}
/**
* Find difference between points.
* <p>
* The returned value will be such that <code>this.move(deltaTo(point)).equals(point)</code>.
*
* @param point Another point
* @return A new Point, (point.getX()-getX(), point.getY()-getY())
*/
public Point deltaTo(Point point) {
return new Point(point.x - x, point.y - y);
}
}

View File

@ -1,329 +1,330 @@
package inf101.v18.gfx.gfxmode;
import java.util.List;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Shape;
import java.util.List;
public class ShapePainter implements IShape {
private abstract static class DrawCommand {
protected double calcX(Gravity g, double w) {
switch (g) {
default:
case CENTER:
return w / 2;
case EAST:
return w;
case NORTH:
return w / 2;
case NORTHEAST:
return w;
case NORTHWEST:
return 0;
case SOUTH:
return w / 2;
case SOUTHEAST:
return w;
case SOUTHWEST:
return 0;
case WEST:
return 0;
}
}
private abstract static class DrawCommand {
protected double calcX(Gravity g, double w) {
switch (g) {
default:
case CENTER:
case SOUTH:
case NORTH:
return w / 2;
case EAST:
case NORTHEAST:
case SOUTHEAST:
return w;
case NORTHWEST:
case WEST:
case SOUTHWEST:
return 0;
}
}
protected double calcY(Gravity g, double h) {
switch (g) {
default:
case CENTER:
return h / 2;
case EAST:
return h / 2;
case NORTH:
return 0;
case NORTHEAST:
return 0;
case NORTHWEST:
return 0;
case SOUTH:
return h;
case SOUTHEAST:
return h;
case SOUTHWEST:
return h;
case WEST:
return h / 2;
}
}
protected double calcY(Gravity g, double h) {
switch (g) {
default:
case CENTER:
case EAST:
case WEST:
return h / 2;
case NORTH:
case NORTHWEST:
case NORTHEAST:
return 0;
case SOUTH:
case SOUTHWEST:
case SOUTHEAST:
return h;
}
}
public void fill(GraphicsContext ctx, ShapePainter p) {
ctx.save();
ctx.setFill(p.fill);
ctx.translate(p.x, p.y);
if (p.rot != 0)
ctx.rotate(-p.rot);
fillIt(ctx, p);
ctx.restore();
}
public void fill(GraphicsContext ctx, ShapePainter p) {
ctx.save();
ctx.setFill(p.fill);
ctx.translate(p.x, p.y);
if (p.rot != 0) {
ctx.rotate(-p.rot);
}
fillIt(ctx, p);
ctx.restore();
}
protected abstract void fillIt(GraphicsContext ctx, ShapePainter p);
protected abstract void fillIt(GraphicsContext ctx, ShapePainter p);
// public abstract Shape toFXShape(DrawParams p);
//
// public abstract String toSvg(DrawParams p);
// public abstract Shape toFXShape(DrawParams p);
//
// public abstract String toSvg(DrawParams p);
public void stroke(GraphicsContext ctx, ShapePainter p) {
ctx.save();
ctx.setStroke(p.stroke);
if (p.strokeWidth != 0)
ctx.setLineWidth(p.strokeWidth);
ctx.translate(p.x, p.y);
if (p.rot != 0)
ctx.rotate(-p.rot);
strokeIt(ctx, p);
ctx.restore();
}
public void stroke(GraphicsContext ctx, ShapePainter p) {
ctx.save();
ctx.setStroke(p.stroke);
if (p.strokeWidth != 0) {
ctx.setLineWidth(p.strokeWidth);
}
ctx.translate(p.x, p.y);
if (p.rot != 0) {
ctx.rotate(-p.rot);
}
strokeIt(ctx, p);
ctx.restore();
}
protected abstract void strokeIt(GraphicsContext ctx, ShapePainter p);
}
protected abstract void strokeIt(GraphicsContext ctx, ShapePainter p);
}
private static class DrawEllipse extends DrawCommand {
private static class DrawEllipse extends DrawCommand {
@Override
public void fillIt(GraphicsContext ctx, ShapePainter p) {
ctx.fillOval(-calcX(p.gravity, p.w), -calcY(p.gravity, p.h), p.w, p.h);
}
@Override
public void fillIt(GraphicsContext ctx, ShapePainter p) {
ctx.fillOval(-calcX(p.gravity, p.w), -calcY(p.gravity, p.h), p.w, p.h);
}
@Override
public void strokeIt(GraphicsContext ctx, ShapePainter p) {
ctx.strokeOval(-calcX(p.gravity, p.w), -calcY(p.gravity, p.h), p.w, p.h);
}
}
@Override
public void strokeIt(GraphicsContext ctx, ShapePainter p) {
ctx.strokeOval(-calcX(p.gravity, p.w), -calcY(p.gravity, p.h), p.w, p.h);
}
}
private static class DrawLine extends DrawCommand {
private static class DrawLine extends DrawCommand {
@Override
public void fillIt(GraphicsContext ctx, ShapePainter p) {
if (p.lineSegments != null) {
int nPoints = (p.lineSegments.size() / 2) + 1;
double xs[] = new double[nPoints];
double ys[] = new double[nPoints];
xs[0] = -calcX(p.gravity, p.w);
ys[0] = -calcY(p.gravity, p.h);
for (int i = 0; i < p.lineSegments.size(); i++) {
xs[i] = p.lineSegments.get(i * 2) - p.x;
ys[i] = p.lineSegments.get(i * 2 + 1) - p.y;
}
ctx.fillPolygon(xs, ys, nPoints);
}
}
@Override
public void fillIt(GraphicsContext ctx, ShapePainter p) {
if (p.lineSegments != null) {
int nPoints = (p.lineSegments.size() / 2) + 1;
double[] xs = new double[nPoints];
double[] ys = new double[nPoints];
xs[0] = -calcX(p.gravity, p.w);
ys[0] = -calcY(p.gravity, p.h);
for (int i = 0; i < p.lineSegments.size(); i++) {
xs[i] = p.lineSegments.get(i * 2) - p.x;
ys[i] = p.lineSegments.get(i * 2 + 1) - p.y;
}
ctx.fillPolygon(xs, ys, nPoints);
}
}
@Override
public void strokeIt(GraphicsContext ctx, ShapePainter p) {
if (p.lineSegments == null) {
double x = -calcX(p.gravity, p.w);
double y = -calcY(p.gravity, p.h);
ctx.strokeLine(x, y, x + p.w, y + p.h);
} else {
int nPoints = (p.lineSegments.size() / 2) + 1;
double xs[] = new double[nPoints];
double ys[] = new double[nPoints];
xs[0] = -calcX(p.gravity, p.w);
ys[0] = -calcY(p.gravity, p.h);
for (int i = 0; i < p.lineSegments.size(); i++) {
xs[i] = p.lineSegments.get(i * 2) - p.x;
ys[i] = p.lineSegments.get(i * 2 + 1) - p.y;
}
if (p.closed)
ctx.strokePolygon(xs, ys, nPoints);
else
ctx.strokePolyline(xs, ys, nPoints);
}
}
}
@Override
public void strokeIt(GraphicsContext ctx, ShapePainter p) {
if (p.lineSegments == null) {
double x = -calcX(p.gravity, p.w);
double y = -calcY(p.gravity, p.h);
ctx.strokeLine(x, y, x + p.w, y + p.h);
} else {
int nPoints = (p.lineSegments.size() / 2) + 1;
double[] xs = new double[nPoints];
double[] ys = new double[nPoints];
xs[0] = -calcX(p.gravity, p.w);
ys[0] = -calcY(p.gravity, p.h);
for (int i = 0; i < p.lineSegments.size(); i++) {
xs[i] = p.lineSegments.get(i * 2) - p.x;
ys[i] = p.lineSegments.get(i * 2 + 1) - p.y;
}
if (p.closed) {
ctx.strokePolygon(xs, ys, nPoints);
} else {
ctx.strokePolyline(xs, ys, nPoints);
}
}
}
}
private static class DrawRectangle extends DrawCommand {
private static class DrawRectangle extends DrawCommand {
@Override
public void fillIt(GraphicsContext ctx, ShapePainter p) {
ctx.fillRect(-calcX(p.gravity, p.w), -calcY(p.gravity, p.h), p.w, p.h);
}
@Override
public void fillIt(GraphicsContext ctx, ShapePainter p) {
ctx.fillRect(-calcX(p.gravity, p.w), -calcY(p.gravity, p.h), p.w, p.h);
}
@Override
public void strokeIt(GraphicsContext ctx, ShapePainter p) {
ctx.strokeRect(-calcX(p.gravity, p.w), -calcY(p.gravity, p.h), p.w, p.h);
}
}
@Override
public void strokeIt(GraphicsContext ctx, ShapePainter p) {
ctx.strokeRect(-calcX(p.gravity, p.w), -calcY(p.gravity, p.h), p.w, p.h);
}
}
private double x = 0, y = 0, w = 0, h = 0, rot = 0, strokeWidth = 0;
private List<Double> lineSegments = null;
private Paint fill = null;
private Paint stroke = null;
private double x = 0;
private double y = 0;
private double w = 0;
private double h = 0;
private double rot = 0;
private final double strokeWidth = 0;
private final List<Double> lineSegments = null;
private Paint fill = null;
private Paint stroke = null;
private Gravity gravity = Gravity.CENTER;
private Gravity gravity = Gravity.CENTER;
private DrawCommand cmd = null;
private DrawCommand cmd = null;
private boolean closed = false;
private boolean closed = false;
private final GraphicsContext context;
private final GraphicsContext context;
public ShapePainter(GraphicsContext context) {
super();
this.context = context;
}
public ShapePainter(GraphicsContext context) {
super();
this.context = context;
}
@Override
public IShape addPoint(double x, double y) {
lineSegments.add(x);
lineSegments.add(y);
return this;
}
@Override
public IShape addPoint(double x, double y) {
lineSegments.add(x);
lineSegments.add(y);
return this;
}
@Override
public IShape addPoint(Point xy) {
lineSegments.add(xy.getX());
lineSegments.add(xy.getY());
return this;
}
@Override
public IShape addPoint(Point xy) {
lineSegments.add(xy.getX());
lineSegments.add(xy.getY());
return this;
}
@Override
public ShapePainter angle(double a) {
return this;
}
@Override
public ShapePainter angle(double a) {
return this;
}
@Override
public IShape arc() {
throw new UnsupportedOperationException();
}
@Override
public IShape arc() {
throw new UnsupportedOperationException();
}
@Override
public ShapePainter at(Point p) {
if (p != null) {
this.x = p.getX();
this.y = p.getY();
} else {
this.x = 0;
this.y = 0;
}
return this;
}
@Override
public ShapePainter at(Point p) {
if (p != null) {
this.x = p.getX();
this.y = p.getY();
} else {
this.x = 0;
this.y = 0;
}
return this;
}
@Override
public IShape close() {
closed = true;
return this;
}
@Override
public IShape close() {
closed = true;
return this;
}
@Override
public void draw() {
draw(context);
}
@Override
public void draw() {
draw(context);
}
@Override
public void draw(GraphicsContext context) {
if (cmd != null && context != null) {
if (fill != null)
cmd.fill(context, this);
if (stroke != null)
cmd.stroke(context, this);
}
}
@Override
public void draw(GraphicsContext context) {
if (cmd != null && context != null) {
if (fill != null) {
cmd.fill(context, this);
}
if (stroke != null) {
cmd.stroke(context, this);
}
}
}
@Override
public IShape ellipse() {
cmd = new DrawEllipse();
return this;
}
@Override
public IShape ellipse() {
cmd = new DrawEllipse();
return this;
}
@Override
public ShapePainter fill() {
if (cmd != null && context != null)
cmd.fill(context, this);
return this;
}
@Override
public ShapePainter fill() {
if (cmd != null && context != null) {
cmd.fill(context, this);
}
return this;
}
@Override
public ShapePainter fillPaint(Paint p) {
fill = p;
return this;
}
@Override
public ShapePainter fillPaint(Paint p) {
fill = p;
return this;
}
@Override
public ShapePainter gravity(Gravity g) {
gravity = g;
return this;
}
@Override
public ShapePainter gravity(Gravity g) {
gravity = g;
return this;
}
@Override
public ShapePainter height(double h) {
this.h = h;
return this;
}
@Override
public ShapePainter height(double h) {
this.h = h;
return this;
}
@Override
public ShapePainter length(double l) {
w = l;
h = l;
return this;
}
@Override
public ShapePainter length(double l) {
w = l;
h = l;
return this;
}
@Override
public IShape line() {
cmd = new DrawLine();
return this;
}
@Override
public IShape line() {
cmd = new DrawLine();
return this;
}
@Override
public IShape rectangle() {
cmd = new DrawRectangle();
return this;
}
@Override
public IShape rectangle() {
cmd = new DrawRectangle();
return this;
}
@Override
public ShapePainter rotation(double angle) {
rot = angle;
return this;
}
@Override
public ShapePainter rotation(double angle) {
rot = angle;
return this;
}
@Override
public ShapePainter stroke() {
if (cmd != null && context != null)
cmd.stroke(context, this);
return this;
}
@Override
public ShapePainter stroke() {
if (cmd != null && context != null) {
cmd.stroke(context, this);
}
return this;
}
@Override
public ShapePainter strokePaint(Paint p) {
stroke = p;
return this;
}
@Override
public ShapePainter strokePaint(Paint p) {
stroke = p;
return this;
}
@Override
public Shape toFXShape() {
throw new UnsupportedOperationException();
}
@Override
public Shape toFXShape() {
throw new UnsupportedOperationException();
}
@Override
public String toSvg() {
throw new UnsupportedOperationException();
}
@Override
public String toSvg() {
throw new UnsupportedOperationException();
}
@Override
public ShapePainter width(double w) {
this.w = w;
return this;
}
@Override
public ShapePainter width(double w) {
this.w = w;
return this;
}
@Override
public ShapePainter x(double x) {
this.x = x;
return this;
}
@Override
public ShapePainter x(double x) {
this.x = x;
return this;
}
@Override
public ShapePainter y(double y) {
this.y = y;
return this;
}
@Override
public ShapePainter y(double y) {
this.y = y;
return this;
}
}

View File

@ -1,8 +1,5 @@
package inf101.v18.gfx.gfxmode;
import java.util.ArrayList;
import java.util.List;
import inf101.v18.gfx.IPaintLayer;
import inf101.v18.gfx.Screen;
import javafx.scene.canvas.Canvas;
@ -12,362 +9,382 @@ import javafx.scene.paint.Paint;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeLineJoin;
import java.util.ArrayList;
import java.util.List;
public class TurtlePainter implements IPaintLayer, ITurtle {
static class TurtleState {
protected Point pos;
protected Direction dir;
protected Direction inDir;
protected double penSize = 1.0;
protected Paint ink = Color.BLACK;
static class TurtleState {
protected Point pos;
protected Direction dir;
protected Direction inDir;
protected double penSize = 1.0;
protected Paint ink = Color.BLACK;
public TurtleState() {
}
public TurtleState() {
}
public TurtleState(TurtleState s) {
pos = s.pos;
dir = s.dir;
inDir = s.inDir;
penSize = s.penSize;
ink = s.ink;
}
}
public TurtleState(TurtleState s) {
pos = s.pos;
dir = s.dir;
inDir = s.inDir;
penSize = s.penSize;
ink = s.ink;
}
}
private final Screen screen;
private final double width;
private final double height;
private final GraphicsContext context;
private final List<TurtleState> stateStack = new ArrayList<>();
private final Screen screen;
private final double width;
private final double height;
private final GraphicsContext context;
private final List<TurtleState> stateStack = new ArrayList<>();
private TurtleState state = new TurtleState();
private final Canvas canvas;
private boolean path = false;
private TurtleState state = new TurtleState();
private final Canvas canvas;
private boolean path = false;
public TurtlePainter(double width, double height) {
this.screen = null;
this.canvas = null;
this.context = null;
this.width = width;
this.height = height;
stateStack.add(new TurtleState());
state.dir = new Direction(1.0, 0.0);
state.pos = new Point(width / 2, height / 2);
}
public TurtlePainter(double width, double height) {
this.screen = null;
this.canvas = null;
this.context = null;
this.width = width;
this.height = height;
stateStack.add(new TurtleState());
state.dir = new Direction(1.0, 0.0);
state.pos = new Point(width / 2, height / 2);
}
public TurtlePainter(Screen screen, Canvas canvas) {
if (screen == null || canvas == null)
throw new IllegalArgumentException();
this.screen = screen;
this.canvas = canvas;
this.context = canvas.getGraphicsContext2D();
this.width = screen.getWidth();
this.height = screen.getHeight();
stateStack.add(new TurtleState());
state.dir = new Direction(1.0, 0.0);
state.pos = new Point(screen.getWidth() / 2, screen.getHeight() / 2);
context.setLineJoin(StrokeLineJoin.BEVEL);
context.setLineCap(StrokeLineCap.SQUARE);
}
public TurtlePainter(Screen screen, Canvas canvas) {
if (screen == null || canvas == null) {
throw new IllegalArgumentException();
}
this.screen = screen;
this.canvas = canvas;
this.context = canvas.getGraphicsContext2D();
this.width = screen.getWidth();
this.height = screen.getHeight();
stateStack.add(new TurtleState());
state.dir = new Direction(1.0, 0.0);
state.pos = new Point(screen.getWidth() / 2, screen.getHeight() / 2);
context.setLineJoin(StrokeLineJoin.BEVEL);
context.setLineCap(StrokeLineCap.SQUARE);
}
@Override
@SuppressWarnings("unchecked")
public <T> T as(Class<T> clazz) {
if (clazz == GraphicsContext.class)
return (T) context;
if (clazz == getClass())
return (T) this;
else
return null;
}
@Override
@SuppressWarnings("unchecked")
public <T> T as(Class<T> clazz) {
if (clazz == GraphicsContext.class) {
return (T) context;
}
if (clazz == getClass()) {
return (T) this;
} else {
return null;
}
}
@Override
public void clear() {
if (context != null)
context.clearRect(0, 0, getWidth(), getHeight());
}
@Override
public void clear() {
if (context != null) {
context.clearRect(0, 0, getWidth(), getHeight());
}
}
@Override
public ITurtle curveTo(Point to, double startControl, double endAngle, double endControl) {
Point c1 = state.pos.move(state.dir, startControl);
Point c2 = to.move(Direction.fromDegrees(endAngle + 180), endControl);
if (context != null) {
if (!path) {
// context.save();
context.setStroke(state.ink);
context.setLineWidth(state.penSize);
context.beginPath();
context.moveTo(state.pos.getX(), state.pos.getY());
}
context.bezierCurveTo(c1.getX(), c1.getY(), c2.getX(), c2.getY(), to.getX(), to.getY());
}
state.inDir = state.dir;
state.pos = to;
state.dir = Direction.fromDegrees(endAngle);
@Override
public ITurtle curveTo(Point to, double startControl, double endAngle, double endControl) {
Point c1 = state.pos.move(state.dir, startControl);
Point c2 = to.move(Direction.fromDegrees(endAngle + 180), endControl);
if (context != null) {
if (!path) {
// context.save();
context.setStroke(state.ink);
context.setLineWidth(state.penSize);
context.beginPath();
context.moveTo(state.pos.getX(), state.pos.getY());
}
context.bezierCurveTo(c1.getX(), c1.getY(), c2.getX(), c2.getY(), to.getX(), to.getY());
}
state.inDir = state.dir;
state.pos = to;
state.dir = Direction.fromDegrees(endAngle);
if (!path && context != null) {
context.stroke();
// context.restore();
}
return this;
}
if (!path && context != null) {
context.stroke();
// context.restore();
}
return this;
}
@Override
public void debugTurtle() {
System.err.println("[" + state.pos + " " + state.dir + "]");
}
@Override
public void debugTurtle() {
System.err.println("[" + state.pos + " " + state.dir + "]");
}
@Override
public ITurtle draw(double dist) {
Point to = state.pos.move(state.dir, dist);
return drawTo(to);
}
@Override
public ITurtle draw(double dist) {
Point to = state.pos.move(state.dir, dist);
return drawTo(to);
}
@Override
public ITurtle draw(Point relPos) {
Point to = state.pos.move(relPos);
return drawTo(to);
}
@Override
public ITurtle draw(Point relPos) {
Point to = state.pos.move(relPos);
return drawTo(to);
}
@Override
public ITurtle drawTo(double x, double y) {
Point to = new Point(x, y);
return drawTo(to);
}
@Override
public ITurtle drawTo(double x, double y) {
Point to = new Point(x, y);
return drawTo(to);
}
@Override
public ITurtle drawTo(Point to) {
if (path && context != null) {
context.setStroke(state.ink);
context.setLineWidth(state.penSize);
context.lineTo(to.getX(), to.getY());
} else {
line(to);
}
state.inDir = state.dir;
state.pos = to;
return this;
}
@Override
public ITurtle drawTo(Point to) {
if (path && context != null) {
context.setStroke(state.ink);
context.setLineWidth(state.penSize);
context.lineTo(to.getX(), to.getY());
} else {
line(to);
}
state.inDir = state.dir;
state.pos = to;
return this;
}
@Override
public double getAngle() {
return state.dir.toDegrees();
}
@Override
public double getAngle() {
return state.dir.toDegrees();
}
@Override
public Direction getDirection() {
return state.dir;
}
@Override
public Direction getDirection() {
return state.dir;
}
@Override
public double getHeight() {
return height;
}
@Override
public double getHeight() {
return height;
}
@Override
public Point getPos() {
return state.pos;
}
@Override
public Point getPos() {
return state.pos;
}
public Screen getScreen() {
return screen;
}
public Screen getScreen() {
return screen;
}
@Override
public double getWidth() {
return width;
}
@Override
public double getWidth() {
return width;
}
@Override
public ITurtle jump(double dist) {
state.inDir = state.dir;
state.pos = state.pos.move(state.dir, dist);
if (path && context != null)
context.moveTo(state.pos.getX(), state.pos.getY());
return this;
}
@Override
public ITurtle jump(double dist) {
state.inDir = state.dir;
state.pos = state.pos.move(state.dir, dist);
if (path && context != null) {
context.moveTo(state.pos.getX(), state.pos.getY());
}
return this;
}
@Override
public ITurtle jump(Point relPos) {
// TODO: state.inDir = state.dir;
state.pos = state.pos.move(relPos);
if (path && context != null)
context.moveTo(state.pos.getX(), state.pos.getY());
@Override
public ITurtle jump(Point relPos) {
// TODO: state.inDir = state.dir;
state.pos = state.pos.move(relPos);
if (path && context != null) {
context.moveTo(state.pos.getX(), state.pos.getY());
}
return this;
}
return this;
}
@Override
public ITurtle jumpTo(double x, double y) {
state.inDir = state.dir;
state.pos = new Point(x, y);
return this;
}
@Override
public ITurtle jumpTo(double x, double y) {
state.inDir = state.dir;
state.pos = new Point(x, y);
return this;
}
@Override
public ITurtle jumpTo(Point to) {
state.inDir = state.dir;
state.pos = to;
return this;
}
@Override
public ITurtle jumpTo(Point to) {
state.inDir = state.dir;
state.pos = to;
return this;
}
@Override
public void layerToBack() {
if (screen != null)
screen.moveToBack(this);
}
@Override
public void layerToBack() {
if (screen != null) {
screen.moveToBack(this);
}
}
@Override
public void layerToFront() {
if (screen != null)
screen.moveToFront(this);
}
@Override
public void layerToFront() {
if (screen != null) {
screen.moveToFront(this);
}
}
@Override
public ITurtle line(Point to) {
if (context != null) {
// context.save();
context.setStroke(state.ink);
context.setLineWidth(state.penSize);
context.strokeLine(state.pos.getX(), state.pos.getY(), to.getX(), to.getY());
// context.restore();
}
return this;
}
@Override
public ITurtle line(Point to) {
if (context != null) {
// context.save();
context.setStroke(state.ink);
context.setLineWidth(state.penSize);
context.strokeLine(state.pos.getX(), state.pos.getY(), to.getX(), to.getY());
// context.restore();
}
return this;
}
@Override
public IPainter restore() {
if (stateStack.size() > 0) {
state = stateStack.remove(stateStack.size() - 1);
}
return this;
}
@Override
public IPainter restore() {
if (stateStack.size() > 0) {
state = stateStack.remove(stateStack.size() - 1);
}
return this;
}
@Override
public IPainter save() {
stateStack.add(new TurtleState(state));
return this;
}
@Override
public IPainter save() {
stateStack.add(new TurtleState(state));
return this;
}
@Override
public IPainter setInk(Paint ink) {
state.ink = ink;
return this;
}
@Override
public IPainter setInk(Paint ink) {
state.ink = ink;
return this;
}
@Override
public ITurtle setPenSize(double pixels) {
if (pixels < 0)
throw new IllegalArgumentException("Negative: " + pixels);
state.penSize = pixels;
return this;
}
@Override
public ITurtle setPenSize(double pixels) {
if (pixels < 0) {
throw new IllegalArgumentException("Negative: " + pixels);
}
state.penSize = pixels;
return this;
}
@Override
public IShape shape() {
ShapePainter s = new ShapePainter(context);
return s.at(getPos()).rotation(getAngle()).strokePaint(state.ink);
}
@Override
public IShape shape() {
ShapePainter s = new ShapePainter(context);
return s.at(getPos()).rotation(getAngle()).strokePaint(state.ink);
}
@Override
public ITurtle turn(double degrees) {
state.dir = state.dir.turn(degrees);
return this;
}
@Override
public ITurtle turn(double degrees) {
state.dir = state.dir.turn(degrees);
return this;
}
@Override
public ITurtle turnAround() {
return turn(180);
}
@Override
public ITurtle turnAround() {
return turn(180);
}
@Override
public ITurtle turnLeft() {
return turn(90);
}
@Override
public ITurtle turnLeft() {
return turn(90);
}
@Override
public ITurtle turnLeft(double degrees) {
if (degrees < 0)
throw new IllegalArgumentException("Negative: " + degrees + " (use turn())");
state.dir = state.dir.turn(degrees);
return this;
}
@Override
public ITurtle turnLeft(double degrees) {
if (degrees < 0) {
throw new IllegalArgumentException("Negative: " + degrees + " (use turn())");
}
state.dir = state.dir.turn(degrees);
return this;
}
@Override
public ITurtle turnRight() {
return turn(-90);
}
@Override
public ITurtle turnRight() {
return turn(-90);
}
@Override
public ITurtle turnRight(double degrees) {
if (degrees < 0)
throw new IllegalArgumentException("Negative: " + degrees + " (use turn())");
state.dir = state.dir.turn(-degrees);
return this;
}
@Override
public ITurtle turnRight(double degrees) {
if (degrees < 0) {
throw new IllegalArgumentException("Negative: " + degrees + " (use turn())");
}
state.dir = state.dir.turn(-degrees);
return this;
}
@Override
public ITurtle turnTo(double degrees) {
state.dir = state.dir.turnTo(degrees);
return this;
}
@Override
public ITurtle turnTo(double degrees) {
state.dir = state.dir.turnTo(degrees);
return this;
}
@Override
public ITurtle turnTowards(double degrees, double percent) {
state.dir = state.dir.turnTowards(new Direction(degrees), percent);
return this;
}
@Override
public ITurtle turnTowards(double degrees, double percent) {
state.dir = state.dir.turnTowards(new Direction(degrees), percent);
return this;
}
@Override
public ITurtle turtle() {
TurtlePainter painter = screen != null ? new TurtlePainter(screen, canvas) : new TurtlePainter(width, height);
painter.stateStack.set(0, new TurtleState(state));
return painter;
}
@Override
public ITurtle turtle() {
TurtlePainter painter = screen != null ? new TurtlePainter(screen, canvas) : new TurtlePainter(width, height);
painter.stateStack.set(0, new TurtleState(state));
return painter;
}
public ITurtle beginPath() {
if (path)
throw new IllegalStateException("beginPath() after beginPath()");
path = true;
if (context != null) {
context.setStroke(state.ink);
context.beginPath();
context.moveTo(state.pos.getX(), state.pos.getY());
}
return this;
}
public ITurtle beginPath() {
if (path) {
throw new IllegalStateException("beginPath() after beginPath()");
}
path = true;
if (context != null) {
context.setStroke(state.ink);
context.beginPath();
context.moveTo(state.pos.getX(), state.pos.getY());
}
return this;
}
public ITurtle closePath() {
if (!path)
throw new IllegalStateException("closePath() without beginPath()");
if (context != null)
context.closePath();
return this;
}
public ITurtle closePath() {
if (!path) {
throw new IllegalStateException("closePath() without beginPath()");
}
if (context != null) {
context.closePath();
}
return this;
}
public ITurtle endPath() {
if (!path)
throw new IllegalStateException("endPath() without beginPath()");
path = false;
if (context != null)
context.stroke();
return this;
}
public ITurtle endPath() {
if (!path) {
throw new IllegalStateException("endPath() without beginPath()");
}
path = false;
if (context != null) {
context.stroke();
}
return this;
}
public ITurtle fillPath() {
if (!path)
throw new IllegalStateException("fillPath() without beginPath()");
path = false;
if (context != null) {
context.save();
context.setFill(state.ink);
context.fill();
context.restore();
}
return this;
}
public ITurtle fillPath() {
if (!path) {
throw new IllegalStateException("fillPath() without beginPath()");
}
path = false;
if (context != null) {
context.save();
context.setFill(state.ink);
context.fill();
context.restore();
}
return this;
}
@Override
public Paint getInk() {
return state.ink;
}
@Override
public Paint getInk() {
return state.ink;
}
}

View File

@ -6,196 +6,200 @@ import java.util.List;
import java.util.function.BiFunction;
public class BlocksAndBoxes {
public enum PixelOrder implements Iterable<Integer> {
LEFT_TO_RIGHT(8, 4, 2, 1), RIGHT_TO_LEFT(4, 8, 1, 2), LEFT_TO_RIGHT_UPWARDS(2, 1, 8,
4), RIGHT_TO_LEFT_UPWARDS(1, 2, 4, 8);
public enum PixelOrder implements Iterable<Integer> {
LEFT_TO_RIGHT(8, 4, 2, 1), RIGHT_TO_LEFT(4, 8, 1, 2), LEFT_TO_RIGHT_UPWARDS(2, 1, 8,
4), RIGHT_TO_LEFT_UPWARDS(1, 2, 4, 8);
private List<Integer> order;
private List<Integer> order;
PixelOrder(int a, int b, int c, int d) {
order = Arrays.asList(a, b, c, d);
}
PixelOrder(int a, int b, int c, int d) {
order = Arrays.asList(a, b, c, d);
}
@Override
public Iterator<Integer> iterator() {
return order.iterator();
}
}
@Override
public Iterator<Integer> iterator() {
return order.iterator();
}
}
public static final String[] unicodeBlocks = { " ", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "" };
public static final String[] unicodeBlocks = {" ", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", ""};
public static final int[] unicodeBlocks_NumPixels = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 2 };
public static final String unicodeBlocksString = String.join("", unicodeBlocks);
public static final String BLOCK_EMPTY = " ";
public static final String BLOCK_BOTTOM_RIGHT = "";
public static final String BLOCK_BOTTOM_LEFT = "";
public static final String BLOCK_BOTTOM = "";
public static final String BLOCK_TOP_RIGHT = "";
public static final String BLOCK_RIGHT = "";
public static final String BLOCK_DIAG_FORWARD = "";
public static final String BLOCK_REVERSE_TOP_LEFT = "";
public static final String BLOCK_TOP_LEFT = "";
public static final String BLOCK_DIAG_BACKWARD = "";
public static final String BLOCK_LEFT = "";
public static final String BLOCK_REVERSE_TOP_RIGHT = "";
public static final String BLOCK_TOP = "";
public static final String BLOCK_REVERSE_BOTTOM_LEFT = "";
public static final String BLOCK_REVERSE_BOTTOM_RIGHT = "";
public static final String BLOCK_FULL = "";
public static final int[] unicodeBlocks_NumPixels = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 2};
public static final String unicodeBlocksString = String.join("", unicodeBlocks);
public static final String BLOCK_EMPTY = " ";
public static final String BLOCK_BOTTOM_RIGHT = "";
public static final String BLOCK_BOTTOM_LEFT = "";
public static final String BLOCK_BOTTOM = "";
public static final String BLOCK_TOP_RIGHT = "";
public static final String BLOCK_RIGHT = "";
public static final String BLOCK_DIAG_FORWARD = "";
public static final String BLOCK_REVERSE_TOP_LEFT = "";
public static final String BLOCK_TOP_LEFT = "";
public static final String BLOCK_DIAG_BACKWARD = "";
public static final String BLOCK_LEFT = "";
public static final String BLOCK_REVERSE_TOP_RIGHT = "";
public static final String BLOCK_TOP = "";
public static final String BLOCK_REVERSE_BOTTOM_LEFT = "";
public static final String BLOCK_REVERSE_BOTTOM_RIGHT = "";
public static final String BLOCK_FULL = "";
public static final String BLOCK_HALF = "";
public static final String BLOCK_HALF = "";
public static String blockAddOne(String s, PixelOrder order) {
int i = BlocksAndBoxes.unicodeBlocksString.indexOf(s);
if (i >= 0) {
for (int bit : order) {
if ((i & bit) == 0)
return unicodeBlocks[i | bit];
}
}
return s;
}
public static String blockAddOne(String s, PixelOrder order) {
int i = BlocksAndBoxes.unicodeBlocksString.indexOf(s);
if (i >= 0) {
for (int bit : order) {
if ((i & bit) == 0) {
return unicodeBlocks[i | bit];
}
}
}
return s;
}
/**
* Convert a string into a Unicode block graphics character.
*
* <p>
* The block characters corresponds to 2x2-pixel images, and can be used, e.g.,
* to draw a 80x44 pixel image on a 40x22 character text screen.
*
* <p>
* The blocks are specified by four-character strings of spaces and asterisks,
* with space indicating an open space and asterisk indicating a filled "pixel",
* with the pixels arranged in a left-to-right, top-to-bottom order:
*
* <pre>
* 01
* 23
* </pre>
*
* <p>
* So <code>"* **"</code> corresponds to the block character <code>""</code>,
* with this layout:
*
* <pre>
* *
* *
* </pre>
*
* <p>
* The special codes <code>"++++"</code> and <code>"+"</code> corresponds to the
* "grey" block <code>""</code>, and <code>"*"</code> corresponds to the
* "black" block <code>""</code>.
*
* @param s
* A four character string, indicating which block character to
* select.
* @return A Unicode block character
* @throws IllegalArgumentException
* if the string isn't of the expected form
*/
public static String blockChar(String s) {
switch (s.replaceAll("\n", s)) {
case " ":
return unicodeBlocks[0];
case " *":
return unicodeBlocks[1];
case " * ":
return unicodeBlocks[2];
case " **":
return unicodeBlocks[3];
case " * ":
return unicodeBlocks[4];
case " * *":
return unicodeBlocks[5];
case " ** ":
return unicodeBlocks[6];
case " ***":
return unicodeBlocks[7];
case "* ":
return unicodeBlocks[8];
case "* *":
return unicodeBlocks[9];
case "* * ":
return unicodeBlocks[10];
case "* **":
return unicodeBlocks[11];
case "** ":
return unicodeBlocks[12];
case "** *":
return unicodeBlocks[13];
case "*** ":
return unicodeBlocks[14];
case "****":
return unicodeBlocks[15];
case "++++":
return unicodeBlocks[16];
case ".":
return BLOCK_BOTTOM_LEFT;
case "_":
return BLOCK_BOTTOM;
case "/":
return BLOCK_DIAG_FORWARD;
case "\\":
return BLOCK_DIAG_BACKWARD;
case "|":
return BLOCK_LEFT;
case "#":
return BLOCK_FULL;
case "`":
return BLOCK_TOP_LEFT;
case "'":
return BLOCK_TOP_RIGHT;
}
throw new IllegalArgumentException(
"Expected length 4 string of \" \" and \"*\", or \"++++\", got \"" + s + "\"");
}
/**
* Convert a string into a Unicode block graphics character.
*
* <p>
* The block characters corresponds to 2x2-pixel images, and can be used, e.g.,
* to draw a 80x44 pixel image on a 40x22 character text screen.
*
* <p>
* The blocks are specified by four-character strings of spaces and asterisks,
* with space indicating an open space and asterisk indicating a filled "pixel",
* with the pixels arranged in a left-to-right, top-to-bottom order:
*
* <pre>
* 01
* 23
* </pre>
*
* <p>
* So <code>"* **"</code> corresponds to the block character <code>""</code>,
* with this layout:
*
* <pre>
* *
* *
* </pre>
*
* <p>
* The special codes <code>"++++"</code> and <code>"+"</code> corresponds to the
* "grey" block <code>""</code>, and <code>"*"</code> corresponds to the
* "black" block <code>""</code>.
*
* @param s A four character string, indicating which block character to
* select.
* @return A Unicode block character
* @throws IllegalArgumentException if the string isn't of the expected form
*/
public static String blockChar(String s) {
switch (s.replaceAll("\n", s)) {
case " ":
return unicodeBlocks[0];
case " *":
return unicodeBlocks[1];
case " * ":
return unicodeBlocks[2];
case " **":
return unicodeBlocks[3];
case " * ":
return unicodeBlocks[4];
case " * *":
return unicodeBlocks[5];
case " ** ":
return unicodeBlocks[6];
case " ***":
return unicodeBlocks[7];
case "* ":
return unicodeBlocks[8];
case "* *":
return unicodeBlocks[9];
case "* * ":
return unicodeBlocks[10];
case "* **":
return unicodeBlocks[11];
case "** ":
return unicodeBlocks[12];
case "** *":
return unicodeBlocks[13];
case "*** ":
return unicodeBlocks[14];
case "****":
return unicodeBlocks[15];
case "++++":
return unicodeBlocks[16];
case ".":
return BLOCK_BOTTOM_LEFT;
case "_":
return BLOCK_BOTTOM;
case "/":
return BLOCK_DIAG_FORWARD;
case "\\":
return BLOCK_DIAG_BACKWARD;
case "|":
return BLOCK_LEFT;
case "#":
return BLOCK_FULL;
case "`":
return BLOCK_TOP_LEFT;
case "'":
return BLOCK_TOP_RIGHT;
}
throw new IllegalArgumentException(
"Expected length 4 string of \" \" and \"*\", or \"++++\", got \"" + s + "\"");
}
public static String blockCompact(String s) {
int i = BlocksAndBoxes.unicodeBlocksString.indexOf(s);
if (i > 0) {
int lower = i & 3;
int upper = (i >> 2) & 3;
i = (lower | upper) | ((lower & upper) << 2);
// System.out.println("Compact: " + s + " -> " + BlocksAndBoxes.unicodeBlocks[i]
// + "\n");
return BlocksAndBoxes.unicodeBlocks[i];
}
return s;
}
public static String blockCompact(String s) {
int i = BlocksAndBoxes.unicodeBlocksString.indexOf(s);
if (i > 0) {
int lower = i & 3;
int upper = (i >> 2) & 3;
i = (lower | upper) | ((lower & upper) << 2);
// System.out.println("Compact: " + s + " -> " + BlocksAndBoxes.unicodeBlocks[i]
// + "\n");
return BlocksAndBoxes.unicodeBlocks[i];
}
return s;
}
public static String blockCompose(String b1, String b2, BiFunction<Integer, Integer, Integer> op) {
int i1 = unicodeBlocksString.indexOf(b1);
if (i1 < 0)
throw new IllegalArgumentException("Not a block character: " + b1);
int i2 = unicodeBlocksString.indexOf(b2);
if (i2 < 0)
throw new IllegalArgumentException("Not a block character: " + b1);
if (i1 == 16 || i2 == 16)
return b2;
else
return unicodeBlocks[op.apply(i1, i2)];
}
public static String blockCompose(String b1, String b2, BiFunction<Integer, Integer, Integer> op) {
int i1 = unicodeBlocksString.indexOf(b1);
if (i1 < 0) {
throw new IllegalArgumentException("Not a block character: " + b1);
}
int i2 = unicodeBlocksString.indexOf(b2);
if (i2 < 0) {
throw new IllegalArgumentException("Not a block character: " + b1);
}
if (i1 == 16 || i2 == 16) {
return b2;
} else {
return unicodeBlocks[op.apply(i1, i2)];
}
}
public static String blockComposeOrOverwrite(String b1, String b2, BiFunction<Integer, Integer, Integer> op) {
int i1 = unicodeBlocksString.indexOf(b1);
int i2 = unicodeBlocksString.indexOf(b2);
if (i1 < 0 || i2 < 0 || i1 == 16 || i2 == 16)
return b2;
else
return unicodeBlocks[op.apply(i1, i2)];
}
public static String blockComposeOrOverwrite(String b1, String b2, BiFunction<Integer, Integer, Integer> op) {
int i1 = unicodeBlocksString.indexOf(b1);
int i2 = unicodeBlocksString.indexOf(b2);
if (i1 < 0 || i2 < 0 || i1 == 16 || i2 == 16) {
return b2;
} else {
return unicodeBlocks[op.apply(i1, i2)];
}
}
public static String blockRemoveOne(String s, PixelOrder order) {
int i = BlocksAndBoxes.unicodeBlocksString.indexOf(s);
if (i >= 0) {
for (int bit : order) {
if ((i & bit) != 0)
return unicodeBlocks[i & ~bit];
}
}
return s;
}
public static String blockRemoveOne(String s, PixelOrder order) {
int i = BlocksAndBoxes.unicodeBlocksString.indexOf(s);
if (i >= 0) {
for (int bit : order) {
if ((i & bit) != 0) {
return unicodeBlocks[i & ~bit];
}
}
}
return s;
}
}

View File

@ -1,5 +1,7 @@
package inf101.v18.gfx.textmode;
import javafx.scene.paint.Color;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
@ -11,266 +13,271 @@ import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.scene.paint.Color;
public class ControlSequences {
private static final boolean DEBUG = false;
public static class CsiPattern {
public static CsiPattern compile0(String pat, String desc, Consumer<Printer> handler) {
CsiPattern csiPattern = new CsiPattern(pat, 0, 0, desc, handler, null, null);
patterns.put(csiPattern.getCommandLetter(), csiPattern);
return csiPattern;
}
private static final boolean DEBUG = false;
public static CsiPattern compile1(String pat, int defaultArg, String desc,
BiConsumer<Printer, Integer> handler) {
CsiPattern csiPattern = new CsiPattern(pat, defaultArg, 1, desc, null, handler, null);
patterns.put(csiPattern.getCommandLetter(), csiPattern);
return csiPattern;
}
public static class CsiPattern {
public static CsiPattern compile0(String pat, String desc, Consumer<Printer> handler) {
CsiPattern csiPattern = new CsiPattern(pat, 0, 0, desc, handler, null, null);
patterns.put(csiPattern.getCommandLetter(), csiPattern);
return csiPattern;
}
public static CsiPattern compileN(String pat, int defaultArg, int numArgs, String desc,
BiConsumer<Printer, List<Integer>> handler) {
CsiPattern csiPattern = new CsiPattern(pat, defaultArg, numArgs, desc, null, null, handler);
patterns.put(csiPattern.getCommandLetter(), csiPattern);
return csiPattern;
}
public static CsiPattern compile1(String pat, int defaultArg, String desc,
BiConsumer<Printer, Integer> handler) {
CsiPattern csiPattern = new CsiPattern(pat, defaultArg, 1, desc, null, handler, null);
patterns.put(csiPattern.getCommandLetter(), csiPattern);
return csiPattern;
}
private String patStr;
private Pattern pattern;
private int defaultArg = 0;
private String desc;
private Consumer<Printer> handler0;
public static CsiPattern compileN(String pat, int defaultArg, int numArgs, String desc,
BiConsumer<Printer, List<Integer>> handler) {
CsiPattern csiPattern = new CsiPattern(pat, defaultArg, numArgs, desc, null, null, handler);
patterns.put(csiPattern.getCommandLetter(), csiPattern);
return csiPattern;
}
private BiConsumer<Printer, Integer> handler1;
private String patStr;
private Pattern pattern;
private int defaultArg = 0;
private String desc;
private Consumer<Printer> handler0;
private BiConsumer<Printer, List<Integer>> handlerN;
private BiConsumer<Printer, Integer> handler1;
private int numArgs;
private BiConsumer<Printer, List<Integer>> handlerN;
public CsiPattern(String pat, int defaultArg, int numArgs, String desc, Consumer<Printer> handler0,
BiConsumer<Printer, Integer> handler1, BiConsumer<Printer, List<Integer>> handlerN) {
this.patStr = pat;
this.pattern = Pattern.compile(pat);
this.defaultArg = defaultArg;
this.numArgs = numArgs;
this.desc = desc;
this.handler0 = handler0;
this.handler1 = handler1;
this.handlerN = handlerN;
}
private int numArgs;
public String getCommandLetter() {
return patStr.substring(patStr.length() - 1);
}
public CsiPattern(String pat, int defaultArg, int numArgs, String desc, Consumer<Printer> handler0,
BiConsumer<Printer, Integer> handler1, BiConsumer<Printer, List<Integer>> handlerN) {
this.patStr = pat;
this.pattern = Pattern.compile(pat);
this.defaultArg = defaultArg;
this.numArgs = numArgs;
this.desc = desc;
this.handler0 = handler0;
this.handler1 = handler1;
this.handlerN = handlerN;
}
public String getDescription() {
return desc;
}
public String getCommandLetter() {
return patStr.substring(patStr.length() - 1);
}
public boolean match(Printer printer, String input) {
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
String argStr = matcher.groupCount() > 0 ? matcher.group(1) : "";
String[] args = argStr.split(";");
if (handler0 != null) {
if(DEBUG)
System.out.println("Handling " + getDescription() + ".");
handler0.accept(printer);
} else if (handler1 != null) {
int arg = args.length > 0 && !args[0].equals("") ? Integer.valueOf(args[0]) : defaultArg;
if(DEBUG)
System.out.println("Handling " + getDescription() + ": " + arg);
handler1.accept(printer, arg);
} else if (handlerN != null) {
List<Integer> argList = new ArrayList<>();
for (String s : args) {
if (s.equals(""))
argList.add(defaultArg);
else
argList.add(Integer.valueOf(s));
}
while (argList.size() < numArgs) {
argList.add(defaultArg);
}
if(DEBUG)
System.out.println("Handling " + getDescription() + ": " + argList);
handlerN.accept(printer, argList);
}
return true;
}
return false;
}
}
public String getDescription() {
return desc;
}
public static final Map<String, CsiPattern> patterns = new HashMap<>();
public static final CsiPattern CUU = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)A", 1, "cursor up",
(Printer p, Integer i) -> {
p.move(0, -i);
});
public static final CsiPattern CUD = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)B", 1, "cursor down",
(Printer p, Integer i) -> {
p.move(0, i);
});
public static final CsiPattern CUF = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)C", 1, "cursor forward",
(Printer p, Integer i) -> {
p.move(i, 0);
});
public static final CsiPattern CUB = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)D", 1, "cursor back",
(Printer p, Integer i) -> {
p.move(-i, 0);
});
public static final CsiPattern CNL = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)E", 1, "cursor next line",
(Printer p, Integer i) -> {
p.move(0, i);
p.beginningOfLine();
});
public static final CsiPattern CPL = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)F", 1, "cursor previous line",
(Printer p, Integer i) -> {
p.move(0, -i);
p.beginningOfLine();
});
public static final CsiPattern CHA = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)G", 1,
"cursor horizontal absolute", (Printer p, Integer i) -> {
p.moveTo(i, p.getY());
});
public static final CsiPattern CUP = CsiPattern.compileN("\u001b\\\u005b([0-9;]*)H", 1, 2, "cursor position",
(Printer p, List<Integer> i) -> {
p.moveTo(i.get(1), i.get(0));
});
public static final CsiPattern ED = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)J", 0, "erase in display",
(Printer p, Integer i) -> {
if (i == 2 || i == 3)
p.clear();
else
System.err.println("Unimplemented: ED");
});
public static final CsiPattern EK = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)K", 0, "erase in line",
(Printer p, Integer i) -> {
System.err.println("Unimplemented: EK");
});
public static final CsiPattern SU = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)S", 1, "scroll up",
(Printer p, Integer i) -> {
p.scroll(i);
});
public static final CsiPattern SD = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)T", 1, "scroll down",
(Printer p, Integer i) -> {
p.scroll(-i);
});
public static final CsiPattern HVP = CsiPattern.compileN("\u001b\\\u005b([0-9;]*)f", 1, 2,
"horizontal vertical position", (Printer p, List<Integer> l) -> {
p.moveTo(l.get(1), l.get(0));
});
public static final CsiPattern AUX_ON = CsiPattern.compile0("\u001b\\\u005b5i", "aux port on", (Printer p) -> {
System.err.println("Unimplemented: AUX on");
});
public static final CsiPattern AUX_OFF = CsiPattern.compile0("\u001b\\\u005b4i", "aux port off", (Printer p) -> {
System.err.println("Unimplemented: AUX off");
});
public static final CsiPattern DSR = CsiPattern.compile0("\u001b\\\u005b6n", "device status report",
(Printer p) -> {
System.out.println("ESC[" + p.getY() + ";" + p.getX() + "R");
});
public static final CsiPattern SCP = CsiPattern.compile0("\u001b\\\u005bs", "save cursor position", (Printer p) -> {
p.saveCursor();
});
public static final CsiPattern RCP = CsiPattern.compile0("\u001b\\\u005bu", "restore cursor position",
(Printer p) -> {
p.restoreCursor();
});
public static final int F = 0xFF, H = 0xAA, L = 0x55, OFF = 0x00;
public static final Color[] PALETTE_CGA = { //
Color.rgb(0, 0, 0), Color.rgb(0, 0, H), Color.rgb(0, H, 0), Color.rgb(0, H, H), //
Color.rgb(H, 0, 0), Color.rgb(H, 0, H), Color.rgb(H, L, 0), Color.rgb(H, H, H), //
Color.rgb(L, L, L), Color.rgb(L, L, F), Color.rgb(L, F, L), Color.rgb(L, F, F), //
Color.rgb(F, L, L), Color.rgb(F, L, F), Color.rgb(F, F, L), Color.rgb(F, F, F), };
public static final Color[] PALETTE_VGA = { //
Color.rgb(0, 0, 0), Color.rgb(H, 0, 0), Color.rgb(0, H, 0), Color.rgb(H, H, 0), //
Color.rgb(0, 0, H), Color.rgb(H, 0, H), Color.rgb(0, H, H), Color.rgb(H, H, H), //
Color.rgb(L, L, L), Color.rgb(F, L, L), Color.rgb(L, F, L), Color.rgb(F, F, L), //
Color.rgb(L, L, F), Color.rgb(F, L, F), Color.rgb(L, F, F), Color.rgb(F, F, F), };
public boolean match(Printer printer, String input) {
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
String argStr = matcher.groupCount() > 0 ? matcher.group(1) : "";
String[] args = argStr.split(";");
if (handler0 != null) {
if (DEBUG) {
System.out.println("Handling " + getDescription() + ".");
}
handler0.accept(printer);
} else if (handler1 != null) {
int arg = args.length > 0 && !args[0].equals("") ? Integer.valueOf(args[0]) : defaultArg;
if (DEBUG) {
System.out.println("Handling " + getDescription() + ": " + arg);
}
handler1.accept(printer, arg);
} else if (handlerN != null) {
List<Integer> argList = new ArrayList<>();
for (String s : args) {
if (s.equals("")) {
argList.add(defaultArg);
} else {
argList.add(Integer.valueOf(s));
}
}
while (argList.size() < numArgs) {
argList.add(defaultArg);
}
if (DEBUG) {
System.out.println("Handling " + getDescription() + ": " + argList);
}
handlerN.accept(printer, argList);
}
return true;
}
return false;
}
}
public static final CsiPattern SGR = CsiPattern.compileN("\u001b\\\u005b([0-9;]*)m", 0, -1,
"select graphics rendition", (Printer p, List<Integer> l) -> {
if (l.size() == 0) {
l.add(0);
}
int[] attrs = { 0, TextFont.ATTR_BRIGHT, TextFont.ATTR_FAINT, TextFont.ATTR_ITALIC,
TextFont.ATTR_UNDERLINE, TextFont.ATTR_BLINK, TextFont.ATTR_BLINK, TextFont.ATTR_INVERSE, 0,
TextFont.ATTR_LINE_THROUGH };
public static final Map<String, CsiPattern> patterns = new HashMap<>();
public static final CsiPattern CUU = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)A", 1, "cursor up",
(Printer p, Integer i) -> {
p.move(0, -i);
});
public static final CsiPattern CUD = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)B", 1, "cursor down",
(Printer p, Integer i) -> {
p.move(0, i);
});
public static final CsiPattern CUF = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)C", 1, "cursor forward",
(Printer p, Integer i) -> {
p.move(i, 0);
});
public static final CsiPattern CUB = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)D", 1, "cursor back",
(Printer p, Integer i) -> {
p.move(-i, 0);
});
public static final CsiPattern CNL = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)E", 1, "cursor next line",
(Printer p, Integer i) -> {
p.move(0, i);
p.beginningOfLine();
});
public static final CsiPattern CPL = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)F", 1, "cursor previous line",
(Printer p, Integer i) -> {
p.move(0, -i);
p.beginningOfLine();
});
public static final CsiPattern CHA = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)G", 1,
"cursor horizontal absolute", (Printer p, Integer i) -> {
p.moveTo(i, p.getY());
});
public static final CsiPattern CUP = CsiPattern.compileN("\u001b\\\u005b([0-9;]*)H", 1, 2, "cursor position",
(Printer p, List<Integer> i) -> {
p.moveTo(i.get(1), i.get(0));
});
public static final CsiPattern ED = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)J", 0, "erase in display",
(Printer p, Integer i) -> {
if (i == 2 || i == 3) {
p.clear();
} else {
System.err.println("Unimplemented: ED");
}
});
public static final CsiPattern EK = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)K", 0, "erase in line",
(Printer p, Integer i) -> {
System.err.println("Unimplemented: EK");
});
public static final CsiPattern SU = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)S", 1, "scroll up",
(Printer p, Integer i) -> {
p.scroll(i);
});
public static final CsiPattern SD = CsiPattern.compile1("\u001b\\\u005b([0-9;]*)T", 1, "scroll down",
(Printer p, Integer i) -> {
p.scroll(-i);
});
public static final CsiPattern HVP = CsiPattern.compileN("\u001b\\\u005b([0-9;]*)f", 1, 2,
"horizontal vertical position", (Printer p, List<Integer> l) -> {
p.moveTo(l.get(1), l.get(0));
});
public static final CsiPattern AUX_ON = CsiPattern.compile0("\u001b\\\u005b5i", "aux port on", (Printer p) -> {
System.err.println("Unimplemented: AUX on");
});
public static final CsiPattern AUX_OFF = CsiPattern.compile0("\u001b\\\u005b4i", "aux port off", (Printer p) -> {
System.err.println("Unimplemented: AUX off");
});
public static final CsiPattern DSR = CsiPattern.compile0("\u001b\\\u005b6n", "device status report",
(Printer p) -> {
System.out.println("ESC[" + p.getY() + ";" + p.getX() + "R");
});
public static final CsiPattern SCP = CsiPattern.compile0("\u001b\\\u005bs", "save cursor position", (Printer p) -> {
p.saveCursor();
});
public static final CsiPattern RCP = CsiPattern.compile0("\u001b\\\u005bu", "restore cursor position",
(Printer p) -> {
p.restoreCursor();
});
public static final int F = 0xFF, H = 0xAA, L = 0x55, OFF = 0x00;
public static final Color[] PALETTE_CGA = { //
Color.rgb(0, 0, 0), Color.rgb(0, 0, H), Color.rgb(0, H, 0), Color.rgb(0, H, H), //
Color.rgb(H, 0, 0), Color.rgb(H, 0, H), Color.rgb(H, L, 0), Color.rgb(H, H, H), //
Color.rgb(L, L, L), Color.rgb(L, L, F), Color.rgb(L, F, L), Color.rgb(L, F, F), //
Color.rgb(F, L, L), Color.rgb(F, L, F), Color.rgb(F, F, L), Color.rgb(F, F, F),};
public static final Color[] PALETTE_VGA = { //
Color.rgb(0, 0, 0), Color.rgb(H, 0, 0), Color.rgb(0, H, 0), Color.rgb(H, H, 0), //
Color.rgb(0, 0, H), Color.rgb(H, 0, H), Color.rgb(0, H, H), Color.rgb(H, H, H), //
Color.rgb(L, L, L), Color.rgb(F, L, L), Color.rgb(L, F, L), Color.rgb(F, F, L), //
Color.rgb(L, L, F), Color.rgb(F, L, F), Color.rgb(L, F, F), Color.rgb(F, F, F),};
Iterator<Integer> it = l.iterator();
while (it.hasNext()) {
int i = it.next();
if (i == 0) {
p.setVideoAttrs(0);
p.setInk(PALETTE_VGA[7]);
p.setBackground(PALETTE_VGA[0]);
} else if (i < 10) {
p.setVideoAttrEnabled(attrs[i]);
} else if (i >= 20 && i < 30) {
p.setVideoAttrDisabled(attrs[i] - 20);
} else if (i >= 30 && i < 38) {
p.setInk(PALETTE_VGA[i - 30]);
} else if (i == 38) {
p.setInk(decode256(it));
} else if (i == 29) {
p.setInk(Color.WHITE);
} else if (i >= 40 && i < 48) {
p.setBackground(PALETTE_VGA[i - 40]);
} else if (i == 48) {
p.setInk(decode256(it));
} else if (i == 49) {
p.setBackground(Color.BLACK);
} else if (i >= 90 && i < 98) {
p.setInk(PALETTE_VGA[8 + i - 90]);
} else if (i >= 100 && i < 108) {
p.setBackground(PALETTE_VGA[8 + i - 100]);
} else if (i == 53) {
p.setVideoAttrEnabled(TextFont.ATTR_OVERLINE);
} else if (i == 55) {
p.setVideoAttrEnabled(TextFont.ATTR_OVERLINE);
}
}
});
public static final CsiPattern SGR = CsiPattern.compileN("\u001b\\\u005b([0-9;]*)m", 0, -1,
"select graphics rendition", (Printer p, List<Integer> l) -> {
if (l.size() == 0) {
l.add(0);
}
int[] attrs = {0, TextFont.ATTR_BRIGHT, TextFont.ATTR_FAINT, TextFont.ATTR_ITALIC,
TextFont.ATTR_UNDERLINE, TextFont.ATTR_BLINK, TextFont.ATTR_BLINK, TextFont.ATTR_INVERSE, 0,
TextFont.ATTR_LINE_THROUGH};
public static boolean applyCsi(Printer printer, String csi) {
CsiPattern csiPattern = patterns.get(csi.substring(csi.length() - 1));
// System.out.println("Applying CSI: " + csi.replaceAll("\u001b", "ESC"));
Iterator<Integer> it = l.iterator();
while (it.hasNext()) {
int i = it.next();
if (i == 0) {
p.setVideoAttrs(0);
p.setInk(PALETTE_VGA[7]);
p.setBackground(PALETTE_VGA[0]);
} else if (i < 10) {
p.setVideoAttrEnabled(attrs[i]);
} else if (i >= 20 && i < 30) {
p.setVideoAttrDisabled(attrs[i] - 20);
} else if (i >= 30 && i < 38) {
p.setInk(PALETTE_VGA[i - 30]);
} else if (i == 38) {
p.setInk(decode256(it));
} else if (i == 29) {
p.setInk(Color.WHITE);
} else if (i >= 40 && i < 48) {
p.setBackground(PALETTE_VGA[i - 40]);
} else if (i == 48) {
p.setInk(decode256(it));
} else if (i == 49) {
p.setBackground(Color.BLACK);
} else if (i >= 90 && i < 98) {
p.setInk(PALETTE_VGA[8 + i - 90]);
} else if (i >= 100 && i < 108) {
p.setBackground(PALETTE_VGA[8 + i - 100]);
} else if (i == 53) {
p.setVideoAttrEnabled(TextFont.ATTR_OVERLINE);
} else if (i == 55) {
p.setVideoAttrEnabled(TextFont.ATTR_OVERLINE);
}
}
});
if (csiPattern != null) {
if (csiPattern.match(printer, csi))
return true;
else
System.err.println("Handler failed for escape sequence: " + csi.replaceAll("\u001b", "ESC"));
public static boolean applyCsi(Printer printer, String csi) {
CsiPattern csiPattern = patterns.get(csi.substring(csi.length() - 1));
// System.out.println("Applying CSI: " + csi.replaceAll("\u001b", "ESC"));
} else {
System.err.println("No handler for escape sequence: " + csi.replaceAll("\u001b", "ESC"));
}
return false;
}
if (csiPattern != null) {
if (csiPattern.match(printer, csi)) {
return true;
} else {
System.err.println("Handler failed for escape sequence: " + csi.replaceAll("\u001b", "ESC"));
}
private static Color decode256(Iterator<Integer> it) {
int i;
try {
i = it.next();
if (i == 5) {
i = it.next();
if (i < 16)
return PALETTE_VGA[i];
else if (i < 232)
return Color.rgb(i / 36, (i / 6) % 6, i % 6);
else
return Color.gray((i - 232) / 23.0);
} else if (i == 2) {
int r = it.next();
int g = it.next();
int b = it.next();
return Color.rgb(r, g, b);
}
} catch (NoSuchElementException e) {
}
return null;
}
} else {
System.err.println("No handler for escape sequence: " + csi.replaceAll("\u001b", "ESC"));
}
return false;
}
private static Color decode256(Iterator<Integer> it) {
int i;
try {
i = it.next();
if (i == 5) {
i = it.next();
if (i < 16) {
return PALETTE_VGA[i];
} else if (i < 232) {
return Color.rgb(i / 36, (i / 6) % 6, i % 6);
} else {
return Color.gray((i - 232) / 23.0);
}
} else if (i == 2) {
int r = it.next();
int g = it.next();
int b = it.next();
return Color.rgb(r, g, b);
}
} catch (NoSuchElementException e) {
}
return null;
}
}

View File

@ -1,153 +1,161 @@
package inf101.v18.gfx.textmode;
import javafx.scene.paint.Color;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javafx.scene.paint.Color;
public class DemoPages {
public static void printAnsiArt(Printer printer) {
printer.moveTo(1, 1);
printer.setAutoScroll(false);
printer.clear();
public static void printAnsiArt(Printer printer) {
printer.moveTo(1, 1);
printer.setAutoScroll(false);
printer.clear();
try (InputStream stream = DemoPages.class.getResourceAsStream("flower.txt")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
printer.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
try (InputStream stream = DemoPages.class.getResourceAsStream("flower.txt")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
printer.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void printBlockPlotting(Printer printer) {
printer.clear();
printer.setAutoScroll(false);
printer.setVideoAttrs(0);
int topLine = 8;
for (int x = 0; x < 16; x += 1) {
if ((x & 1) > 0)
printer.plot(4 * x + 1, 1 + (topLine - 1) * 2);
if ((x & 2) > 0)
printer.plot(4 * x, 1 + (topLine - 1) * 2);
if ((x & 4) > 0)
printer.plot(4 * x + 1, (topLine - 1) * 2);
if ((x & 8) > 0)
printer.plot(4 * x, (topLine - 1) * 2);
printer.printAt(1 + 2 * x, topLine + 2, BlocksAndBoxes.unicodeBlocks[x]);
printer.printAt(1 + 2 * x, topLine + 4, BlocksAndBoxes.unicodeBlocks[15]);
printer.printAt(1 + 2 * x, topLine + 6, BlocksAndBoxes.unicodeBlocks[~x & +0xf]);
printer.printAt(1 + 2 * x, topLine + 7, String.format("%X", x));
if ((x & 1) > 0)
printer.unplot(4 * x + 1, 1 + (4 + topLine - 1) * 2);
if ((x & 2) > 0)
printer.unplot(4 * x, 1 + (4 + topLine - 1) * 2);
if ((x & 4) > 0)
printer.unplot(4 * x + 1, (4 + topLine - 1) * 2);
if ((x & 8) > 0)
printer.unplot(4 * x, (4 + topLine - 1) * 2);
}
printer.printAt(1, 1,
"Plotting with Unicode Block Elements\n(ZX81-like Graphics)\n\nThe plot/print and unplot/inverse\nlines should be equal:");
printer.printAt(33, topLine, "plot");
printer.printAt(33, topLine + 2, "print");
printer.printAt(33, topLine + 4, "unplot");
printer.printAt(33, topLine + 6, "inverse");
printer.printAt(0, topLine + 9, String.format("Full blocks:\n Clear[%s] Shaded[%s] Opaque[%s]",
BlocksAndBoxes.unicodeBlocks[0], BlocksAndBoxes.unicodeBlocks[16], BlocksAndBoxes.unicodeBlocks[15]));
printer.printAt(41, topLine + 9, "(ZX81 inverted shade and half block");
printer.printAt(41, topLine + 10, "shades are missing in Unicode and");
printer.printAt(41, topLine + 11, "therefore not supported)");
printer.println();
}
public static void printBlockPlotting(Printer printer) {
printer.clear();
printer.setAutoScroll(false);
printer.setVideoAttrs(0);
int topLine = 8;
for (int x = 0; x < 16; x += 1) {
if ((x & 1) > 0) {
printer.plot(4 * x + 1, 1 + (topLine - 1) * 2);
}
if ((x & 2) > 0) {
printer.plot(4 * x, 1 + (topLine - 1) * 2);
}
if ((x & 4) > 0) {
printer.plot(4 * x + 1, (topLine - 1) * 2);
}
if ((x & 8) > 0) {
printer.plot(4 * x, (topLine - 1) * 2);
}
printer.printAt(1 + 2 * x, topLine + 2, BlocksAndBoxes.unicodeBlocks[x]);
printer.printAt(1 + 2 * x, topLine + 4, BlocksAndBoxes.unicodeBlocks[15]);
printer.printAt(1 + 2 * x, topLine + 6, BlocksAndBoxes.unicodeBlocks[~x & +0xf]);
printer.printAt(1 + 2 * x, topLine + 7, String.format("%X", x));
if ((x & 1) > 0) {
printer.unplot(4 * x + 1, 1 + (4 + topLine - 1) * 2);
}
if ((x & 2) > 0) {
printer.unplot(4 * x, 1 + (4 + topLine - 1) * 2);
}
if ((x & 4) > 0) {
printer.unplot(4 * x + 1, (4 + topLine - 1) * 2);
}
if ((x & 8) > 0) {
printer.unplot(4 * x, (4 + topLine - 1) * 2);
}
}
printer.printAt(1, 1,
"Plotting with Unicode Block Elements\n(ZX81-like Graphics)\n\nThe plot/print and unplot/inverse\nlines should be equal:");
printer.printAt(33, topLine, "plot");
printer.printAt(33, topLine + 2, "print");
printer.printAt(33, topLine + 4, "unplot");
printer.printAt(33, topLine + 6, "inverse");
printer.printAt(0, topLine + 9, String.format("Full blocks:\n Clear[%s] Shaded[%s] Opaque[%s]",
BlocksAndBoxes.unicodeBlocks[0], BlocksAndBoxes.unicodeBlocks[16], BlocksAndBoxes.unicodeBlocks[15]));
printer.printAt(41, topLine + 9, "(ZX81 inverted shade and half block");
printer.printAt(41, topLine + 10, "shades are missing in Unicode and");
printer.printAt(41, topLine + 11, "therefore not supported)");
printer.println();
}
public static void printBoxDrawing(Printer printer) {
printer.clear();
printer.setAutoScroll(false);
printer.println(" Latin-1 Boxes & Blocks");
printer.println(" U+0000..00FF U+2500..257F..259F");
printer.println(" ");
printer.println(" 0123456789ABCDEF 0123456789ABCDEF");
for (int y = 0; y < 16; y++) {
printer.print(String.format(" %X", y));
int c = y * 0x010;
for (int x = 0; x < 16; x++) {
printer.print(c >= 0x20 ? Character.toString((char) (c + x)) : " ");
}
printer.print(" ");
public static void printBoxDrawing(Printer printer) {
printer.clear();
printer.setAutoScroll(false);
printer.println(" Latin-1 Boxes & Blocks");
printer.println(" U+0000..00FF U+2500..257F..259F");
printer.println(" ");
printer.println(" 0123456789ABCDEF 0123456789ABCDEF");
for (int y = 0; y < 16; y++) {
printer.print(String.format(" %X", y));
int c = y * 0x010;
for (int x = 0; x < 16; x++) {
printer.print(c >= 0x20 ? Character.toString((char) (c + x)) : " ");
}
printer.print(" ");
if (y < 10) {
printer.print(String.format("%X", y));
c = 0x2500 + y * 0x010;
for (int x = 0; x < 16; x++) {
printer.print(Character.toString((char) (c + x)));
}
}
printer.println();
}
}
if (y < 10) {
printer.print(String.format("%X", y));
c = 0x2500 + y * 0x010;
for (int x = 0; x < 16; x++) {
printer.print(Character.toString((char) (c + x)));
}
}
printer.println();
}
}
public static void printVideoAttributes(Printer printer) {
printer.clear();
printer.setAutoScroll(false);
printer.setVideoAttrs(0);
printer.setInk(Color.BLACK);
printer.setStroke(Color.WHITE);
public static void printVideoAttributes(Printer printer) {
printer.clear();
printer.setAutoScroll(false);
printer.setVideoAttrs(0);
printer.setInk(Color.BLACK);
printer.setStroke(Color.WHITE);
String demoLine = "Lorem=ipsum-dolor$sit.ametÆØÅå*,|▞&Jumps Over\\the?fLat Dog{}()#\"!";
printer.println("RIBU|" + demoLine);
for (int i = 1; i < 16; i++) {
printer.setVideoAttrs(i);
String s = (i & 1) != 0 ? "X" : " ";
s += (i & 2) != 0 ? "X" : " ";
s += (i & 4) != 0 ? "X" : " ";
s += (i & 8) != 0 ? "X" : " ";
printer.println(s + "|" + demoLine);
}
printer.setVideoAttrs(0);
printer.println();
printer.println("Lines: under, through, over");
printer.setVideoAttrs(TextFont.ATTR_UNDERLINE);
printer.println(" " + demoLine + " ");
printer.setVideoAttrs(TextFont.ATTR_LINE_THROUGH);
printer.println(" " + demoLine + " ");
printer.setVideoAttrs(TextFont.ATTR_OVERLINE);
printer.println(" " + demoLine + " ");
printer.setVideoAttrs(0);
String demoLine = "Lorem=ipsum-dolor$sit.ametÆØÅå*,|▞&Jumps Over\\the?fLat Dog{}()#\"!";
printer.println("RIBU|" + demoLine);
for (int i = 1; i < 16; i++) {
printer.setVideoAttrs(i);
String s = (i & 1) != 0 ? "X" : " ";
s += (i & 2) != 0 ? "X" : " ";
s += (i & 4) != 0 ? "X" : " ";
s += (i & 8) != 0 ? "X" : " ";
printer.println(s + "|" + demoLine);
}
printer.setVideoAttrs(0);
printer.println();
printer.println("Lines: under, through, over");
printer.setVideoAttrs(TextFont.ATTR_UNDERLINE);
printer.println(" " + demoLine + " ");
printer.setVideoAttrs(TextFont.ATTR_LINE_THROUGH);
printer.println(" " + demoLine + " ");
printer.setVideoAttrs(TextFont.ATTR_OVERLINE);
printer.println(" " + demoLine + " ");
printer.setVideoAttrs(0);
}
}
public static void printZX(Printer printer) {
printer.moveTo(1, 1);
printer.setAutoScroll(false);
printer.clear();
printer.println(" ▄▄▄ ▄ ▄ ▄");
printer.println(" █ █ █ █ █ █ █");
printer.println(" █ █ █ █ █ █ █");
printer.println(" █ █ █ █ █ █ █");
printer.println(" ▀ ▀ ▀ ▀ ▀▀▀");
printer.println(" ▄▄▄ ▄▄");
printer.println(" █ █");
printer.println(" █ █");
printer.println(" █ █");
printer.println(" ▀▀▀ ▀▀");
printer.println(" ▄▄ ▄ ▄ ▄");
printer.println(" █ █ █ █ █ █");
printer.println(" █ █ █ █ █ █");
printer.println(" █ █ █ █ █ █");
printer.println(" ▀▀ ▀ ▀ ▀▀▀");
printer.println("ON █████ █ █ ███ █");
printer.println("THE █ █ █ █ █ ██");
printer.println("SINCLAIR █ ███ █");
printer.println(" █ █ █ █ █ WITH");
printer.println(" █ █ █ █ █ █ 16K");
printer.println(" █████ █ █ ███ ███ RAM");
printer.moveTo(1, 1);
printer.setAutoScroll(true);
}
public static void printZX(Printer printer) {
printer.moveTo(1, 1);
printer.setAutoScroll(false);
printer.clear();
printer.println(" ▄▄▄ ▄ ▄ ▄");
printer.println(" █ █ █ █ █ █ █");
printer.println(" █ █ █ █ █ █ █");
printer.println(" █ █ █ █ █ █ █");
printer.println(" ▀ ▀ ▀ ▀ ▀▀▀");
printer.println(" ▄▄▄ ▄▄");
printer.println(" █ █");
printer.println(" █ █");
printer.println(" █ █");
printer.println(" ▀▀▀ ▀▀");
printer.println(" ▄▄ ▄ ▄ ▄");
printer.println(" █ █ █ █ █ █");
printer.println(" █ █ █ █ █ █");
printer.println(" █ █ █ █ █ █");
printer.println(" ▀▀ ▀ ▀ ▀▀▀");
printer.println("ON █████ █ █ ███ █");
printer.println("THE █ █ █ █ █ ██");
printer.println("SINCLAIR █ ███ █");
printer.println(" █ █ █ █ █ WITH");
printer.println(" █ █ █ █ █ █ 16K");
printer.println(" █████ █ █ ███ ███ RAM");
printer.moveTo(1, 1);
printer.setAutoScroll(true);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,6 @@
package inf101.v18.gfx.textmode;
import inf101.v18.gfx.Screen;
import inf101.v18.gfx.textmode.Printer;
import javafx.application.Application;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
@ -11,226 +10,227 @@ import javafx.stage.Stage;
import java.util.Objects;
public class TextFontAdjuster extends Application {
// private static final String FONT_NAME = "PetMe64.ttf";
// new TextFont(FONT_NAME, 22.2, TextModes.CHAR_BOX_SIZE, 0.0, 0.0, 1.0, 1.0);
private static TextFontAdjuster demo;
// private static final String FONT_NAME = "PetMe64.ttf";
// new TextFont(FONT_NAME, 22.2, TextModes.CHAR_BOX_SIZE, 0.0, 0.0, 1.0, 1.0);
private static TextFontAdjuster demo;
public static TextFontAdjuster getInstance() {
return demo;
}
public static TextFontAdjuster getInstance() {
return demo;
}
public static void main(String[] args) {
launch(args);
}
public static void main(String[] args) {
launch(args);
}
private TextFont textFont = Printer.FONT_SYMBOLA;//
// new TextFont("ZXSpectrum-7.otf", 22.00, TextMode.CHAR_BOX_SIZE, 3.1000,
// -3.8000, 1.0000, 1.0000, true);
private Screen screen;
private TextFont textFont = Printer.FONT_SYMBOLA;//
// new TextFont("ZXSpectrum-7.otf", 22.00, TextMode.CHAR_BOX_SIZE, 3.1000,
// -3.8000, 1.0000, 1.0000, true);
private Screen screen;
private boolean paused;
private Printer printer;
private boolean paused;
private Printer printer;
private boolean grid = true;
private boolean grid = true;
private double adjustAmount = 0.1;
private final double adjustAmount = 0.1;
private double adjustX(KeyCode code) {
switch (code) {
case LEFT:
return -1 * adjustAmount;
case RIGHT:
return 1 * adjustAmount;
default:
return 0;
}
}
private double adjustX(KeyCode code) {
switch (code) {
case LEFT:
return -1 * adjustAmount;
case RIGHT:
return 1 * adjustAmount;
default:
return 0;
}
}
private double adjustY(KeyCode code) {
switch (code) {
case UP:
return 1 * adjustAmount;
case DOWN:
return -1 * adjustAmount;
default:
return 0;
}
}
private double adjustY(KeyCode code) {
switch (code) {
case UP:
return 1 * adjustAmount;
case DOWN:
return -1 * adjustAmount;
default:
return 0;
}
}
private void drawBackgroundGrid() {
if (grid) {
printer.drawCharCells();
/*
* painter.turnTo(0); for (int y = 0; y < printer.getPageHeight(); y++) {
* painter.jumpTo(0, y * printer.getCharHeight()); for (int x = 0; x <
* printer.getLineWidth(); x++) { painter.setInk( (x + y) % 2 == 0 ?
* Color.CORNFLOWERBLUE : Color.CORNFLOWERBLUE.brighter().brighter());
* painter.fillRectangle(printer.getCharWidth(), printer.getCharHeight());
* painter.jump(printer.getCharWidth()); } }
*/
} else {
screen.clearBackground();
}
}
private void drawBackgroundGrid() {
if (grid) {
printer.drawCharCells();
/*
* painter.turnTo(0); for (int y = 0; y < printer.getPageHeight(); y++) {
* painter.jumpTo(0, y * printer.getCharHeight()); for (int x = 0; x <
* printer.getLineWidth(); x++) { painter.setInk( (x + y) % 2 == 0 ?
* Color.CORNFLOWERBLUE : Color.CORNFLOWERBLUE.brighter().brighter());
* painter.fillRectangle(printer.getCharWidth(), printer.getCharHeight());
* painter.jump(printer.getCharWidth()); } }
*/
} else {
screen.clearBackground();
}
}
private void printHelp() {
printer.moveTo(1, 1);
printer.setAutoScroll(false);
printer.println(" " + Printer.center("TextFontAdjuster", 36) + " ");
printer.println(" ");
printer.println(" ");
printer.println(" ");
printer.println("________________________________________");
printer.println("Adjust letter parameters: ");
printer.println(" Font size: CTRL +, CTRL - ");
printer.println(" Position: LEFT, RIGHT, UP, DOWN ");
printer.println(" Scaling: CTRL-(LEFT, RIGHT, UP, DOWN)");
printer.println("Commands / options (with CTRL key): ");
printer.println(" Hires (R) Grid (G) Fullscreen (F) ");
printer.println(" Help (H) Quit (Q) ");
printer.println("Write text with any other key. ");
printer.println("_-*-_-*-_-*-_-*-_-*-_-*-_-*-_-*-_-*-_-*-");
printer.println(" ");
printer.println("Sample text: ");
printer.println("the quick brown fox jumps over the lazy ");
printer.println(" dog, THE QUICK BROWN FOX JUMPS OVER THE");
printer.println("LAZY DOG den vågale røde reven værer den");
printer.println("sinte hunden DEN VÅGALE RØDE REVEN VÆRER");
printer.println("DEN SINTE HUNDEN !\"#%&/()?,._-@£${[]}?|^");
private void printHelp() {
printer.moveTo(1, 1);
printer.setAutoScroll(false);
printer.println(" " + Printer.center("TextFontAdjuster", 36) + " ");
printer.println(" ");
printer.println(" ");
printer.println(" ");
printer.println("________________________________________");
printer.println("Adjust letter parameters: ");
printer.println(" Font size: CTRL +, CTRL - ");
printer.println(" Position: LEFT, RIGHT, UP, DOWN ");
printer.println(" Scaling: CTRL-(LEFT, RIGHT, UP, DOWN)");
printer.println("Commands / options (with CTRL key): ");
printer.println(" Hires (R) Grid (G) Fullscreen (F) ");
printer.println(" Help (H) Quit (Q) ");
printer.println("Write text with any other key. ");
printer.println("_-*-_-*-_-*-_-*-_-*-_-*-_-*-_-*-_-*-_-*-");
printer.println(" ");
printer.println("Sample text: ");
printer.println("the quick brown fox jumps over the lazy ");
printer.println(" dog, THE QUICK BROWN FOX JUMPS OVER THE");
printer.println("LAZY DOG den vågale røde reven værer den");
printer.println("sinte hunden DEN VÅGALE RØDE REVEN VÆRER");
printer.println("DEN SINTE HUNDEN !\"#%&/()?,._-@£${[]}?|^");
// printer.print(" ");
printer.moveTo(1, 15);
printer.setAutoScroll(true);
// printer.print(" ");
printer.moveTo(1, 15);
printer.setAutoScroll(true);
}
}
private void printInfo() {
printer.moveTo(1, 3);
printer.println(String.format("Font: %s at %1.1fpt ", textFont.getFont().getName(),
textFont.getFont().getSize()));
printer.println(String.format(" xTr=%-1.1f yTr=%-1.1f xSc=%-1.1f ySc=%-1.1f ", textFont.getxTranslate(),
textFont.getyTranslate(), textFont.getxScale(), textFont.getyScale()));
System.out.printf("new TextFont(\"%s\", %1.2f, Printer.CHAR_HEIGHT, %1.4f, %1.4f, %1.4f, %1.4f)%n",
textFont.getFont().getName(), textFont.getSize(), textFont.getxTranslate(), textFont.getyTranslate(),
textFont.getxScale(), textFont.getyScale());
private void printInfo() {
printer.moveTo(1, 3);
printer.println(String.format("Font: %s at %1.1fpt ", textFont.getFont().getName(),
textFont.getFont().getSize()));
printer.println(String.format(" xTr=%-1.1f yTr=%-1.1f xSc=%-1.1f ySc=%-1.1f ", textFont.getxTranslate(),
textFont.getyTranslate(), textFont.getxScale(), textFont.getyScale()));
System.out.printf("new TextFont(\"%s\", %1.2f, Printer.CHAR_HEIGHT, %1.4f, %1.4f, %1.4f, %1.4f)%n",
textFont.getFont().getName(), textFont.getSize(), textFont.getxTranslate(), textFont.getyTranslate(),
textFont.getxScale(), textFont.getyScale());
printer.moveTo(1, 15);
}
printer.moveTo(1, 15);
}
private void setup() {
drawBackgroundGrid();
printHelp();
printInfo();
}
private void setup() {
drawBackgroundGrid();
printHelp();
printInfo();
}
@Override
public void start(Stage stage) {
demo = this;
@Override
public void start(Stage stage) {
demo = this;
screen = Screen.startPaintScene(stage);
screen = Screen.startPaintScene(stage);
printer = screen.createPrinter();
printer.setInk(Color.BLACK);
printer.setFont(textFont);
screen.setKeyOverride((KeyEvent event) -> {
KeyCode code = event.getCode();
// System.out.println(event);
if (event.isControlDown() || event.isShortcutDown()) {
if (code == KeyCode.Q) {
System.exit(0);
} else if (code == KeyCode.P) {
paused = !paused;
return true;
} else if (code == KeyCode.R) {
printer.cycleMode(true);
drawBackgroundGrid();
return true;
} else if (code == KeyCode.S) {
if (event.isAltDown())
screen.fitScaling();
else
screen.zoomCycle();
drawBackgroundGrid();
return true;
} else if (code == KeyCode.A) {
screen.cycleAspect();
return true;
} else if (code == KeyCode.G) {
grid = !grid;
drawBackgroundGrid();
return true;
} else if (code == KeyCode.H) {
printHelp();
printInfo();
return true;
} else if (code == KeyCode.F) {
stage.setFullScreen(!stage.isFullScreen());
return true;
} else if (code == KeyCode.M) {
printer.print("\r");
return true;
} else if (code == KeyCode.L) {
printer.redrawTextPage();
return true;
} else if (code == KeyCode.DIGIT1) {
DemoPages.printBoxDrawing(printer);
return true;
} else if (code == KeyCode.DIGIT2) {
DemoPages.printZX(printer);
return true;
} else if (code == KeyCode.DIGIT3) {
DemoPages.printBlockPlotting(printer);
return true;
} else if (code == KeyCode.DIGIT4) {
DemoPages.printVideoAttributes(printer);
return true;
} else if (code == KeyCode.DIGIT5) {
DemoPages.printAnsiArt(printer);
return true;
} else if (code == KeyCode.PLUS) {
textFont = textFont.adjust(adjustAmount, 0.0, 0.0, 0.0, 0.0);
printer.setFont(textFont);
printer.redrawTextPage();
printInfo();
return true;
} else if (code == KeyCode.MINUS) {
textFont = textFont.adjust(-adjustAmount, 0.0, 0.0, 0.0, 0.0);
printer.setFont(textFont);
printer.redrawTextPage();
printInfo();
return true;
} else if (code == KeyCode.LEFT || code == KeyCode.RIGHT || code == KeyCode.UP
|| code == KeyCode.DOWN) {
textFont = textFont.adjust(0.0, 0.0, 0.0, adjustX(code), adjustY(code));
printer.setFont(textFont);
printer.redrawTextPage();
printInfo();
return true;
}
} else if (code == KeyCode.LEFT || code == KeyCode.RIGHT || code == KeyCode.UP || code == KeyCode.DOWN) {
textFont = textFont.adjust(0.0, adjustX(code), adjustY(code), 0.0, 0.0);
printer.setFont(textFont);
printer.redrawTextPage();
printInfo();
return true;
} else if (code == KeyCode.ENTER) {
printer = screen.createPrinter();
printer.setInk(Color.BLACK);
printer.setFont(textFont);
screen.setKeyOverride((KeyEvent event) -> {
KeyCode code = event.getCode();
// System.out.println(event);
if (event.isControlDown() || event.isShortcutDown()) {
if (code == KeyCode.Q) {
System.exit(0);
} else if (code == KeyCode.P) {
paused = !paused;
return true;
} else if (code == KeyCode.R) {
printer.cycleMode(true);
drawBackgroundGrid();
return true;
} else if (code == KeyCode.S) {
if (event.isAltDown()) {
screen.fitScaling();
} else {
screen.zoomCycle();
}
drawBackgroundGrid();
return true;
} else if (code == KeyCode.A) {
screen.cycleAspect();
return true;
} else if (code == KeyCode.G) {
grid = !grid;
drawBackgroundGrid();
return true;
} else if (code == KeyCode.H) {
printHelp();
printInfo();
return true;
} else if (code == KeyCode.F) {
stage.setFullScreen(!stage.isFullScreen());
return true;
} else if (code == KeyCode.M) {
printer.print("\r");
return true;
} else if (code == KeyCode.L) {
printer.redrawTextPage();
return true;
} else if (code == KeyCode.DIGIT1) {
DemoPages.printBoxDrawing(printer);
return true;
} else if (code == KeyCode.DIGIT2) {
DemoPages.printZX(printer);
return true;
} else if (code == KeyCode.DIGIT3) {
DemoPages.printBlockPlotting(printer);
return true;
} else if (code == KeyCode.DIGIT4) {
DemoPages.printVideoAttributes(printer);
return true;
} else if (code == KeyCode.DIGIT5) {
DemoPages.printAnsiArt(printer);
return true;
} else if (code == KeyCode.PLUS) {
textFont = textFont.adjust(adjustAmount, 0.0, 0.0, 0.0, 0.0);
printer.setFont(textFont);
printer.redrawTextPage();
printInfo();
return true;
} else if (code == KeyCode.MINUS) {
textFont = textFont.adjust(-adjustAmount, 0.0, 0.0, 0.0, 0.0);
printer.setFont(textFont);
printer.redrawTextPage();
printInfo();
return true;
} else if (code == KeyCode.LEFT || code == KeyCode.RIGHT || code == KeyCode.UP
|| code == KeyCode.DOWN) {
textFont = textFont.adjust(0.0, 0.0, 0.0, adjustX(code), adjustY(code));
printer.setFont(textFont);
printer.redrawTextPage();
printInfo();
return true;
}
} else if (code == KeyCode.LEFT || code == KeyCode.RIGHT || code == KeyCode.UP || code == KeyCode.DOWN) {
textFont = textFont.adjust(0.0, adjustX(code), adjustY(code), 0.0, 0.0);
printer.setFont(textFont);
printer.redrawTextPage();
printInfo();
return true;
} else if (code == KeyCode.ENTER) {
printer.print("\n");
return true;
}
return false;
});
screen.setKeyTypedHandler((KeyEvent event) -> {
if (!Objects.equals(event.getCharacter(), KeyEvent.CHAR_UNDEFINED)) {
printer.print(event.getCharacter());
return true;
}
return false;
});
setup();
printer.print("\n");
return true;
}
return false;
});
screen.setKeyTypedHandler((KeyEvent event) -> {
if (!Objects.equals(event.getCharacter(), KeyEvent.CHAR_UNDEFINED)) {
printer.print(event.getCharacter());
return true;
}
return false;
});
setup();
stage.show();
stage.show();
}
}
}

View File

@ -3,156 +3,169 @@ package inf101.v18.gfx.textmode;
import inf101.v18.gfx.Screen;
public enum TextMode {
/** Low resolution, wide screen (20:11, fits 16:9) text mode 40x22 */
MODE_40X22(Constants.H40, Constants.V22, Screen.ASPECT_WIDE),
/** Low resolution, 16:10 aspect text mode 40x25 */
MODE_40X25(Constants.H40, Constants.V25, Screen.ASPECT_MEDIUM),
/** Low resolution, 4:3 aspect text mode 40x30 */
MODE_40X30(Constants.H40, Constants.V30, Screen.ASPECT_CLASSIC),
/** High resolution, wide screen (20:11, fits 16:9) text mode 80x22 */
MODE_80X22(Constants.H80, Constants.V22, Screen.ASPECT_WIDE),
/** High resolution, 16:10 aspect text mode 80x25 */
MODE_80X25(Constants.H80, Constants.V25, Screen.ASPECT_MEDIUM),
/** High resolution, 4:3 aspect text mode 80x30 */
MODE_80X30(Constants.H80, Constants.V30, Screen.ASPECT_CLASSIC);
/**
* Low resolution, wide screen (20:11, fits 16:9) text mode 40x22
*/
MODE_40X22(Constants.H40, Constants.V22, Screen.ASPECT_WIDE),
/**
* Low resolution, 16:10 aspect text mode 40x25
*/
MODE_40X25(Constants.H40, Constants.V25, Screen.ASPECT_MEDIUM),
/**
* Low resolution, 4:3 aspect text mode 40x30
*/
MODE_40X30(Constants.H40, Constants.V30, Screen.ASPECT_CLASSIC),
/**
* High resolution, wide screen (20:11, fits 16:9) text mode 80x22
*/
MODE_80X22(Constants.H80, Constants.V22, Screen.ASPECT_WIDE),
/**
* High resolution, 16:10 aspect text mode 80x25
*/
MODE_80X25(Constants.H80, Constants.V25, Screen.ASPECT_MEDIUM),
/**
* High resolution, 4:3 aspect text mode 80x30
*/
MODE_80X30(Constants.H80, Constants.V30, Screen.ASPECT_CLASSIC);
protected static class Constants {
protected static final int H40 = 0, H80 = 1;
protected static final int[] HREZ = { 40, 80 };
protected static final int V22 = 0, V25 = 1, V30 = 2;
protected static final int[] VREZ = { 22, 25, 30 };
private static TextMode[] MODES = null;
protected static class Constants {
protected static final int H40 = 0, H80 = 1;
protected static final int[] HREZ = {40, 80};
protected static final int V22 = 0, V25 = 1, V30 = 2;
protected static final int[] VREZ = {22, 25, 30};
private static TextMode[] MODES = null;
// work around initialization order for statics and enums
protected static TextMode getMode(int i) {
if (MODES == null)
MODES = new TextMode[] { MODE_40X22, MODE_40X25, MODE_40X30, MODE_80X22, MODE_80X25, MODE_80X30 };
return MODES[(i + MODES.length) % MODES.length];
}
}
// work around initialization order for statics and enums
protected static TextMode getMode(int i) {
if (MODES == null) {
MODES = new TextMode[]{MODE_40X22, MODE_40X25, MODE_40X30, MODE_80X22, MODE_80X25, MODE_80X30};
}
return MODES[(i + MODES.length) % MODES.length];
}
}
/**
* Size of the square-shaped "box" bounds of character cells.
*
* For "high" resolution, characters will be squeezed horizontally to fit half
* the width.
*/
public static final double CHAR_BOX_SIZE = 32;
/**
* Maximum length of a line in any resolution mode
*/
public static final int LINE_WIDTH_MAX = Constants.HREZ[Constants.HREZ.length - 1];
/**
* Maximum height of a page in any resolution mode
*/
public static final int PAGE_HEIGHT_MAX = Constants.VREZ[Constants.VREZ.length - 1];
private int aspect;
private int w;
/**
* Size of the square-shaped "box" bounds of character cells.
* <p>
* For "high" resolution, characters will be squeezed horizontally to fit half
* the width.
*/
public static final double CHAR_BOX_SIZE = 32;
/**
* Maximum length of a line in any resolution mode
*/
public static final int LINE_WIDTH_MAX = Constants.HREZ[Constants.HREZ.length - 1];
/**
* Maximum height of a page in any resolution mode
*/
public static final int PAGE_HEIGHT_MAX = Constants.VREZ[Constants.VREZ.length - 1];
private int aspect;
private int w;
private int h;
private int h;
private int hIndex;
private int hIndex;
private int vIndex;
private int vIndex;
TextMode(int w, int h, int aspect) {
this.hIndex = w;
this.vIndex = h;
this.aspect = aspect;
this.w = Constants.HREZ[w];
this.h = Constants.VREZ[h];
}
TextMode(int w, int h, int aspect) {
this.hIndex = w;
this.vIndex = h;
this.aspect = aspect;
this.w = Constants.HREZ[w];
this.h = Constants.VREZ[h];
}
private TextMode findMode(int hIndex, int vIndex) {
hIndex = (hIndex + Constants.HREZ.length) % Constants.HREZ.length;
vIndex = (vIndex + Constants.VREZ.length) % Constants.VREZ.length;
return Constants.getMode(vIndex + hIndex * Constants.VREZ.length);
}
private TextMode findMode(int hIndex, int vIndex) {
hIndex = (hIndex + Constants.HREZ.length) % Constants.HREZ.length;
vIndex = (vIndex + Constants.VREZ.length) % Constants.VREZ.length;
return Constants.getMode(vIndex + hIndex * Constants.VREZ.length);
}
/**
* Get aspect ration descriptor for use with {@link Screen#setAspect()}
*
* @return One of {@link Screen#ASPECT_WIDE}, {@link Screen#ASPECT_MEDIUM} or
* {@link Screen#ASPECT_CLASSIC}
*/
public int getAspect() {
return aspect;
}
/**
* Get aspect ration descriptor for use with {@link Screen#setAspect()}
*
* @return One of {@link Screen#ASPECT_WIDE}, {@link Screen#ASPECT_MEDIUM} or
* {@link Screen#ASPECT_CLASSIC}
*/
public int getAspect() {
return aspect;
}
public double getCharBoxSize() {
return CHAR_BOX_SIZE;
}
public double getCharBoxSize() {
return CHAR_BOX_SIZE;
}
public double getCharHeight() {
return CHAR_BOX_SIZE;
}
public double getCharHeight() {
return CHAR_BOX_SIZE;
}
public double getCharWidth() {
return w == 80 ? CHAR_BOX_SIZE / 2 : CHAR_BOX_SIZE;
}
public double getCharWidth() {
return w == 80 ? CHAR_BOX_SIZE / 2 : CHAR_BOX_SIZE;
}
public int getLineWidth() {
return w;
}
public int getLineWidth() {
return w;
}
public int getPageHeight() {
return h;
}
public int getPageHeight() {
return h;
}
/**
* Cycle through horizontal modes
*
* @return Next available horizontal mode (vertical resolution unchanged)
*/
public TextMode nextHorizMode() {
return findMode((hIndex + 1) % Constants.HREZ.length, vIndex);
}
/**
* Cycle through horizontal modes
*
* @return Next available horizontal mode (vertical resolution unchanged)
*/
public TextMode nextHorizMode() {
return findMode((hIndex + 1) % Constants.HREZ.length, vIndex);
}
/**
* Cycle through modes
*
* @return Next available mode
*/
public TextMode nextMode() {
int m = vIndex + hIndex * Constants.VREZ.length;
return Constants.getMode(m + 1);
}
/**
* Cycle through modes
*
* @return Next available mode
*/
public TextMode nextMode() {
int m = vIndex + hIndex * Constants.VREZ.length;
return Constants.getMode(m + 1);
}
/**
* Cycle through vertical modes
*
* @return Next available vertical mode (horizontal resolution unchanged)
*/
public TextMode nextVertMode() {
return findMode((hIndex + 1) % Constants.HREZ.length, vIndex);
}
/**
* Cycle through vertical modes
*
* @return Next available vertical mode (horizontal resolution unchanged)
*/
public TextMode nextVertMode() {
return findMode((hIndex + 1) % Constants.HREZ.length, vIndex);
}
/**
* Cycle through horizontal modes
*
* @return Previous available horizontal mode (vertical resolution unchanged)
*/
public TextMode prevHorizMode() {
return findMode((hIndex - 1) % Constants.HREZ.length, vIndex);
}
/**
* Cycle through horizontal modes
*
* @return Previous available horizontal mode (vertical resolution unchanged)
*/
public TextMode prevHorizMode() {
return findMode((hIndex - 1) % Constants.HREZ.length, vIndex);
}
/**
* Cycle through modes
*
* @return Previous available mode
*/
public TextMode prevMode() {
int m = vIndex + hIndex * Constants.VREZ.length;
return Constants.getMode(m);
}
/**
* Cycle through modes
*
* @return Previous available mode
*/
public TextMode prevMode() {
int m = vIndex + hIndex * Constants.VREZ.length;
return Constants.getMode(m);
}
/**
* Cycle through vertical modes
*
* @return Previous available vertical mode (horizontal resolution unchanged)
*/
public TextMode prevVertMode() {
return findMode((hIndex - 1) % Constants.HREZ.length, vIndex);
}
/**
* Cycle through vertical modes
*
* @return Previous available vertical mode (horizontal resolution unchanged)
*/
public TextMode prevVertMode() {
return findMode((hIndex - 1) % Constants.HREZ.length, vIndex);
}
}

View File

@ -4,66 +4,73 @@ import java.util.Arrays;
import java.util.List;
public enum GridDirection {
EAST(0, 1, 0, 4), NORTH(90, 0, -1, 1), WEST(180, -1, 0, 8), SOUTH(270, 0, 1, 2), //
NORTHEAST(45, 1, -1, 5), NORTHWEST(135, -1, -1, 9), SOUTHWEST(225, -1, 1, 10), SOUTHEAST(315, 1, 1, 6), //
CENTER(0, 0, 0, 0);
/**
* The four cardinal directions: {@link #NORTH}, {@link #SOUTH}, {@link #EAST},
* {@link #WEST}.
*/
public static final List<GridDirection> FOUR_DIRECTIONS = Arrays.asList(EAST, NORTH, WEST, SOUTH);
/**
* The eight cardinal and intercardinal directions: {@link #NORTH},
* {@link #SOUTH}, {@link #EAST}, {@link #WEST}, {@link #NORTHWEST},
* {@link #NORTHEAST}, {@link #SOUTHWEST}, {@link #SOUTHEAST}.
*/
public static final List<GridDirection> EIGHT_DIRECTIONS = Arrays.asList(EAST, NORTHEAST, NORTH, NORTHWEST, WEST,
SOUTHWEST, SOUTH, SOUTHEAST);
/**
* The eight cardinal and intercardinal directions ({@link #EIGHT_DIRECTIONS}),
* plus {@link #CENTER}.
*/
public static final List<GridDirection> NINE_DIRECTIONS = Arrays.asList(EAST, NORTHEAST, NORTH, NORTHWEST, WEST,
SOUTHWEST, SOUTH, SOUTHEAST, CENTER);
EAST(0, 1, 0, 4),
NORTH(90, 0, -1, 1),
WEST(180, -1, 0, 8),
SOUTH(270, 0, 1, 2),
NORTHEAST(45, 1, -1, 5),
NORTHWEST(135, -1, -1, 9),
SOUTHWEST(225, -1, 1, 10),
SOUTHEAST(315, 1, 1, 6),
CENTER(0, 0, 0, 0);
private final double degrees;
private final int dx;
private final int dy;
private final int mask;
/**
* The four cardinal directions: {@link #NORTH}, {@link #SOUTH}, {@link #EAST},
* {@link #WEST}.
*/
public static final List<GridDirection> FOUR_DIRECTIONS = Arrays.asList(EAST, NORTH, WEST, SOUTH);
/**
* The eight cardinal and intercardinal directions: {@link #NORTH},
* {@link #SOUTH}, {@link #EAST}, {@link #WEST}, {@link #NORTHWEST},
* {@link #NORTHEAST}, {@link #SOUTHWEST}, {@link #SOUTHEAST}.
*/
public static final List<GridDirection> EIGHT_DIRECTIONS = Arrays.asList(EAST, NORTHEAST, NORTH, NORTHWEST, WEST,
SOUTHWEST, SOUTH, SOUTHEAST);
/**
* The eight cardinal and intercardinal directions ({@link #EIGHT_DIRECTIONS}),
* plus {@link #CENTER}.
*/
public static final List<GridDirection> NINE_DIRECTIONS = Arrays.asList(EAST, NORTHEAST, NORTH, NORTHWEST, WEST,
SOUTHWEST, SOUTH, SOUTHEAST, CENTER);
GridDirection(double degrees, int dx, int dy, int mask) {
this.degrees = degrees;
this.dx = dx;
this.dy = dy;
this.mask = mask;
}
private final double degrees;
private final int dx;
private final int dy;
private final int mask;
/**
* @return The angle of this direction, with 0° facing due {@link #EAST} and 90°
* being {@link #NORTH}.
*/
public double getDegrees() {
return degrees;
}
GridDirection(double degrees, int dx, int dy, int mask) {
this.degrees = degrees;
this.dx = dx;
this.dy = dy;
this.mask = mask;
}
/**
* @return The change to your X-coordinate if you were to move one step in this
* direction
*/
public int getDx() {
return dx;
}
/**
* @return The angle of this direction, with 0° facing due {@link #EAST} and 90°
* being {@link #NORTH}.
*/
public double getDegrees() {
return degrees;
}
/**
* @return The change to your Y-coordinate if you were to move one step in this
* direction
*/
public int getDy() {
return dy;
}
/**
* @return The change to your X-coordinate if you were to move one step in this
* direction
*/
public int getDx() {
return dx;
}
public int getMask() {
return mask;
}
/**
* @return The change to your Y-coordinate if you were to move one step in this
* direction
*/
public int getDy() {
return dy;
}
public int getMask() {
return mask;
}
}

View File

@ -10,152 +10,150 @@ import java.util.stream.Stream;
* locations within the area.
* <p>
* See {@link #location(int, int)} to covert (x,y)-coordinates to
* {@link ILocation}s.
* {@link Location}s.
* <p>
* An {@link IArea} does not <em>store</em> anything, it just defines valid
* storage locations (e.g., for an {@link IGrid}), and the relationships between
* locations (e.g., how to find neighbours of a given location).
*
*
* @author Anya Helene Bagge, UiB
*/
public interface IArea extends Iterable<ILocation> {
/**
* Check if a (x,y) is inside the area.
*
* @param x
* X-coordinate
* @param y
* Y-coordinate
* @return True if the (x,y) position lies within the area
*/
boolean contains(int x, int y);
public interface IArea extends Iterable<Location> {
/**
* Check if a (x,y) is inside the area.
*
* @param x X-coordinate
* @param y Y-coordinate
* @return True if the (x,y) position lies within the area
*/
boolean contains(int x, int y);
/**
* Check if a position is inside the area.
*
* @param pos
* A position
* @return True if the position lies within the area
*/
boolean contains(IPosition pos);
/**
* Check if a position is inside the area.
*
* @param pos A position
* @return True if the position lies within the area
*/
boolean contains(IPosition pos);
@Override
boolean equals(Object other);
@Override
boolean equals(Object other);
/**
* Convert a 1D coordinate to a location
* <p>
* Returns a location <code>l = fromIndex(i)</code> such that
* <code>toIndex(l.getX(), l.getY()) == i</code>.
*
* @param i
* @return A location
*/
ILocation fromIndex(int i);
/**
* Convert a 1D coordinate to a location
* <p>
* Returns a location <code>l = fromIndex(i)</code> such that
* <code>toIndex(l.getX(), l.getY()) == i</code>.
*
* @param i
* @return A location
*/
Location fromIndex(int i);
/** @return Height of the area */
int getHeight();
/**
* @return Height of the area
*/
int getHeight();
/**
* Returns the number of legal positions in the area
*
* @return Same as getWidth()*getHeight()
*/
int getSize();
/**
* Returns the number of legal positions in the area
*
* @return Same as getWidth()*getHeight()
*/
int getSize();
/** @return Width of the area */
int getWidth();
/**
* @return Width of the area
*/
int getWidth();
@Override
int hashCode();
@Override
int hashCode();
/**
* Get a location object corresponding to (x,y)
*
* @param x
* X-coordinate
* @param y
* Y-coordinate
* @return The location object associated with (x,y)
* @throws IndexOutOfBoundsException
* if {@link #contains(int, int)} returns false for (x,y)
*/
ILocation location(int x, int y);
/**
* Get a location object corresponding to (x,y)
*
* @param x X-coordinate
* @param y Y-coordinate
* @return The location object associated with (x,y)
* @throws IndexOutOfBoundsException if {@link #contains(int, int)} returns false for (x,y)
*/
Location location(int x, int y);
/**
* Get all locations in area
* <p>
* Since IArea is @{@link Iterable}, you can also use directly in a for-loop to
* iterate over the locations.
* <p>
* All locations in the list are guaranteed to be valid according to
* {@link #isValid(ILocation)}. The returned list cannot be modified.
*
* @return An unmodifiable list with all the locations in the area
*/
List<ILocation> locations();
/**
* Get all locations in area
* <p>
* Since IArea is @{@link Iterable}, you can also use directly in a for-loop to
* iterate over the locations.
* <p>
* All locations in the list are guaranteed to be valid according to
* {@link #isValid(Location)}. The returned list cannot be modified.
*
* @return An unmodifiable list with all the locations in the area
*/
List<Location> locations();
/**
* Return an object for iterating over all the neighbours of the given position,
* suitable for use in a new-style for-loop.
* <p>
* The iterator will yield up to eight positions (less if the given position is
* at the edge of the area, and the coordinates are not wrapped). E.g., for a
* 1x1 area, the iterator will yield nothing (if the area is not wrapped), or
* the same position two or eight times (if the area is wrapped horizontally,
* vertically or both).
*
* @param pos
* A position in the area
* @return An iterable over positions, with {@link #contains(ILocation)} being
* true for each position.
* @see #wrapsHorizontally(), {@link #wrapsVertically()}
* @throws IndexOutOfBoundsException
* if !contains(pos)
*/
Iterable<ILocation> neighboursOf(ILocation pos);
/**
* Return an object for iterating over all the neighbours of the given position,
* suitable for use in a new-style for-loop.
* <p>
* The iterator will yield up to eight positions (less if the given position is
* at the edge of the area, and the coordinates are not wrapped). E.g., for a
* 1x1 area, the iterator will yield nothing (if the area is not wrapped), or
* the same position two or eight times (if the area is wrapped horizontally,
* vertically or both).
*
* @param pos A position in the area
* @return An iterable over positions, with {@link #contains(Location)} being
* true for each position.
* @throws IndexOutOfBoundsException if !contains(pos)
* @see #wrapsHorizontally(), {@link #wrapsVertically()}
*/
Iterable<Location> neighboursOf(Location pos);
/** @return A (possibly) parallel {@link Stream} of all locations in the area */
Stream<ILocation> parallelStream();
/**
* @return A (possibly) parallel {@link Stream} of all locations in the area
*/
Stream<Location> parallelStream();
/** @return A {@link Stream} of all locations in the area */
Stream<ILocation> stream();
/**
* @return A {@link Stream} of all locations in the area
*/
Stream<Location> stream();
/**
* Convert a 2D coordinate to 1D
*
* @param x
* X-coordinate
* @param y
* Y-coordinate
* @return x + y*getWidth()
*/
int toIndex(int x, int y);
/**
* Convert a 2D coordinate to 1D
*
* @param x X-coordinate
* @param y Y-coordinate
* @return x + y*getWidth()
*/
int toIndex(int x, int y);
@Override
String toString();
@Override
String toString();
/**
* If the area wraps horizontally, then x will be the same as x+(k*getWidth())
* for any k i.e., it will be as if the 2D area is projected on a cylinder or
* torus in 3D-space.
* <p>
* With no wrapping, accessing positions outside (0,0)(getWidth(),getHeight())
* is illegal.
*
* @return True if the area wraps around horizontally
*/
boolean wrapsHorizontally();
/**
* If the area wraps horizontally, then x will be the same as x+(k*getWidth())
* for any k i.e., it will be as if the 2D area is projected on a cylinder or
* torus in 3D-space.
* <p>
* With no wrapping, accessing positions outside (0,0)(getWidth(),getHeight())
* is illegal.
*
* @return True if the area wraps around horizontally
*/
boolean wrapsHorizontally();
/**
* If the area wraps vertically, then y will be the same as y+(k*getHeight())
* for any k i.e., it will be as if the 2D area is projected on a cylinder or
* torus in 3D-space.
* <p>
* With no wrapping, accessing positions outside (0,0)(getWidth(),getHeight())
* is illegal.
*
* @return True if the area wraps around vertically
*/
boolean wrapsVertically();
/**
* If the area wraps vertically, then y will be the same as y+(k*getHeight())
* for any k i.e., it will be as if the 2D area is projected on a cylinder or
* torus in 3D-space.
* <p>
* With no wrapping, accessing positions outside (0,0)(getWidth(),getHeight())
* is illegal.
*
* @return True if the area wraps around vertically
*/
boolean wrapsVertically();
}

View File

@ -5,209 +5,194 @@ import java.util.stream.Stream;
public interface IGrid<T> extends Iterable<T> {
/**
* Make a copy
*
* @return A fresh copy of the grid, with the same elements
*/
IGrid<T> copy();
/**
* Make a copy
*
* @return A fresh copy of the grid, with the same elements
*/
IGrid<T> copy();
/**
* Create a parallel {@link Stream} with all the elements in this grid.
*
* @return A stream
* @see {@link java.util.Collection#parallelStream()}
*/
Stream<T> elementParallelStream();
/**
* Create a parallel {@link Stream} with all the elements in this grid.
*
* @return A stream
* @see {@link java.util.Collection#parallelStream()}
*/
Stream<T> elementParallelStream();
/**
* Create a {@link Stream} with all the elements in this grid.
*
* @return A stream
*/
Stream<T> elementStream();
/**
* Create a {@link Stream} with all the elements in this grid.
*
* @return A stream
*/
Stream<T> elementStream();
/**
* Initialise the contents of all cells using an initialiser function.
*
* The function will be called with the (x,y) position of an element, and is
* expected to return the element to place at that position. For example:
*
* <pre>
* // fill all cells with the position as a string (e.g., "(2,2)")
* grid.setAll((x, y) -> String.format("(%d,%d)", x, y));
* </pre>
*
* @param initialiser
* The initialiser function
*/
void fill(Function<ILocation, T> initialiser);
/**
* Initialise the contents of all cells using an initialiser function.
* <p>
* The function will be called with the (x,y) position of an element, and is
* expected to return the element to place at that position. For example:
*
* <pre>
* // fill all cells with the position as a string (e.g., "(2,2)")
* grid.setAll((x, y) -> String.format("(%d,%d)", x, y));
* </pre>
*
* @param initialiser The initialiser function
*/
void fill(Function<Location, T> initialiser);
/**
* Set the contents of all cells to <code>element</code>
*
* For example:
*
* <pre>
* // clear the grid
* grid.setAll(null);
* </pre>
*
* @param element
*/
void fill(T element);
/**
* Set the contents of all cells to <code>element</code>
* <p>
* For example:
*
* <pre>
* // clear the grid
* grid.setAll(null);
* </pre>
*
* @param element
*/
void fill(T element);
/**
* Get the contents of the cell in the given x,y location.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos
* The (x,y) position of the grid cell to get the contents of.
* @throws IndexOutOfBoundsException
* if !isValid(pos)
*/
T get(ILocation pos);
/**
* Get the contents of the cell in the given x,y location.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos The (x,y) position of the grid cell to get the contents of.
* @throws IndexOutOfBoundsException if !isValid(pos)
*/
T get(Location pos);
/**
* Get the contents of the cell in the given x,y location.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param x
* The column of the cell to get the contents of.
* @param y
* The row of the cell to get contents of.
* @throws IndexOutOfBoundsException
* if !isValid(x,y)
*/
T get(int x, int y);
/**
* Get the contents of the cell in the given x,y location.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param x The column of the cell to get the contents of.
* @param y The row of the cell to get contents of.
* @throws IndexOutOfBoundsException if !isValid(x,y)
*/
T get(int x, int y);
IArea getArea();
IArea getArea();
/** @return The height of the grid. */
int getHeight();
/**
* @return The height of the grid.
*/
int getHeight();
/**
* Get the contents of the cell in the given x,y location.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos
* The (x,y) position of the grid cell to get the contents of.
* @param defaultResult
* A default value to be substituted if the (x,y) is out of bounds or
* contents == null.
*/
T getOrDefault(ILocation pos, T defaultResult);
/**
* Get the contents of the cell in the given x,y location.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos The (x,y) position of the grid cell to get the contents of.
* @param defaultResult A default value to be substituted if the (x,y) is out of bounds or
* contents == null.
*/
T getOrDefault(Location pos, T defaultResult);
/**
* Get the contents of the cell in the given x,y location.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param x
* The column of the cell to get the contents of.
* @param y
* The row of the cell to get contents of.
* @param defaultResult
* A default value to be substituted if the (x,y) is out of bounds or
* contents == null.
*/
T getOrDefault(int x, int y, T defaultResult);
/**
* Get the contents of the cell in the given x,y location.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param x The column of the cell to get the contents of.
* @param y The row of the cell to get contents of.
* @param defaultResult A default value to be substituted if the (x,y) is out of bounds or
* contents == null.
*/
T getOrDefault(int x, int y, T defaultResult);
/** @return The width of the grid. */
int getWidth();
/**
* @return The width of the grid.
*/
int getWidth();
/**
* Check if coordinates are valid.
*
* Valid coordinates are 0 <= pos.getX() < getWidth(), 0 <= pos.getY() <
* getHeight().
*
* @param pos
* A position
* @return true if the position is within the grid
*/
boolean isValid(ILocation pos);
/**
* Check if coordinates are valid.
* <p>
* Valid coordinates are 0 <= pos.getX() < getWidth(), 0 <= pos.getY() <
* getHeight().
*
* @param pos A position
* @return true if the position is within the grid
*/
boolean isValid(Location pos);
/**
* Check if coordinates are valid.
*
* Valid coordinates are 0 <= x < getWidth(), 0 <= y < getHeight().
*
* @param x
* an x coordinate
* @param y
* an y coordinate
* @return true if the (x,y) position is within the grid
*/
boolean isValid(int x, int y);
/**
* Check if coordinates are valid.
* <p>
* Valid coordinates are 0 <= x < getWidth(), 0 <= y < getHeight().
*
* @param x an x coordinate
* @param y an y coordinate
* @return true if the (x,y) position is within the grid
*/
boolean isValid(int x, int y);
/**
* Create a parallel {@link Stream} with all the locations in this grid.
* <p>
* All locations obtained through the stream are guaranteed to be valid
* according to {@link #isValid(ILocation)}.
*
* @return A stream
* @see {@link java.util.Collection#parallelStream()}
*/
Stream<ILocation> locationParallelStream();
/**
* Create a parallel {@link Stream} with all the locations in this grid.
* <p>
* All locations obtained through the stream are guaranteed to be valid
* according to {@link #isValid(Location)}.
*
* @return A stream
* @see {@link java.util.Collection#parallelStream()}
*/
Stream<Location> locationParallelStream();
/**
* Iterate over all grid locations
* <p>
* See also {@link #iterator()} using the grid directly in a for-loop will
* iterate over the elements.
* <p>
* All locations obtained through the iterator are guaranteed to be valid
* according to {@link #isValid(ILocation)}.
*
* @return An iterable for iterating over all the locations in the grid
*/
Iterable<ILocation> locations();
/**
* Iterate over all grid locations
* <p>
* See also {@link #iterator()} using the grid directly in a for-loop will
* iterate over the elements.
* <p>
* All locations obtained through the iterator are guaranteed to be valid
* according to {@link #isValid(Location)}.
*
* @return An iterable for iterating over all the locations in the grid
*/
Iterable<Location> locations();
/**
* Create a {@link Stream} with all the locations in this grid.
* <p>
* All locations obtained through the stream are guaranteed to be valid
* according to {@link #isValid(ILocation)}.
*
* @return A stream
*/
Stream<ILocation> locationStream();
/**
* Create a {@link Stream} with all the locations in this grid.
* <p>
* All locations obtained through the stream are guaranteed to be valid
* according to {@link #isValid(Location)}.
*
* @return A stream
*/
Stream<Location> locationStream();
/**
* Set the contents of the cell in the given x,y location.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos
* The (x,y) position of the grid cell to get the contents of.
* @param element
* The contents the cell is to have.
* @throws IndexOutOfBoundsException
* if !isValid(pos)
*/
void set(ILocation pos, T element);
/**
* Set the contents of the cell in the given x,y location.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos The (x,y) position of the grid cell to get the contents of.
* @param element The contents the cell is to have.
* @throws IndexOutOfBoundsException if !isValid(pos)
*/
void set(Location pos, T element);
/**
* Set the contents of the cell in the given x,y location.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param element
* The contents the cell is to have.
* @throws IndexOutOfBoundsException
* if !isValid(x,y)
*/
void set(int x, int y, T element);
/**
* Set the contents of the cell in the given x,y location.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param element The contents the cell is to have.
* @throws IndexOutOfBoundsException if !isValid(x,y)
*/
void set(int x, int y, T element);
}

View File

@ -1,107 +0,0 @@
package inf101.v18.grid;
import java.util.Collection;
import java.util.List;
/**
* Represents a location within an {@link IArea}.
* <p>
* <em>Immutable:</em> Locations are immutable; i.e., a particular
* <code>ILocation</code> will always have the same x- and y-coordinates and
* cannot be changed. Methods that find neighbours (such as
* {@link #go(GridDirection)}) will return another <code>ILocation</code>.
* <p>
* <em>Area:</em> All {@link ILocation}s are tied to an {@link IArea}, thus they
* will know whether they are on the edge of the area (and not all neighbouring
* grid coordinates will be valid locations within the area) and other
* coordinate system properties that are determined by the {@link IArea} (e.g.,
* if the coordinate system wraps around like on the surface of a donut).
* <p>
* <em>Unique objects:</em> All {@link ILocation} in an {@link IArea} are
* unique. This means that <code>area.location(x,y) == area.location(x,y)</code>
* for all <em>x</em> and <em>y</em>, and that:
*
* <pre>
* // equality is reference equality for locations in the same area
* if (l1.getArea() == l2.getArea())
* assertEquals(l1.equals(l2), (l1 == l2));
* </pre>
*
*
* @author Anya Helene Bagge, UiB
*/
public interface ILocation extends IPosition {
/**
* Iterate over neighbours in eight directions.
* <p>
* (The iterator may yield fewer than eight locations if the current location is
* at the edge of its containing area.
*
* @return The neighbours in the eight cardinal and intercardinal directions
* ({@link GridDirection#NORTH}, @link GridDirection#SOUTH}, @link
* GridDirection#EAST}, @link GridDirection#WEST},
* {@link GridDirection#NORTHEAST}, @link
* GridDirection#NORTHWEST}, @link GridDirection#SOUTHEAST}, @link
* GridDirection#SOUTHWEST}, )
*/
Collection<ILocation> allNeighbours();
/**
* Checks whether you can go towards direction dir without going outside the
* area bounds
*
* @param dir
* @return True if go(dir) will succeed
*/
boolean canGo(GridDirection dir);
/**
* Iterate over north/south/east/west neighbours.
* <p>
* (The iterator may yield fewer than four locations if the current location is
* at the edge of its containing area.
*
* @return The neighbours in the four cardinal directions
* ({@link GridDirection#NORTH}, @link GridDirection#SOUTH}, @link
* GridDirection#EAST}, @link GridDirection#WEST}
*/
Collection<ILocation> cardinalNeighbours();
IArea getArea();
int getIndex();
/**
* Return the next location in direction dir.
* <p>
* This <em>does not</em> change the location object; rather it returns the
* ILocation you would end up at if you go in the given direction from this
* ILocation.
*
* @param dir
* A direction
* @return A neighbouring location
* @throws IndexOutOfBoundsException
* if !canGo(dir)
*/
ILocation go(GridDirection dir);
/**
* Find the grid cells between this location (exclusive) and another location
* (inclusive).
*
* This is a list of length {@link #gridDistanceTo(other)}, containing
* the cells that a chess queen would visit when moving to <code>other</code>.
* <p>
* Computes the maximum of the horizontal and the vertical distance. For
* example, to go from (0,0) to (3,5), you could go three steps SOUTHEAST and
* two steps SOUTH, so the {@link #gridDistanceTo(IPosition)} is 5.
*
* @param other
* @return Number of horizontal/vertical/diagonal (<em>queen</em>-like) steps to
* other
*/
List<ILocation> gridLineTo(ILocation other);
}

View File

@ -5,210 +5,172 @@ import java.util.function.Predicate;
import java.util.stream.Collectors;
public interface IMultiGrid<T> extends IGrid<List<T>> {
/**
* Add to the cell at the given location.
*
* @param loc
* The (x,y) position of the grid cell to get the contents of.
* @param element
* An element to be added to the cell.
* @throws IndexOutOfBoundsException
* if !isValid(loc)
*/
default void add(ILocation loc, T element) {
get(loc).add(element);
}
/**
* Add to the cell at the given location.
*
* @param loc The (x,y) position of the grid cell to get the contents of.
* @param element An element to be added to the cell.
* @throws IndexOutOfBoundsException if !isValid(loc)
*/
default void add(Location loc, T element) {
get(loc).add(element);
}
/**
* Add to the cell at the given x,y location.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos
* The (x,y) position of the grid cell to get the contents of.
* @param element
* An element to be added to the cell
* @throws IndexOutOfBoundsException
* if !isValid(x,y)
*/
default void add(int x, int y, T element) {
get(x, y).add(element);
}
/**
* Add to the cell at the given x,y location.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos The (x,y) position of the grid cell to get the contents of.
* @param element An element to be added to the cell
* @throws IndexOutOfBoundsException if !isValid(x,y)
*/
default void add(int x, int y, T element) {
get(x, y).add(element);
}
/**
* Check if a cell contains an element.
*
*
* @param loc
* The (x,y) position of the grid cell
* @param predicate
* Search predicate.
* @return true if an element matching the predicate was found
* @throws IndexOutOfBoundsException
* if !isValid(loc)
*/
default boolean contains(ILocation loc, Predicate<T> predicate) {
for (T t : get(loc)) {
if (predicate.test(t))
return true;
}
return false;
}
/**
* Check if a cell contains an element.
*
* @param loc The (x,y) position of the grid cell
* @param predicate Search predicate.
* @return true if an element matching the predicate was found
* @throws IndexOutOfBoundsException if !isValid(loc)
*/
default boolean contains(Location loc, Predicate<T> predicate) {
for (T t : get(loc)) {
if (predicate.test(t)) {
return true;
}
}
return false;
}
/**
* Check if a cell contains an element.
*
*
* @param loc
* The (x,y) position of the grid cell
* @param element
* An element to search for.
* @return true if element is at the given location
* @throws IndexOutOfBoundsException
* if !isValid(loc)
*/
default boolean contains(ILocation loc, T element) {
return get(loc).contains(element);
}
/**
* Check if a cell contains an element.
*
* @param loc The (x,y) position of the grid cell
* @param element An element to search for.
* @return true if element is at the given location
* @throws IndexOutOfBoundsException if !isValid(loc)
*/
default boolean contains(Location loc, T element) {
return get(loc).contains(element);
}
/**
* Check if a cell contains an element.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos
* The (x,y) position of the grid cell to get the contents of.
* @param predicate
* Search predicate.
* @return true if an element matching the predicate was found
* @throws IndexOutOfBoundsException
* if !isValid(x,y)
*/
default boolean contains(int x, int y, Predicate<T> predicate) {
return contains(this.getArea().location(x, y), predicate);
}
/**
* Check if a cell contains an element.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos The (x,y) position of the grid cell to get the contents of.
* @param predicate Search predicate.
* @return true if an element matching the predicate was found
* @throws IndexOutOfBoundsException if !isValid(x,y)
*/
default boolean contains(int x, int y, Predicate<T> predicate) {
return contains(this.getArea().location(x, y), predicate);
}
/**
* Check if a cell contains an element.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos
* The (x,y) position of the grid cell to get the contents of.
* @param element
* An element to search for.
* @return true if element is at the given location
* @throws IndexOutOfBoundsException
* if !isValid(x,y)
*/
default boolean contains(int x, int y, T element) {
return get(x, y).contains(element);
}
/**
* Check if a cell contains an element.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos The (x,y) position of the grid cell to get the contents of.
* @param element An element to search for.
* @return true if element is at the given location
* @throws IndexOutOfBoundsException if !isValid(x,y)
*/
default boolean contains(int x, int y, T element) {
return get(x, y).contains(element);
}
/**
* Get all elements in a cell that match the predicate
*
*
* @param loc
* The (x,y) position of the grid cell
* @param predicate
* Search predicate.
* @return true if an element matching the predicate was found
* @throws IndexOutOfBoundsException
* if !isValid(loc)
*/
default List<T> get(ILocation loc, Predicate<T> predicate) {
return get(loc).stream().filter(predicate).collect(Collectors.toList());
}
/**
* Get all elements in a cell that match the predicate
*
* @param loc The (x,y) position of the grid cell
* @param predicate Search predicate.
* @return true if an element matching the predicate was found
* @throws IndexOutOfBoundsException if !isValid(loc)
*/
default List<T> get(Location loc, Predicate<T> predicate) {
return get(loc).stream().filter(predicate).collect(Collectors.toList());
}
/**
* Check if a cell contains an element.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos
* The (x,y) position of the grid cell to get the contents of.
* @param predicate
* Search predicate.
* @return true if an element matching the predicate was found
* @throws IndexOutOfBoundsException
* if !isValid(x,y)
*/
default List<T> get(int x, int y, Predicate<T> predicate) {
return get(this.getArea().location(x, y), predicate);
}
/**
* Check if a cell contains an element.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos The (x,y) position of the grid cell to get the contents of.
* @param predicate Search predicate.
* @return true if an element matching the predicate was found
* @throws IndexOutOfBoundsException if !isValid(x,y)
*/
default List<T> get(int x, int y, Predicate<T> predicate) {
return get(this.getArea().location(x, y), predicate);
}
/**
* Remove an element from the cell at the given location.
*
* @param loc
* The location of the grid cell
* @param predicate
* Predicate which should be true for elements to be removed
* @return Number of elements removed
* @throws IndexOutOfBoundsException
* if !isValid(loc)
*/
default int remove(ILocation loc, Predicate<T> predicate) {
List<T> list = get(loc);
int s = list.size();
get(loc).removeIf(predicate);
return s - list.size();
}
/**
* Remove an element from the cell at the given location.
*
* @param loc The location of the grid cell
* @param predicate Predicate which should be true for elements to be removed
* @return Number of elements removed
* @throws IndexOutOfBoundsException if !isValid(loc)
*/
default int remove(Location loc, Predicate<T> predicate) {
List<T> list = get(loc);
int s = list.size();
get(loc).removeIf(predicate);
return s - list.size();
}
/**
* Remove an element from the cell at the given location.
*
* @param loc
* The location of the grid cell
* @param element
* An element to be removed from the cell.
* @return Number of elements removed
* @throws IndexOutOfBoundsException
* if !isValid(loc)
*/
default int remove(ILocation loc, T element) {
return get(loc).remove(element) ? 1 : 0;
}
/**
* Remove an element from the cell at the given location.
*
* @param loc The location of the grid cell
* @param element An element to be removed from the cell.
* @return Number of elements removed
* @throws IndexOutOfBoundsException if !isValid(loc)
*/
default int remove(Location loc, T element) {
return get(loc).remove(element) ? 1 : 0;
}
/**
* Remove an element from the cell at the given x,y location.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos
* The (x,y) position of the grid cell
* @param predicate
* Predicate which should be true for elements to be removed
* @return Number of elements removed
* @throws IndexOutOfBoundsException
* if !isValid(x,y)
*/
default int remove(int x, int y, Predicate<T> predicate) {
return remove(getArea().location(x, y), predicate);
}
/**
* Remove an element from the cell at the given x,y location.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos The (x,y) position of the grid cell
* @param predicate Predicate which should be true for elements to be removed
* @return Number of elements removed
* @throws IndexOutOfBoundsException if !isValid(x,y)
*/
default int remove(int x, int y, Predicate<T> predicate) {
return remove(getArea().location(x, y), predicate);
}
/**
* Remove an element from the cell at the given x,y location.
*
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos
* The (x,y) position of the grid cell
* @param element
* An element to be removed from the cell
* @return Number of elements removed
* @throws IndexOutOfBoundsException
* if !isValid(x,y)
*/
default int remove(int x, int y, T element) {
return get(x, y).remove(element) ? 1 : 0;
}
/**
* Remove an element from the cell at the given x,y location.
* <p>
* y must be greater than or equal to 0 and less than getHeight(). x must be
* greater than or equal to 0 and less than getWidth().
*
* @param pos The (x,y) position of the grid cell
* @param element An element to be removed from the cell
* @return Number of elements removed
* @throws IndexOutOfBoundsException if !isValid(x,y)
*/
default int remove(int x, int y, T element) {
return get(x, y).remove(element) ? 1 : 0;
}
}

View File

@ -2,82 +2,83 @@ package inf101.v18.grid;
public interface IPosition {
/**
* @param obj
* Another object
* @return true if obj is also an IPosition, and the x and y coordinates are
* equal
*/
@Override
boolean equals(Object obj);
/**
* @param obj Another object
* @return true if obj is also an IPosition, and the x and y coordinates are
* equal
*/
@Override
boolean equals(Object obj);
/**
* Find the Euclidian distance between the midpoint of this position and another
* position.
*
* The distance is computed with the Pythagorean formula, with the assumption
* that the grid cells are square shaped with <em>width</em> = <em>height</em> =
* 1. For example, the distance from (0,0) to (3,5) is (3²+5²) = 5.83.
*
* @param other
* @return Euclidian distance between this and other's midpoints
*/
double geometricDistanceTo(IPosition other);
/**
* Find the Euclidian distance between the midpoint of this position and another
* position.
* <p>
* The distance is computed with the Pythagorean formula, with the assumption
* that the grid cells are square shaped with <em>width</em> = <em>height</em> =
* 1. For example, the distance from (0,0) to (3,5) is (3²+5²) = 5.83.
*
* @param other
* @return Euclidian distance between this and other's midpoints
*/
double geometricDistanceTo(IPosition other);
/**
* Gets the x-coordinate
*
* @return
*/
int getX();
/**
* Gets the x-coordinate
*
* @return
*/
int getX();
/**
* Gets the y-coordinate
*
* @return
*/
int getY();
/**
* Gets the y-coordinate
*
* @return
*/
int getY();
/**
* Find the distance in grid cells to another location.
*
* This is different from {@link #stepDistanceTo(IPosition)} in that diagonal
* steps are allowed, and is the same as the number of steps a queen would take
* on a chess board.
* <p>
* Computes the maximum of the horizontal and the vertical distance. For
* example, to go from (0,0) to (3,5), you could go three steps SOUTHEAST and
* two steps SOUTH, so the {@link #gridDistanceTo(IPosition)} is 5.
*
* @param other
* @return Number of horizontal/vertical/diagonal (<em>queen</em>-like) steps to
* other
*/
int gridDistanceTo(IPosition other);
/**
* Find the distance in grid cells to another location.
* <p>
* This is different from {@link #stepDistanceTo(IPosition)} in that diagonal
* steps are allowed, and is the same as the number of steps a queen would take
* on a chess board.
* <p>
* Computes the maximum of the horizontal and the vertical distance. For
* example, to go from (0,0) to (3,5), you could go three steps SOUTHEAST and
* two steps SOUTH, so the {@link #gridDistanceTo(IPosition)} is 5.
*
* @param other
* @return Number of horizontal/vertical/diagonal (<em>queen</em>-like) steps to
* other
*/
int gridDistanceTo(IPosition other);
@Override
int hashCode();
@Override
int hashCode();
/**
* Find the number of non-diagonal steps needed to go from this location the
* other location.
*
* This is different from {@link #gridDistanceTo(IPosition)} in that only
* non-diagonal steps are allowed, and is the same as the number of steps a rook
* would take on a chess board.
* <p>
* Computes the distance to another location as the sum of the absolute
* difference between the x- and y-coordinates. For example, to go from (0,0) to
* (3,5), you would need to go three steps EAST and five steps SOUTH, so the
* {@link #stepDistanceTo(IPosition)} is 8.
*
* @param other
* @return Number of horizontal/vertical (<em>rook</em>-like) steps to other
*/
int stepDistanceTo(IPosition other);
/**
* Find the number of non-diagonal steps needed to go from this location the
* other location.
* <p>
* This is different from {@link #gridDistanceTo(IPosition)} in that only
* non-diagonal steps are allowed, and is the same as the number of steps a rook
* would take on a chess board.
* <p>
* Computes the distance to another location as the sum of the absolute
* difference between the x- and y-coordinates. For example, to go from (0,0) to
* (3,5), you would need to go three steps EAST and five steps SOUTH, so the
* {@link #stepDistanceTo(IPosition)} is 8.
*
* @param other
* @return Number of horizontal/vertical (<em>rook</em>-like) steps to other
*/
int stepDistanceTo(IPosition other);
/** @return Position as a string, "(x,y)" */
@Override
String toString();
/**
* @return Position as a string, "(x,y)"
*/
@Override
String toString();
}

View File

@ -0,0 +1,104 @@
package inf101.v18.grid;
import java.util.Collection;
import java.util.List;
/**
* Represents a location within an {@link IArea}.
* <p>
* <em>Immutable:</em> Locations are immutable; i.e., a particular
* <code>ILocation</code> will always have the same x- and y-coordinates and
* cannot be changed. Methods that find neighbours (such as
* {@link #go(GridDirection)}) will return another <code>ILocation</code>.
* <p>
* <em>Area:</em> All {@link Location}s are tied to an {@link IArea}, thus they
* will know whether they are on the edge of the area (and not all neighbouring
* grid coordinates will be valid locations within the area) and other
* coordinate system properties that are determined by the {@link IArea} (e.g.,
* if the coordinate system wraps around like on the surface of a donut).
* <p>
* <em>Unique objects:</em> All {@link Location} in an {@link IArea} are
* unique. This means that <code>area.location(x,y) == area.location(x,y)</code>
* for all <em>x</em> and <em>y</em>, and that:
*
* <pre>
* // equality is reference equality for locations in the same area
* if (l1.getArea() == l2.getArea())
* assertEquals(l1.equals(l2), (l1 == l2));
* </pre>
*
* @author Anya Helene Bagge, UiB
*/
public interface Location extends IPosition {
/**
* Iterate over neighbours in eight directions.
* <p>
* (The iterator may yield fewer than eight locations if the current location is
* at the edge of its containing area.
*
* @return The neighbours in the eight cardinal and intercardinal directions
* ({@link GridDirection#NORTH}, @link GridDirection#SOUTH}, @link
* GridDirection#EAST}, @link GridDirection#WEST},
* {@link GridDirection#NORTHEAST}, @link
* GridDirection#NORTHWEST}, @link GridDirection#SOUTHEAST}, @link
* GridDirection#SOUTHWEST}, )
*/
Collection<Location> allNeighbours();
/**
* Checks whether you can go towards direction dir without going outside the
* area bounds
*
* @param dir
* @return True if go(dir) will succeed
*/
boolean canGo(GridDirection dir);
/**
* Iterate over north/south/east/west neighbours.
* <p>
* (The iterator may yield fewer than four locations if the current location is
* at the edge of its containing area.
*
* @return The neighbours in the four cardinal directions
* ({@link GridDirection#NORTH}, @link GridDirection#SOUTH}, @link
* GridDirection#EAST}, @link GridDirection#WEST}
*/
Collection<Location> cardinalNeighbours();
IArea getArea();
int getIndex();
/**
* Return the next location in direction dir.
* <p>
* This <em>does not</em> change the location object; rather it returns the
* ILocation you would end up at if you go in the given direction from this
* ILocation.
*
* @param dir A direction
* @return A neighbouring location
* @throws IndexOutOfBoundsException if !canGo(dir)
*/
Location go(GridDirection dir);
/**
* Find the grid cells between this location (exclusive) and another location
* (inclusive).
* <p>
* This is a list of length {@link #gridDistanceTo(other)}, containing
* the cells that a chess queen would visit when moving to <code>other</code>.
* <p>
* Computes the maximum of the horizontal and the vertical distance. For
* example, to go from (0,0) to (3,5), you could go three steps SOUTHEAST and
* two steps SOUTH, so the {@link #gridDistanceTo(IPosition)} is 5.
*
* @param other
* @return Number of horizontal/vertical/diagonal (<em>queen</em>-like) steps to
* other
*/
List<Location> gridLineTo(Location other);
}

View File

@ -5,12 +5,12 @@ import java.util.List;
public class MultiGrid<T> extends MyGrid<List<T>> implements IMultiGrid<T> {
public MultiGrid(IArea area) {
super(area, (l) -> new ArrayList<T>());
}
public MultiGrid(IArea area) {
super(area, (l) -> new ArrayList<T>());
}
public MultiGrid(int width, int height) {
super(width, height, (l) -> new ArrayList<T>());
}
public MultiGrid(int width, int height) {
super(width, height, (l) -> new ArrayList<T>());
}
}

View File

@ -6,216 +6,219 @@ import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
/** A Grid contains a set of cells in a square 2D matrix. */
/**
* A Grid contains a set of cells in a square 2D matrix.
*/
public class MyGrid<T> implements IGrid<T> {
private final IArea area;
private final List<T> cells;
private final IArea area;
private final List<T> cells;
/**
* Construct a grid with the given dimensions.
*
* The initialiser function will be called with the (x,y) position of an
* element, and is expected to return the element to place at that position. For
* example:
*
* <pre>
* // fill all cells with the position as a string (e.g., "(2,2)")
* new MyGrid(10, 10, ((x, y) -> String.format("(%d,%d)", x, y));
* </pre>
*
* @param area
* @param initialiser
* The initialiser function
*/
public MyGrid(IArea area, Function<ILocation, T> initialiser) {
if (area == null || initialiser == null) {
throw new IllegalArgumentException();
}
/**
* Construct a grid with the given dimensions.
* <p>
* The initialiser function will be called with the (x,y) position of an
* element, and is expected to return the element to place at that position. For
* example:
*
* <pre>
* // fill all cells with the position as a string (e.g., "(2,2)")
* new MyGrid(10, 10, ((x, y) -> String.format("(%d,%d)", x, y));
* </pre>
*
* @param area
* @param initialiser The initialiser function
*/
public MyGrid(IArea area, Function<Location, T> initialiser) {
if (area == null || initialiser == null) {
throw new IllegalArgumentException();
}
this.area = area;
this.cells = new ArrayList<T>(area.getSize());
for (ILocation loc : area) {
cells.add(initialiser.apply(loc));
}
}
this.area = area;
this.cells = new ArrayList<T>(area.getSize());
for (Location loc : area) {
cells.add(initialiser.apply(loc));
}
}
/**
* Construct a grid with the given dimensions.
*
* @param area
* @param initElement
* What the cells should initially hold (possibly null)
*/
public MyGrid(IArea area, T initElement) {
if (area == null) {
throw new IllegalArgumentException();
}
/**
* Construct a grid with the given dimensions.
*
* @param area
* @param initElement What the cells should initially hold (possibly null)
*/
public MyGrid(IArea area, T initElement) {
if (area == null) {
throw new IllegalArgumentException();
}
this.area = area;
this.cells = new ArrayList<T>(area.getSize());
for (int i = 0; i < area.getSize(); ++i) {
cells.add(initElement);
}
}
this.area = area;
this.cells = new ArrayList<T>(area.getSize());
for (int i = 0; i < area.getSize(); ++i) {
cells.add(initElement);
}
}
/**
* Construct a grid with the given dimensions.
*
* The initialiser function will be called with the (x,y) position of an
* element, and is expected to return the element to place at that position. For
* example:
*
* <pre>
* // fill all cells with the position as a string (e.g., "(2,2)")
* new MyGrid(10, 10, ((x, y) -> String.format("(%d,%d)", x, y));
* </pre>
*
* @param width
* @param height
* @param initialiser
* The initialiser function
*/
public MyGrid(int width, int height, Function<ILocation, T> initialiser) {
this(new RectArea(width, height), initialiser);
}
/**
* Construct a grid with the given dimensions.
* <p>
* The initialiser function will be called with the (x,y) position of an
* element, and is expected to return the element to place at that position. For
* example:
*
* <pre>
* // fill all cells with the position as a string (e.g., "(2,2)")
* new MyGrid(10, 10, ((x, y) -> String.format("(%d,%d)", x, y));
* </pre>
*
* @param width
* @param height
* @param initialiser The initialiser function
*/
public MyGrid(int width, int height, Function<Location, T> initialiser) {
this(new RectArea(width, height), initialiser);
}
/**
* Construct a grid with the given dimensions.
*
* @param width
* @param height
* @param initElement
* What the cells should initially hold (possibly null)
*/
public MyGrid(int width, int height, T initElement) {
this(new RectArea(width, height), initElement);
}
/**
* Construct a grid with the given dimensions.
*
* @param width
* @param height
* @param initElement What the cells should initially hold (possibly null)
*/
public MyGrid(int width, int height, T initElement) {
this(new RectArea(width, height), initElement);
}
@Override
public IGrid<T> copy() {
return new MyGrid<>(getWidth(), getHeight(), (l) -> get(l));
}
@Override
public IGrid<T> copy() {
return new MyGrid<>(getWidth(), getHeight(), (l) -> get(l));
}
@Override
public Stream<T> elementParallelStream() {
return cells.parallelStream();
}
@Override
public Stream<T> elementParallelStream() {
return cells.parallelStream();
}
@Override
public Stream<T> elementStream() {
return cells.stream();
}
@Override
public Stream<T> elementStream() {
return cells.stream();
}
@Override
public void fill(Function<ILocation, T> initialiser) {
if (initialiser == null)
throw new NullPointerException();
@Override
public void fill(Function<Location, T> initialiser) {
if (initialiser == null) {
throw new NullPointerException();
}
for (int i = 0; i < area.getSize(); i++) {
cells.set(i, initialiser.apply(area.fromIndex(i)));
}
}
for (int i = 0; i < area.getSize(); i++) {
cells.set(i, initialiser.apply(area.fromIndex(i)));
}
}
@Override
public void fill(T element) {
for (int i = 0; i < area.getSize(); i++) {
cells.set(i, element);
}
}
@Override
public void fill(T element) {
for (int i = 0; i < area.getSize(); i++) {
cells.set(i, element);
}
}
@Override
public T get(ILocation loc) {
if (loc.getArea() == area)
return cells.get(loc.getIndex());
else
return cells.get(area.toIndex(loc.getX(), loc.getY()));
}
@Override
public T get(Location loc) {
if (loc.getArea() == area) {
return cells.get(loc.getIndex());
} else {
return cells.get(area.toIndex(loc.getX(), loc.getY()));
}
}
@Override
public T get(int x, int y) {
return cells.get(area.toIndex(x, y));
}
@Override
public T get(int x, int y) {
return cells.get(area.toIndex(x, y));
}
@Override
public IArea getArea() {
return area;
}
@Override
public IArea getArea() {
return area;
}
@Override
public int getHeight() {
return area.getHeight();
}
@Override
public int getHeight() {
return area.getHeight();
}
@Override
public T getOrDefault(ILocation loc, T defaultResult) {
if (loc.getArea() == area) {
T r = cells.get(loc.getIndex());
if (r != null)
return r;
else
return defaultResult;
} else {
return getOrDefault(loc.getX(), loc.getY(), defaultResult);
}
}
@Override
public T getOrDefault(Location loc, T defaultResult) {
if (loc.getArea() == area) {
T r = cells.get(loc.getIndex());
if (r != null) {
return r;
} else {
return defaultResult;
}
} else {
return getOrDefault(loc.getX(), loc.getY(), defaultResult);
}
}
@Override
public T getOrDefault(int x, int y, T defaultResult) {
T r = null;
if (isValid(x, y))
r = get(x, y);
if (r != null)
return r;
else
return defaultResult;
}
@Override
public T getOrDefault(int x, int y, T defaultResult) {
T r = null;
if (isValid(x, y)) {
r = get(x, y);
}
if (r != null) {
return r;
} else {
return defaultResult;
}
}
@Override
public int getWidth() {
return area.getWidth();
}
@Override
public int getWidth() {
return area.getWidth();
}
@Override
public boolean isValid(ILocation loc) {
return loc.getArea() == area || area.contains(loc.getX(), loc.getY());
}
@Override
public boolean isValid(Location loc) {
return loc.getArea() == area || area.contains(loc.getX(), loc.getY());
}
@Override
public boolean isValid(int x, int y) {
return area.contains(x, y);
}
@Override
public boolean isValid(int x, int y) {
return area.contains(x, y);
}
@Override
public Iterator<T> iterator() {
return cells.iterator();
}
@Override
public Iterator<T> iterator() {
return cells.iterator();
}
@Override
public Stream<ILocation> locationParallelStream() {
return area.parallelStream();
}
@Override
public Stream<Location> locationParallelStream() {
return area.parallelStream();
}
@Override
public Iterable<ILocation> locations() {
return area;
}
@Override
public Iterable<Location> locations() {
return area;
}
@Override
public Stream<ILocation> locationStream() {
return area.stream();
}
@Override
public Stream<Location> locationStream() {
return area.stream();
}
@Override
public void set(ILocation loc, T element) {
if (loc.getArea() == area) {
cells.set(loc.getIndex(), element);
} else {
set(loc.getX(), loc.getY(), element);
}
}
@Override
public void set(Location loc, T element) {
if (loc.getArea() == area) {
cells.set(loc.getIndex(), element);
} else {
set(loc.getX(), loc.getY(), element);
}
}
@Override
public void set(int x, int y, T elem) {
cells.set(area.toIndex(x, y), elem);
}
@Override
public void set(int x, int y, T elem) {
cells.set(area.toIndex(x, y), elem);
}
}

View File

@ -2,9 +2,21 @@
## Changes from the Cellular Automaton version
* If you look at `MyGrid.java`, you will notice that it no longer uses `IList<T>`/`MyList<T>` to hold the grid cells, and both `IList.java` and `MyList.java` have been removed. Instead we use standard built-in Java lists, with the `List<T>` interface (and `ArrayList<T>` as the class for new list objects).
* This saves us the work of maintaining and improving our own list, and makes it immediately compatible with useful standard Java library operations on lists.
* In general, you should always use built-in APIs (such as the Java Collections API which provides lists and similar) when available. Not only does it save time, but they're likely to be much better tested (and probably better designed) than you can do yourself, so they're less likely to have, e.g., stupid bugs that only show up in corner cases. You may also get better performance.
* You might want to do things yourself if you want to learn how stuff works; also, in some cases, there may not be a suitable API available or the API doesn't really fully fit with what we want to do. While Java has one-dimensional lists and arrays, it doesn't really have built-in classes for grids, so we're making our own.
* An alternative to IGrid/MyGrid would be to use two-dimensional arrays but these aren't *actually* two-dimensional arrays, but rather arrays-of-arrays, which makes them fit less well with the concept of a “grid” (the same goes for making a list of lists). In addition to being a bit inconvenient, they're also much less efficient in use and they won't let us do useful things like “please give me the cell to the north of this cell” or “please give me all cells neighbouring this cell”.
* If you look at `MyGrid.java`, you will notice that it no longer uses `IList<T>`/`MyList<T>` to hold the grid cells,
and both `IList.java` and `MyList.java` have been removed. Instead we use standard built-in Java lists, with
the `List<T>` interface (and `ArrayList<T>` as the class for new list objects).
* This saves us the work of maintaining and improving our own list, and makes it immediately compatible with useful
standard Java library operations on lists.
* In general, you should always use built-in APIs (such as the Java Collections API which provides lists and
similar) when available. Not only does it save time, but they're likely to be much better tested (and probably
better designed) than you can do yourself, so they're less likely to have, e.g., stupid bugs that only show up in
corner cases. You may also get better performance.
* You might want to do things yourself if you want to learn how stuff works; also, in some cases, there may not be a
suitable API available or the API doesn't really fully fit with what we want to do. While Java has
one-dimensional lists and arrays, it doesn't really have built-in classes for grids, so we're making our own.
* An alternative to IGrid/MyGrid would be to use two-dimensional arrays but these aren't *actually*
two-dimensional arrays, but rather arrays-of-arrays, which makes them fit less well with the concept of a “grid” (
the same goes for making a list of lists). In addition to being a bit inconvenient, they're also much less
efficient in use and they won't let us do useful things like “please give me the cell to the north of this cell”
or “please give me all cells neighbouring this cell”.

View File

@ -8,334 +8,338 @@ import java.util.List;
import java.util.stream.Stream;
public class RectArea implements IArea {
/** A class to represent an (x, y)-location on a grid. */
class Location implements ILocation {
/**
* A class to represent an (x, y)-location on a grid.
*/
class Location implements inf101.v18.grid.Location {
/** value of the x-coordinate */
protected final int x;
/** value of the y-coordinate */
protected final int y;
protected final int idx;
protected final int edgeMask;
/**
* value of the x-coordinate
*/
protected final int x;
/**
* value of the y-coordinate
*/
protected final int y;
protected final int idx;
protected final int edgeMask;
/**
* Main constructor. Initializes a new {@link #Location} objects with the
* corresponding values of x and y.
*
* @param x
* X coordinate
* @param y
* Y coordinate
* @param idx
* 1-dimensional index
* @param edgeMask
* mask with bits {@link RectArea#N}, {@link RectArea#S},
* {@link RectArea#E}, {@link RectArea#W} set if we're on the
* corresponding edge of the area
*/
Location(int x, int y, int idx, int edgeMask) {
this.x = x;
this.y = y;
this.idx = idx;
this.edgeMask = edgeMask;
}
/**
* Main constructor. Initializes a new {@link #Location} objects with the
* corresponding values of x and y.
*
* @param x X coordinate
* @param y Y coordinate
* @param idx 1-dimensional index
* @param edgeMask mask with bits {@link RectArea#N}, {@link RectArea#S},
* {@link RectArea#E}, {@link RectArea#W} set if we're on the
* corresponding edge of the area
*/
Location(int x, int y, int idx, int edgeMask) {
this.x = x;
this.y = y;
this.idx = idx;
this.edgeMask = edgeMask;
}
@Override
public Collection<ILocation> allNeighbours() {
Collection<ILocation> ns = new ArrayList<>(8);
for (GridDirection d : GridDirection.EIGHT_DIRECTIONS) {
if (canGo(d))
ns.add(go(d));
}
return ns;
}
@Override
public Collection<inf101.v18.grid.Location> allNeighbours() {
Collection<inf101.v18.grid.Location> ns = new ArrayList<>(8);
for (GridDirection d : GridDirection.EIGHT_DIRECTIONS) {
if (canGo(d)) {
ns.add(go(d));
}
}
return ns;
}
@Override
public boolean canGo(GridDirection dir) {
return (edgeMask & dir.getMask()) == 0;
}
@Override
public boolean canGo(GridDirection dir) {
return (edgeMask & dir.getMask()) == 0;
}
@Override
public Collection<ILocation> cardinalNeighbours() {
Collection<ILocation> ns = new ArrayList<>(4);
for (GridDirection d : GridDirection.FOUR_DIRECTIONS) {
if (canGo(d))
ns.add(go(d));
}
return ns;
}
@Override
public Collection<inf101.v18.grid.Location> cardinalNeighbours() {
Collection<inf101.v18.grid.Location> ns = new ArrayList<>(4);
for (GridDirection d : GridDirection.FOUR_DIRECTIONS) {
if (canGo(d)) {
ns.add(go(d));
}
}
return ns;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof IPosition)) {
return false;
}
IPosition other = (IPosition) obj;
if (x != other.getX()) {
return false;
}
return y == other.getY();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof IPosition)) {
return false;
}
IPosition other = (IPosition) obj;
if (x != other.getX()) {
return false;
}
return y == other.getY();
}
@Override
public double geometricDistanceTo(IPosition other) {
return Math.sqrt(Math.pow(this.x - other.getX(), 2) + Math.pow(this.y - other.getY(), 2));
}
@Override
public double geometricDistanceTo(IPosition other) {
return Math.sqrt(Math.pow(this.x - other.getX(), 2) + Math.pow(this.y - other.getY(), 2));
}
@Override
public IArea getArea() {
return RectArea.this;
}
@Override
public IArea getArea() {
return RectArea.this;
}
@Override
public int getIndex() {
return idx;
}
@Override
public int getIndex() {
return idx;
}
@Override
public int getX() {
return x;
}
@Override
public int getX() {
return x;
}
@Override
public int getY() {
return y;
}
@Override
public int getY() {
return y;
}
@Override
public ILocation go(GridDirection dir) {
return location(x + dir.getDx(), y + dir.getDy());
}
@Override
public inf101.v18.grid.Location go(GridDirection dir) {
return location(x + dir.getDx(), y + dir.getDy());
}
@Override
public int gridDistanceTo(IPosition other) {
return Math.max(Math.abs(this.x - other.getX()), Math.abs(this.y - other.getY()));
}
@Override
public int gridDistanceTo(IPosition other) {
return Math.max(Math.abs(this.x - other.getX()), Math.abs(this.y - other.getY()));
}
@Override
public List<ILocation> gridLineTo(ILocation other) {
if (!contains(other))
throw new IllegalArgumentException();
int distX = other.getX() - x;
int distY = other.getY() - y;
int length = Math.max(Math.abs(distX), Math.abs(distY));
List<ILocation> line = new ArrayList<>(length);
if (length == 0)
return line;
double dx = (double) distX / (double) length;
double dy = (double) distY / (double) length;
// System.out.printf("dx=%g, dy=%g, length=%d%n", dx, dy, length);
for (int i = 1; i <= length; i++) {
line.add(location(x + (int) Math.round(dx * i), y + (int) Math.round(dy * i)));
}
return line;
}
@Override
public List<inf101.v18.grid.Location> gridLineTo(inf101.v18.grid.Location other) {
if (!contains(other)) {
throw new IllegalArgumentException();
}
int distX = other.getX() - x;
int distY = other.getY() - y;
int length = Math.max(Math.abs(distX), Math.abs(distY));
List<inf101.v18.grid.Location> line = new ArrayList<>(length);
if (length == 0) {
return line;
}
double dx = (double) distX / (double) length;
double dy = (double) distY / (double) length;
// System.out.printf("dx=%g, dy=%g, length=%d%n", dx, dy, length);
for (int i = 1; i <= length; i++) {
line.add(location(x + (int) Math.round(dx * i), y + (int) Math.round(dy * i)));
}
return line;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public int stepDistanceTo(IPosition other) {
return Math.abs(this.x - other.getX()) + Math.abs(this.y - other.getY());
}
@Override
public int stepDistanceTo(IPosition other) {
return Math.abs(this.x - other.getX()) + Math.abs(this.y - other.getY());
}
@Override
public String toString() {
return "(x=" + x + ",y=" + y + ")";
}
@Override
public String toString() {
return "(x=" + x + ",y=" + y + ")";
}
}
}
protected final int width;
protected final int height;
protected final int size;
protected final List<ILocation> locs;
protected final int width;
protected final int height;
protected final int size;
protected final List<inf101.v18.grid.Location> locs;
protected final boolean hWrap, vWrap;
protected final boolean hWrap, vWrap;
public RectArea(int width, int height) {
this(width, height, false, false);
}
public RectArea(int width, int height) {
this(width, height, false, false);
}
private RectArea(int width, int height, boolean horizWrap, boolean vertWrap) {
if (width < 1 || height < 1) {
throw new IllegalArgumentException("Width and height must be positive");
}
this.hWrap = horizWrap;
this.vWrap = vertWrap;
this.width = width;
this.height = height;
this.size = width * height;
List<ILocation> l = new ArrayList<>(size);
for (int y = 0, i = 0; y < height; y++) {
// set N or S bits if we're on the northern or southern edge
int edge = (y == 0 ? GridDirection.NORTH.getMask() : 0)
| (y == height - 1 ? GridDirection.SOUTH.getMask() : 0);
for (int x = 0; x < width; x++, i++) {
// set W or E bits if we're on the western or eastern edge
int e = edge | (x == 0 ? GridDirection.WEST.getMask() : 0)
| (x == width - 1 ? GridDirection.EAST.getMask() : 0);
l.add(new Location(x, y, i, e));
}
}
locs = Collections.unmodifiableList(l);
}
private RectArea(int width, int height, boolean horizWrap, boolean vertWrap) {
if (width < 1 || height < 1) {
throw new IllegalArgumentException("Width and height must be positive");
}
this.hWrap = horizWrap;
this.vWrap = vertWrap;
this.width = width;
this.height = height;
this.size = width * height;
List<inf101.v18.grid.Location> l = new ArrayList<>(size);
for (int y = 0, i = 0; y < height; y++) {
// set N or S bits if we're on the northern or southern edge
int edge = (y == 0 ? GridDirection.NORTH.getMask() : 0)
| (y == height - 1 ? GridDirection.SOUTH.getMask() : 0);
for (int x = 0; x < width; x++, i++) {
// set W or E bits if we're on the western or eastern edge
int e = edge | (x == 0 ? GridDirection.WEST.getMask() : 0)
| (x == width - 1 ? GridDirection.EAST.getMask() : 0);
l.add(new Location(x, y, i, e));
}
}
locs = Collections.unmodifiableList(l);
}
/**
* @param x
* X-coordinate
* @return The same x, wrapped to wrapX(x)
* @throws IndexOutOfBoundsException
* if coordinate is out of range, and wrapping is not enabled
*/
protected int checkX(int x) {
x = wrapX(x);
if (x < 0 || x >= width) {
throw new IndexOutOfBoundsException("x=" + x);
}
/**
* @param x X-coordinate
* @return The same x, wrapped to wrapX(x)
* @throws IndexOutOfBoundsException if coordinate is out of range, and wrapping is not enabled
*/
protected int checkX(int x) {
x = wrapX(x);
if (x < 0 || x >= width) {
throw new IndexOutOfBoundsException("x=" + x);
}
return x;
}
return x;
}
/**
* @param y
* Y-coordinate
* @return The same y, wrapped to wrapY(y)
* @throws IndexOutOfBoundsException
* if coordinate is out of range, and wrapping is not enabled
*/
protected int checkY(int y) {
y = wrapY(y);
if (y < 0 || y >= height) {
throw new IndexOutOfBoundsException("y=" + y);
}
return y;
}
/**
* @param y Y-coordinate
* @return The same y, wrapped to wrapY(y)
* @throws IndexOutOfBoundsException if coordinate is out of range, and wrapping is not enabled
*/
protected int checkY(int y) {
y = wrapY(y);
if (y < 0 || y >= height) {
throw new IndexOutOfBoundsException("y=" + y);
}
return y;
}
@Override
public boolean contains(int x, int y) {
x = wrapX(x);
y = wrapY(y);
return x >= 0 && x < width && y >= 0 && y < height;
}
@Override
public boolean contains(int x, int y) {
x = wrapX(x);
y = wrapY(y);
return x >= 0 && x < width && y >= 0 && y < height;
}
@Override
public boolean contains(IPosition pos) {
return (pos instanceof ILocation && ((ILocation) pos).getArea() == this) || contains(pos.getX(), pos.getY());
}
@Override
public boolean contains(IPosition pos) {
return (pos instanceof inf101.v18.grid.Location && ((inf101.v18.grid.Location) pos).getArea() == this) || contains(pos.getX(), pos.getY());
}
@Override
public ILocation fromIndex(int i) {
if (i >= 0 && i < size)
return locs.get(i);
else
throw new IndexOutOfBoundsException("" + i);
}
@Override
public inf101.v18.grid.Location fromIndex(int i) {
if (i >= 0 && i < size) {
return locs.get(i);
} else {
throw new IndexOutOfBoundsException("" + i);
}
}
@Override
public int getHeight() {
return height;
}
@Override
public int getHeight() {
return height;
}
@Override
public int getSize() {
return size;
}
@Override
public int getSize() {
return size;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getWidth() {
return width;
}
@Override
public Iterator<ILocation> iterator() {
return locs.iterator();
}
@Override
public Iterator<inf101.v18.grid.Location> iterator() {
return locs.iterator();
}
@Override
public ILocation location(int x, int y) {
if (x < 0 || x >= width || y < 0 || y >= height)
throw new IndexOutOfBoundsException("(" + x + "," + y + ")");
int i = x + y * width;
return locs.get(i);
}
@Override
public inf101.v18.grid.Location location(int x, int y) {
if (x < 0 || x >= width || y < 0 || y >= height) {
throw new IndexOutOfBoundsException("(" + x + "," + y + ")");
}
int i = x + y * width;
return locs.get(i);
}
@Override
public List<ILocation> locations() {
return locs; // (OK since locs has been through Collections.unmodifiableList())
}
@Override
public List<inf101.v18.grid.Location> locations() {
return locs; // (OK since locs has been through Collections.unmodifiableList())
}
@Override
public Iterable<ILocation> neighboursOf(ILocation pos) {
return pos.allNeighbours();
}
@Override
public Iterable<inf101.v18.grid.Location> neighboursOf(inf101.v18.grid.Location pos) {
return pos.allNeighbours();
}
@Override
public Stream<ILocation> parallelStream() {
return locs.parallelStream();
}
@Override
public Stream<inf101.v18.grid.Location> parallelStream() {
return locs.parallelStream();
}
@Override
public Stream<ILocation> stream() {
return locs.stream();
}
@Override
public Stream<inf101.v18.grid.Location> stream() {
return locs.stream();
}
@Override
public int toIndex(int x, int y) {
x = checkX(x);
y = checkY(y);
return y * width + x;
}
@Override
public int toIndex(int x, int y) {
x = checkX(x);
y = checkY(y);
return y * width + x;
}
@Override
public String toString() {
return "RectArea [width=" + width + ", height=" + height + ", hWrap=" + hWrap + ", vWrap=" + vWrap + "]";
}
@Override
public String toString() {
return "RectArea [width=" + width + ", height=" + height + ", hWrap=" + hWrap + ", vWrap=" + vWrap + "]";
}
@Override
public boolean wrapsHorizontally() {
return hWrap;
}
@Override
public boolean wrapsHorizontally() {
return hWrap;
}
@Override
public boolean wrapsVertically() {
return vWrap;
}
@Override
public boolean wrapsVertically() {
return vWrap;
}
protected int wrapX(int x) {
if (hWrap) {
if (x < 0) {
return getWidth() + x % getWidth();
} else {
return x % getWidth();
}
} else {
return x;
}
}
protected int wrapX(int x) {
if (hWrap) {
if (x < 0) {
return getWidth() + x % getWidth();
} else {
return x % getWidth();
}
} else {
return x;
}
}
protected int wrapY(int y) {
if (hWrap) {
if (y < 0) {
return getHeight() + y % getHeight();
} else {
return y % getHeight();
}
} else {
return y;
}
}
protected int wrapY(int y) {
if (hWrap) {
if (y < 0) {
return getHeight() + y % getHeight();
} else {
return y % getHeight();
}
} else {
return y;
}
}
}

View File

@ -4,29 +4,29 @@ import java.util.Arrays;
import java.util.List;
public class AppInfo {
/**
* Your application name.
*/
public static final String APP_NAME = "Not Really Rogue";
/**
* Your name.
*/
public static final String APP_DEVELOPER = "Kristian Knarvik (kkn015)";
/**
* A short description.
*/
public static final String APP_DESCRIPTION = "Implementasjon av inf101.v18.sem1";
/**
* List of extra credits (e.g. for media sources)
*/
public static final List<String> APP_EXTRA_CREDITS = Arrays.asList(
"Sounds by Mike Koenig, Stephan Schutze and Mark DiAngelo",
"Thanks to Stian Johannesen Husum and Henning Berge for exchanging ideas"
);
/**
* Help text. Could be used for an in-game help page, perhaps.
* <p>
* Use <code>\n</code> for new lines, <code>\f<code> between pages (if multi-page).
*/
public static final String APP_HELP = "";
/**
* Your application name.
*/
public static final String APP_NAME = "Not Really Rogue";
/**
* Your name.
*/
public static final String APP_DEVELOPER = "Kristian Knarvik (kkn015)";
/**
* A short description.
*/
public static final String APP_DESCRIPTION = "Implementasjon av inf101.v18.sem1";
/**
* List of extra credits (e.g. for media sources)
*/
public static final List<String> APP_EXTRA_CREDITS = Arrays.asList(
"Sounds by Mike Koenig, Stephan Schutze and Mark DiAngelo",
"Thanks to Stian Johannesen Husum and Henning Berge for exchanging ideas"
);
/**
* Help text. Could be used for an in-game help page, perhaps.
* <p>
* Use <code>\n</code> for new lines, <code>\f<code> between pages (if multi-page).
*/
public static final String APP_HELP = "";
}

View File

@ -3,7 +3,9 @@ package inf101.v18.rogue101;
import javafx.application.Application;
public class Launcher {
public static void main(String[] args) {
Application.launch(Main.class, args);
}
}

View File

@ -1,13 +1,10 @@
package inf101.v18.rogue101;
import java.io.PrintWriter;
import java.io.StringWriter;
import inf101.v18.gfx.Screen;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.textmode.Printer;
import inf101.v18.gfx.textmode.TextMode;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.game.RogueGame;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
@ -17,112 +14,118 @@ import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.PrintWriter;
import java.io.StringWriter;
public class Main extends Application {
// you might want to tune these options
public static final boolean MAIN_USE_BACKGROUND_GRID = false;
public static final boolean MAP_AUTO_SCALE_ITEM_DRAW = true;
public static final boolean MAP_DRAW_ONLY_DIRTY_CELLS = false;
public static final TextMode MAIN_TEXT_MODE = TextMode.MODE_80X25;
public static final boolean DEBUG_TIME = false;
// you might want to tune these options
public static final boolean MAIN_USE_BACKGROUND_GRID = false;
public static final boolean MAP_AUTO_SCALE_ITEM_DRAW = true;
public static final boolean MAP_DRAW_ONLY_DIRTY_CELLS = false;
public static final TextMode MAIN_TEXT_MODE = TextMode.MODE_80X25;
public static final int LINE_MAP_BOTTOM = 20;
public static final int LINE_STATUS = 21;
public static final int LINE_MSG1 = 22;
public static final int LINE_MSG2 = 23;
public static final int LINE_MSG3 = 24;
public static final int LINE_DEBUG = 25;
public static final int COLUMN_MAP_END = 40;
public static final int COLUMN_RIGHTSIDE_START = 43;
public static final boolean DEBUG_TIME = false;
public static final int LINE_STATUS = 21;
public static final int LINE_MSG1 = 22;
public static final int LINE_MSG2 = 23;
public static final int LINE_MSG3 = 24;
public static final int LINE_DEBUG = 25;
public static final int COLUMN_MAP_END = 40;
public static final int COLUMN_RIGHT_SIDE_START = 43;
public static void main(String[] args) {
launch(args);
}
public static void main(String[] args) {
launch(args);
}
private Screen screen;
private ITurtle painter;
private Printer printer;
private Screen screen;
private ITurtle painter;
private Printer printer;
private Game game;
private RogueGame game;
private boolean grid = MAIN_USE_BACKGROUND_GRID;
private boolean autoNextTurn = false;
private Timeline bigStepTimeline;
private Timeline smallStepTimeline;
private boolean grid = MAIN_USE_BACKGROUND_GRID;
private boolean autoNextTurn = false;
private Timeline bigStepTimeline;
private Timeline smallStepTimeline;
private void setup() {
//
game = new Game(screen, painter, printer);
game.draw();
private void setup() {
//
game = new RogueGame(screen, painter, printer);
game.draw();
//
bigStepTimeline = new Timeline();
bigStepTimeline.setCycleCount(Timeline.INDEFINITE);
KeyFrame kf = new KeyFrame(Duration.millis(1000), (ActionEvent event) -> {
if (autoNextTurn) {
doTurn();
}
});
bigStepTimeline.getKeyFrames().add(kf);
// bigStepTimeline.playFromStart();
//
bigStepTimeline = new Timeline();
bigStepTimeline.setCycleCount(Timeline.INDEFINITE);
KeyFrame kf = new KeyFrame(Duration.millis(1000), (ActionEvent event) -> {
if (autoNextTurn) {
doTurn();
}
});
bigStepTimeline.getKeyFrames().add(kf);
// bigStepTimeline.playFromStart();
//
smallStepTimeline = new Timeline();
smallStepTimeline.setCycleCount(1);
kf = new KeyFrame(Duration.millis(1), (ActionEvent event) -> {
doTurn();
});
smallStepTimeline.getKeyFrames().add(kf);
//
smallStepTimeline = new Timeline();
smallStepTimeline.setCycleCount(1);
kf = new KeyFrame(Duration.millis(1), (ActionEvent event) -> {
doTurn();
});
smallStepTimeline.getKeyFrames().add(kf);
// finally, start game
doTurn();
}
// finally, start game
doTurn();
}
@Override
public void start(Stage primaryStage) throws Exception {
screen = Screen.startPaintScene(primaryStage, Screen.CONFIG_PIXELS_STEP_SCALED); // Screen.CONFIG_SCREEN_FULLSCREEN_NO_HINT);
@Override
public void start(Stage primaryStage) throws Exception {
screen = Screen.startPaintScene(primaryStage, Screen.CONFIG_PIXELS_STEP_SCALED); // Screen.CONFIG_SCREEN_FULLSCREEN_NO_HINT);
printer = screen.createPrinter();
painter = screen.createPainter();
printer.setTextMode(MAIN_TEXT_MODE, true);
// Font with emojis need separate download
printer.setFont(Printer.FONT_SYMBOLA);
if (grid)
printer.drawCharCells();
printer.setAutoScroll(false);
screen.setKeyPressedHandler((KeyEvent event) -> {
KeyCode code = event.getCode();
if (event.isShortcutDown()) {
if (code == KeyCode.Q) {
System.exit(0);
} else if (code == KeyCode.R) {
printer.cycleMode(true);
if (grid)
printer.drawCharCells();
game.draw();
printer.redrawDirty();
return true;
} else if (code == KeyCode.A) {
screen.cycleAspect();
if (grid)
printer.drawCharCells();
return true;
} else if (code == KeyCode.G) {
grid = !grid;
if (grid)
printer.drawCharCells();
else
screen.clearBackground();
return true;
} else if (code == KeyCode.F) {
screen.setFullScreen(!screen.isFullScreen());
return true;
} else if (code == KeyCode.L) {
printer.redrawTextPage();
return true;
}
printer = screen.createPrinter();
painter = screen.createPainter();
printer.setTextMode(MAIN_TEXT_MODE, true);
// Font with emojis need separate download
printer.setFont(Printer.FONT_SYMBOLA);
if (grid) {
printer.drawCharCells();
}
printer.setAutoScroll(false);
screen.setKeyPressedHandler((KeyEvent event) -> {
KeyCode code = event.getCode();
if (event.isShortcutDown()) {
if (code == KeyCode.Q) {
System.exit(0);
} else if (code == KeyCode.R) {
printer.cycleMode(true);
if (grid) {
printer.drawCharCells();
}
game.draw();
printer.redrawDirty();
return true;
} else if (code == KeyCode.A) {
screen.cycleAspect();
if (grid) {
printer.drawCharCells();
}
return true;
} else if (code == KeyCode.G) {
grid = !grid;
if (grid) {
printer.drawCharCells();
} else {
screen.clearBackground();
}
return true;
} else if (code == KeyCode.F) {
screen.setFullScreen(!screen.isFullScreen());
return true;
} else if (code == KeyCode.L) {
printer.redrawTextPage();
return true;
}
/*} else if (code == KeyCode.ENTER) {
try {
doTurn();
@ -131,81 +134,83 @@ public class Main extends Application {
e.printStackTrace();
}
return true;*/ // This interferes with other code
} else {
try {
if (game.keyPressed(code)) {
game.draw();
} else {
try {
if (game.keyPressed(code)) {
game.draw();
} else {
doTurn();
doTurn();
}
} catch (Exception e) {
e.printStackTrace();
try {
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
e.printStackTrace(writer);
writer.close();
String trace = sw.toString().split("\n")[0];
game.displayDebug("Exception: " + trace);
} catch (Exception e2) {
System.err.println("Also got this exception trying to display the previous one");
e2.printStackTrace();
game.displayDebug("Exception: " + e.getMessage());
}
}
printer.redrawDirty();
return true;
}
return false;
});
/*
* screen.setKeyTypedHandler((KeyEvent event) -> { if (event.getCharacter() !=
* KeyEvent.CHAR_UNDEFINED) { printer.print(event.getCharacter()); return true;
* } return false; });
*/
setup();
} catch (Exception e) {
e.printStackTrace();
try {
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
e.printStackTrace(writer);
writer.close();
String trace = sw.toString().split("\n")[0];
game.displayDebug("Exception: " + trace);
} catch (Exception e2) {
System.err.println("Also got this exception trying to display the previous one");
e2.printStackTrace();
game.displayDebug("Exception: " + e.getMessage());
}
}
printer.redrawDirty();
return true;
}
return false;
});
/*
* screen.setKeyTypedHandler((KeyEvent event) -> { if (event.getCharacter() !=
* KeyEvent.CHAR_UNDEFINED) { printer.print(event.getCharacter()); return true;
* } return false; });
*/
setup();
primaryStage.show();
primaryStage.show();
}
}
public void doTurn() {
long t = System.currentTimeMillis();
boolean waitForPlayer = game.doTurn();
if (DEBUG_TIME)
System.out.println("doTurn() took " + (System.currentTimeMillis() - t) + "ms");
long t2 = System.currentTimeMillis();
game.draw();
printer.redrawDirty();
if (DEBUG_TIME) {
System.out.println("draw() took " + (System.currentTimeMillis() - t2) + "ms");
System.out.println("doTurn()+draw() took " + (System.currentTimeMillis() - t) + "ms");
System.out.println("waiting for player? " + waitForPlayer);
}
if (!waitForPlayer)
smallStepTimeline.playFromStart(); // this will kickstart a new turn in a few milliseconds
}
public void doTurn() {
long t = System.currentTimeMillis();
boolean waitForPlayer = game.doTurn();
if (DEBUG_TIME) {
System.out.println("doTurn() took " + (System.currentTimeMillis() - t) + "ms");
}
long t2 = System.currentTimeMillis();
game.draw();
printer.redrawDirty();
if (DEBUG_TIME) {
System.out.println("draw() took " + (System.currentTimeMillis() - t2) + "ms");
System.out.println("doTurn()+draw() took " + (System.currentTimeMillis() - t) + "ms");
System.out.println("waiting for player? " + waitForPlayer);
}
if (!waitForPlayer) {
smallStepTimeline.playFromStart(); // this will kickstart a new turn in a few milliseconds
}
}
public static String BUILTIN_MAP = "40 20\n" //
+ "########################################\n" //
+ "#...... ..C.R ......R.R......... ..R...#\n" //
+ "#.R@R...... ..........RC..R...... ... .#\n" //
+ "#.......... ..R......R.R..R........R...#\n" //
+ "#R. R......... R..R.........R......R.RR#\n" //
+ "#... ..R........R......R. R........R.RR#\n" //
+ "###############################....R..R#\n" //
+ "#. ...R..C. ..R.R..........C.RC....... #\n" //
+ "#..C.....R..... ........RR R..R.....R..#\n" //
+ "#...R..R.R..............R .R..R........#\n" //
+ "#.R.....R........RRR.......R.. .C....R.#\n" //
+ "#.C.. ..R. .....R.RC..C....R...R..C. .#\n" //
+ "#. R..............R R..R........C.....R#\n" //
+ "#........###############################\n" //
+ "# R.........R...C....R.....R...R.......#\n" //
+ "# R......... R..R........R......R.RR..##\n" //
+ "#. ..R........R.....R. ....C...R.RR...#\n" //
+ "#....RC..R........R......R.RC......R...#\n" //
+ "#.C.... ..... ......... .R..R....R...R.#\n" //
+ "########################################\n" //
;
public static String BUILTIN_MAP = "40 20\n" //
+ "########################################\n" //
+ "#...... ..C.R ......R.R......... ..R...#\n" //
+ "#.R@R...... ..........RC..R...... ... .#\n" //
+ "#.......... ..R......R.R..R........R...#\n" //
+ "#R. R......... R..R.........R......R.RR#\n" //
+ "#... ..R........R......R. R........R.RR#\n" //
+ "###############################....R..R#\n" //
+ "#. ...R..C. ..R.R..........C.RC....... #\n" //
+ "#..C.....R..... ........RR R..R.....R..#\n" //
+ "#...R..R.R..............R .R..R........#\n" //
+ "#.R.....R........RRR.......R.. .C....R.#\n" //
+ "#.C.. ..R. .....R.RC..C....R...R..C. .#\n" //
+ "#. R..............R R..R........C.....R#\n" //
+ "#........###############################\n" //
+ "# R.........R...C....R.....R...R.......#\n" //
+ "# R......... R..R........R......R.RR..##\n" //
+ "#. ..R........R.....R. ....C...R.RR...#\n" //
+ "#....RC..R........R......R.RC......R...#\n" //
+ "#.C.... ..... ......... .R..R....R...R.#\n" //
+ "########################################\n" //
;
}

View File

@ -1,29 +1,29 @@
package inf101.v18.rogue101.enemies;
import inf101.v18.grid.ILocation;
import inf101.v18.rogue101.Main;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.items.Backpack;
import inf101.v18.rogue101.items.Sword;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.objects.INonPlayer;
import inf101.v18.rogue101.shared.NPC;
import inf101.v18.rogue101.states.Attack;
import inf101.v18.rogue101.game.RogueGame;
import inf101.v18.rogue101.items.weapon.BasicSword;
import inf101.v18.rogue101.object.Item;
import inf101.v18.rogue101.state.AttackType;
import inf101.v18.util.NPCHelper;
public class Boss implements INonPlayer {
private int hp = getMaxHealth();
private final Backpack backpack = new Backpack();
private ILocation loc;
/**
* A boss enemy that's harder than any other enemy
*/
public class Boss extends Enemy {
/**
* Instantiates a new boss character
*/
public Boss() {
backpack.add(new Sword());
backpack.add(new BasicSword());
}
@Override
public void doTurn(IGame game) {
loc = game.getLocation();
NPC.tryAttack(game, 1, Attack.MELEE);
public void doTurn(Game game) {
currentLocation = game.getLocation();
NPCHelper.tryAttack(game, 1, AttackType.MELEE);
}
@Override
@ -36,23 +36,13 @@ public class Boss implements INonPlayer {
return 15;
}
@Override
public IItem getItem(Class<?> type) {
for (IItem item : backpack.getContent()) {
if (type.isInstance(item)) {
return item;
}
}
return null;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
public int getDefense() {
return 40;
}
@ -87,21 +77,13 @@ public class Boss implements INonPlayer {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
if (hp < 0 && backpack.size() > 0) { //Will be useful in a dungeon with several bosses
boolean dropped = false;
for (IItem item : backpack.getContent()) {
if (game.dropAt(loc, item)) {
dropped = true;
}
}
if (dropped) {
game.displayMessage(getName() + " dropped something");
}
((Game)game).win();
public int handleDamage(Game game, Item source, int amount) {
super.handleDamage(game, source, amount);
if (hp < 0) {
((RogueGame) game).win();
}
game.getPrinter().printAt(Main.COLUMN_RIGHTSIDE_START, 19, "Boss HP: " + NPC.hpBar(this));
game.getPrinter().printAt(Main.COLUMN_RIGHT_SIDE_START, 19, "Boss HP: " + NPCHelper.hpBar(this));
return amount;
}
}

View File

@ -0,0 +1,46 @@
package inf101.v18.rogue101.enemies;
import inf101.v18.grid.Location;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.items.container.Backpack;
import inf101.v18.rogue101.object.Item;
import inf101.v18.rogue101.object.NonPlayerCharacter;
import inf101.v18.rogue101.state.Sound;
public abstract class Enemy implements NonPlayerCharacter {
protected int hp = getMaxHealth();
protected final Backpack backpack = new Backpack();
protected Location currentLocation;
@Override
public Item getItem(Class<?> type) {
for (Item item : backpack.getContent()) {
if (type.isInstance(item)) {
return item;
}
}
return null;
}
@Override
public int handleDamage(Game game, Item source, int amount) {
hp -= amount;
if (hp < 0) {
Sound.NPC_DEATH.play();
}
if (hp < 0 && backpack.size() > 0) { //Will be useful in a dungeon with several bosses
boolean dropped = false;
for (Item item : backpack.getContent()) {
if (game.dropAt(currentLocation, item)) {
dropped = true;
}
}
if (dropped) {
game.displayMessage(getName() + " dropped something");
}
}
return amount;
}
}

View File

@ -1,108 +1,127 @@
package inf101.v18.rogue101.enemies;
import inf101.v18.grid.GridDirection;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.items.*;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.objects.INonPlayer;
import inf101.v18.rogue101.shared.NPC;
import inf101.v18.rogue101.states.Age;
import inf101.v18.rogue101.states.Attack;
import inf101.v18.rogue101.states.Occupation;
import inf101.v18.rogue101.states.Personality;
import inf101.v18.grid.Location;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.items.buff.BuffItem;
import inf101.v18.rogue101.items.weapon.BasicBow;
import inf101.v18.rogue101.items.weapon.BasicSword;
import inf101.v18.rogue101.items.weapon.FireStaff;
import inf101.v18.rogue101.items.weapon.MagicWeapon;
import inf101.v18.rogue101.items.weapon.MeleeWeapon;
import inf101.v18.rogue101.items.weapon.RangedWeapon;
import inf101.v18.rogue101.object.Item;
import inf101.v18.rogue101.state.AttackType;
import inf101.v18.rogue101.state.LifeStage;
import inf101.v18.rogue101.state.Occupation;
import inf101.v18.rogue101.state.Personality;
import inf101.v18.util.NPCHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Girl implements INonPlayer {
/**
* An enemy NPC
*/
public class Girl extends Enemy {
private final String name = randomName();
private final Age age = Age.getRandom();
private final LifeStage lifeStage = LifeStage.getRandom();
private final Personality personality = Personality.getRandom();
private final Occupation occupation = Occupation.getRandom();
private int maxhp;
private int hp;
private int maxHp;
private int attack;
private int defence;
private int visibility;
private int damage;
private final Backpack backpack = new Backpack();
private List<GridDirection> damageDirections;
private static final Random random = new Random();
private List<Class<?>> validItems;
private static final String[] namelist = {"Milk", "Salad", "Mikan", "Rima", "Suki", "Miki", "Hinata", "Haruna", "Asuna"};
private static final String[] nameList = {"Milk", "Salad", "Mikan", "Rima", "Suki", "Miki", "Hinata", "Haruna",
"Asuna"};
/**
* Instantiates a new Girl enemy NPC
*/
public Girl() {
setStats();
setValidItems();
}
private void setStats() {
switch (age) {
// Set stats based on the NPC's age
switch (lifeStage) {
case TODDLER:
maxhp = 30;
maxHp = 30;
attack = 10;
defence = 50;
damage = 1 + random.nextInt(5);
visibility = 1;
break;
case CHILD:
maxhp = 50;
maxHp = 50;
attack = 20;
defence = 40;
damage = 2 + random.nextInt(5);
visibility = 2;
break;
case TEEN:
maxhp = 70;
maxHp = 70;
attack = 25;
defence = 30;
damage = 3 + random.nextInt(5);
visibility = 3;
break;
case ADULT:
maxhp = 100;
maxHp = 100;
attack = 30;
defence = 20;
damage = 4 + random.nextInt(5);
visibility = 4;
break;
case ELDER:
maxhp = 70;
maxHp = 70;
attack = 15;
defence = 35;
damage = 3 + random.nextInt(5);
visibility = 2;
break;
}
// Improve stats based on occupation
if (occupation == Occupation.KNIGHT) {
attack += 10; //Knights are quite powerful.
} else if (occupation == Occupation.MAGE) {
attack += 5; // Mages have lesser range than bowsmen, but more damage.
attack += 5; // Mages have lesser range than archers, but more damage.
}
maxhp += (int)(random.nextGaussian() * 10);
hp = maxhp;
attack += (int)(random.nextGaussian() * 5);
defence += (int)(random.nextGaussian() * 5);
// Add random stat improvements
maxHp += (int) (random.nextGaussian() * 10);
hp = maxHp;
attack += (int) (random.nextGaussian() * 5);
defence += (int) (random.nextGaussian() * 5);
}
/**
* Has a chance of giving a weapon to a girl.
*
* @param lvl The current map level
* @param lvl The current map level
*/
public void giveWeapon(int lvl) {
if (random.nextInt(5) < lvl) {
switch (occupation) {
case KNIGHT:
backpack.add(new Sword());
break;
case MAGE:
backpack.add(new Staff());
break;
case BOWSMAN:
backpack.add(new Bow());
}
// Randomly grant a weapon based on occupation.
// The chance of being granted a weapon increases for each level
if (random.nextInt(5) >= lvl) {
return;
}
switch (occupation) {
case KNIGHT:
backpack.add(new BasicSword());
break;
case MAGE:
backpack.add(new FireStaff());
break;
case ARCHER:
backpack.add(new BasicBow());
}
}
@ -112,48 +131,70 @@ public class Girl implements INonPlayer {
private void setValidItems() {
validItems = new ArrayList<>();
switch (occupation) {
case BOWSMAN:
validItems.add(IRangedWeapon.class);
case ARCHER:
validItems.add(RangedWeapon.class);
break;
case MAGE:
validItems.add(IMagicWeapon.class);
validItems.add(MagicWeapon.class);
break;
case KNIGHT:
validItems.add(IMeleeWeapon.class);
validItems.add(MeleeWeapon.class);
}
validItems.add(IBuffItem.class);
validItems.add(BuffItem.class);
}
/**
* Picks a "random" name
*
* @return A random name
* @return A random name
*/
private String randomName() {
return namelist[random.nextInt(namelist.length)] + "-chan";
return nameList[random.nextInt(nameList.length)] + "-chan";
}
@Override
public void doTurn(IGame game) {
public void doTurn(Game game) {
currentLocation = game.getLocation();
List<GridDirection> damageDirections = this.damageDirections;
this.damageDirections = null;
// If this NPC has space, pick up any items on the ground
if (backpack.hasSpace()) {
IItem item = NPC.pickUp(game, validItems);
Item item = NPCHelper.pickUp(game, validItems);
if (item != null) {
backpack.add(item);
return;
}
if (NPC.trackItem(game, validItems)) {
if (NPCHelper.trackItem(game, validItems)) {
return;
}
}
if (personality == Personality.AFRAID && NPC.flee(game)) {
return;
// TODO: If attacked on the last turn, flee from the attacker if not within sight range
if ((personality == Personality.AFRAID || hp < 0.1 * maxHp)) {
// Flee from the nearest enemy
if (NPCHelper.flee(game)) {
return;
}
// Flee in the direction this NPC was damaged from. This allows the NPC to flee from ranged attacks outside
// visible range.
if (damageDirections != null) {
for (GridDirection direction : damageDirections) {
if (game.canGo(direction)) {
game.move(direction);
return;
}
}
}
}
// Attack if necessary
if (willAttack(game) && attack(game)) {
return;
}
// Move a random direction if possible
List<GridDirection> possibleMoves = game.getPossibleMoves();
if (!possibleMoves.isEmpty()) {
Collections.shuffle(possibleMoves);
@ -164,22 +205,22 @@ public class Girl implements INonPlayer {
/**
* Tries to attack with an attack specified by the Girl's occupation
*
* @param game An IGame object
* @return True if an attack occurred. False otherwise
* @param game An IGame object
* @return True if an attack occurred. False otherwise
*/
private boolean attack(IGame game) {
private boolean attack(Game game) {
switch (occupation) {
case KNIGHT:
if (NPC.tryAttack(game, 1, Attack.MELEE)) {
if (NPCHelper.tryAttack(game, 1, AttackType.MELEE)) {
return true;
}
break;
case MAGE:
if (NPC.tryAttack(game, getVision() / 2 + getVision() % 2 == 0 ? 0 : 1, Attack.MAGIC)) {
if (NPCHelper.tryAttack(game, getVision() / 2 + getVision() % 2 == 0 ? 0 : 1, AttackType.MAGIC)) {
return true;
}
case BOWSMAN:
if (NPC.tryAttack(game, getVision(), Attack.RANGED)) {
case ARCHER:
if (NPCHelper.tryAttack(game, getVision(), AttackType.RANGED)) {
return true;
}
}
@ -189,23 +230,26 @@ public class Girl implements INonPlayer {
/**
* Checks if the current girl will try to attack.
*
* @param game An IGame object
* @return True if the girl will attack. False otherwise
* @param game An IGame object
* @return True if the girl will attack. False otherwise
*/
private boolean willAttack(IGame game) {
private boolean willAttack(Game game) {
boolean attack = false;
switch (personality) {
case CALM:
if (hp < maxhp) {
// Attack if previously attacked
if (hp < maxHp) {
attack = true;
}
break;
case AFRAID:
// Attack if cornered
if (game.getPossibleMoves().isEmpty()) {
attack = true;
}
break;
case AGRESSIVE:
case AGGRESSIVE:
// Always attack
attack = true;
break;
}
@ -228,13 +272,13 @@ public class Girl implements INonPlayer {
}
@Override
public int getDefence() {
public int getDefense() {
return defence;
}
@Override
public int getMaxHealth() {
return maxhp;
return maxHp;
}
@Override
@ -263,18 +307,12 @@ public class Girl implements INonPlayer {
}
@Override
public IItem getItem(Class<?> type) {
for (IItem item : backpack.getContent()) {
if (type.isInstance(item)) {
return item;
}
}
return null;
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
public int handleDamage(Game game, Item source, int amount) {
super.handleDamage(game, source, amount);
Location location = game.getMap().getLocation(source);
Location location2 = game.getMap().getLocation(this);
damageDirections = game.locationDirection(location, location2);
return amount;
}
}

View File

@ -1,145 +1,97 @@
package inf101.v18.rogue101.events;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
/**
* Example implementation of events could be used to have more complex
* behaviour than just attack/defend/get damaged/pickup/drop.
*
* @author anya
*
* @param <T>
* Relevant extra data for this particular event
* @param <T> Relevant extra data for this particular event
* @author anya
*/
public class GameEvent<T> implements IEvent<T> {
public static final String ATTACK_FAILURE = "attackFailure";
public static final String ATTACK_SUCCESS = "attackSuccess";
public static final String DEFEND_FAILURE = "defendFailure";
public static final String DEFEND_SUCCESS = "defendSuccess";
public static final String EATEN = "eaten";
/**
* Create and send events for an attack.
* <p>
* Both attacker and defender will receive appropriate events (ATTACK_* or
* DEFEND_*), depending on who won. The amount of damage is available through
* {@link #getData()}.
* <p>
* Attacker will be sent the "damage" that was actually done (as returned by
* defender's event handler)
* <p>
* Methods such as these could sensible be placed in IGame/Game.
*
* @param success
* True if attack succeeded (attacker "won")
* @param attacker
* @param defender
* @param damage
*/
public static void triggerAttack(boolean success, IItem attacker, IItem defender, int damage) {
if (success) {
Integer result = defender
.handleEvent(new GameEvent<Integer>(DEFEND_FAILURE, null, attacker, defender, damage));
if (result != null)
damage = result;
attacker.handleEvent(new GameEvent<Integer>(ATTACK_SUCCESS, null, attacker, defender, damage));
} else {
attacker.handleEvent(new GameEvent<Integer>(ATTACK_FAILURE, null, attacker, defender, 0));
defender.handleEvent(new GameEvent<Integer>(DEFEND_SUCCESS, null, attacker, defender, 0));
}
}
private final String name;
private final Item source;
private final Item target;
private T value;
private final String name;
private final IItem source;
private final IItem target;
private T value;
private final Game game;
private final IGame game;
/**
* Create a new game event
*
* @param name The name is used when checking which event this is / determine its
* meaning
* @param game The game, or <code>null</code> if unknown/not relevant
* @param source The item that caused the event, or <code>null</code> if
* unknown/not relevant
* @param target The item that receives the event, or <code>null</code> if
* unknown/not relevant
* @param value Arbitrary extra data
*/
public GameEvent(String name, Game game, Item source, Item target, T value) {
this.name = name;
this.game = game;
this.source = source;
this.target = target;
this.value = value;
}
/**
* Create a new game event
*
* @param name
* The name is used when checking which event this is / determine its
* meaning
* @param game
* The game, or <code>null</code> if unknown/not relevant
* @param source
* The item that caused the event, or <code>null</code> if
* unknown/not relevant
* @param target
* The item that receives the event, or <code>null</code> if
* unknown/not relevant
* @param value
* Arbitrary extra data
*/
public GameEvent(String name, IGame game, IItem source, IItem target, T value) {
this.name = name;
this.game = game;
this.source = source;
this.target = target;
this.value = value;
}
/**
* Create a new game event
*
* @param name The name is used when checking which event this is / determine its
* meaning
* @param source The item that caused the event, or <code>null</code> if
* unknown/not relevant
*/
public GameEvent(String name, Item source) {
this(name, null, source, null, null);
}
/**
* Create a new game event
*
* @param name
* The name is used when checking which event this is / determine its
* meaning
* @param source
* The item that caused the event, or <code>null</code> if
* unknown/not relevant
*/
public GameEvent(String name, IItem source) {
this(name, null, source, null, null);
}
/**
* Create a new game event
*
* @param name The name is used when checking which event this is / determine its
* meaning
* @param source The item that caused the event, or <code>null</code> if
* unknown/not relevant
* @param value Arbitrary extra data
*/
public GameEvent(String name, Item source, T value) {
this(name, null, source, null, value);
}
/**
* Create a new game event
*
* @param name
* The name is used when checking which event this is / determine its
* meaning
* @param source
* The item that caused the event, or <code>null</code> if
* unknown/not relevant
* @param value
* Arbitrary extra data
*/
public GameEvent(String name, IItem source, T value) {
this(name, null, source, null, value);
}
@Override
public T getData() {
return value;
}
@Override
public T getData() {
return value;
}
@Override
public String getEventName() {
return name;
}
@Override
public String getEventName() {
return name;
}
@Override
public Game getGame() {
return game;
}
@Override
public IGame getGame() {
return game;
}
@Override
public Item getSource() {
return source;
}
@Override
public IItem getSource() {
return source;
}
@Override
public Item getTarget() {
return target;
}
@Override
public IItem getTarget() {
return target;
}
@Override
public void setData(T value) {
this.value = value;
}
@Override
public void setData(T value) {
this.value = value;
}
}

View File

@ -1,7 +1,7 @@
package inf101.v18.rogue101.events;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
/**
* An event is something that happens in the game, typically due to an actor
@ -19,54 +19,51 @@ import inf101.v18.rogue101.objects.IItem;
* source/targets of the event (where relevant).
* <p>
* This system is fairly simplistic, and you're not expected to make use of it.
*
* @author anya
*
* @param <T>
* Type of the extra data
* @param <T> Type of the extra data
* @author anya
*/
public interface IEvent<T> {
/**
* @return Extra data stored in this event
*/
T getData();
/**
* @return Extra data stored in this event
*/
T getData();
/**
* @return The name of this event
*/
String getEventName();
/**
* @return The name of this event
*/
String getEventName();
/**
* Not all events need to be connected to the game, but you can use this if you
* need it (e.g., for showing a message, or adding something to the map).
* <p>
* The result might be null.
*
* @return The game associated with this event, or null.
*/
IGame getGame();
/**
* Not all events need to be connected to the game, but you can use this if you
* need it (e.g., for showing a message, or adding something to the map).
* <p>
* The result might be null.
*
* @return The game associated with this event, or null.
*/
Game getGame();
/**
* The source is the item that caused the event
* <p>
* Could be null if the source is unknown or not relevant.
*
* @return The source of this event
*/
IItem getSource();
/**
* The source is the item that caused the event
* <p>
* Could be null if the source is unknown or not relevant.
*
* @return The source of this event
*/
Item getSource();
/**
* The target is the item that is affected by the event
* <p>
* Could be null if the target is unknown or not relevant.
*
* @return The target of this event, or null
*/
IItem getTarget();
/**
* The target is the item that is affected by the event
* <p>
* Could be null if the target is unknown or not relevant.
*
* @return The target of this event, or null
*/
Item getTarget();
/**
* @param value
* Extra data to store in this event
*/
void setData(T value);
/**
* @param value Extra data to store in this event
*/
void setData(T value);
}

View File

@ -1,82 +1,82 @@
package inf101.v18.rogue101.examples;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
import javafx.scene.paint.Color;
public class Carrot implements IItem {
private int hp = getMaxHealth();
public class Carrot implements Item {
private int hp = getMaxHealth();
public void doTurn() {
hp = Math.min(hp + 1, getMaxHealth());
}
public void doTurn() {
hp = Math.min(hp + 1, getMaxHealth());
}
@Override
public boolean draw(ITurtle painter, double w, double h) {
painter.save();
painter.turn(75);
double size = ((double) hp + getMaxHealth()) / (2.0 * getMaxHealth());
double carrotLength = size * h * .6;
double carrotWidth = size * h * .4;
painter.jump(-carrotLength / 6);
painter.shape().ellipse().width(carrotLength).height(carrotWidth).fillPaint(Color.ORANGE).fill();
painter.jump(carrotLength / 2);
painter.setInk(Color.FORESTGREEN);
for (int i = -1; i < 2; i++) {
painter.save();
painter.turn(20 * i);
painter.draw(carrotLength / 3);
painter.restore();
}
painter.restore();
return true;
}
@Override
public boolean draw(ITurtle painter, double w, double h) {
painter.save();
painter.turn(75);
double size = ((double) hp + getMaxHealth()) / (2.0 * getMaxHealth());
double carrotLength = size * h * .6;
double carrotWidth = size * h * .4;
painter.jump(-carrotLength / 6);
painter.shape().ellipse().width(carrotLength).height(carrotWidth).fillPaint(Color.ORANGE).fill();
painter.jump(carrotLength / 2);
painter.setInk(Color.FORESTGREEN);
for (int i = -1; i < 2; i++) {
painter.save();
painter.turn(20 * i);
painter.draw(carrotLength / 3);
painter.restore();
}
painter.restore();
return true;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getDefense() {
return 0;
}
@Override
public double getHealthStatus() {
return getCurrentHealth() / getMaxHealth();
}
@Override
public double getHealthStatus() {
return getCurrentHealth() / getMaxHealth();
}
@Override
public int getMaxHealth() {
return 23;
}
@Override
public int getMaxHealth() {
return 23;
}
@Override
public String getName() {
return "carrot";
}
@Override
public String getName() {
return "carrot";
}
@Override
public int getSize() {
return 2;
}
@Override
public int getSize() {
return 2;
}
@Override
public String getSymbol() {
return "C";
}
@Override
public String getSymbol() {
return "C";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
@Override
public int handleDamage(Game game, Item source, int amount) {
hp -= amount;
if (hp < 0) {
// we're all eaten!
hp = 0;
}
return amount;
}
if (hp < 0) {
// we're all eaten!
hp = 0;
}
return amount;
}
}

View File

@ -1,51 +0,0 @@
package inf101.v18.rogue101.examples;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
public class ExampleItem implements IItem {
private int hp = getMaxHealth();
@Override
public boolean draw(ITurtle painter, double w, double h) {
return false;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 1;
}
@Override
public String getName() {
return "strange model of an item";
}
@Override
public int getSize() {
return 1;
}
@Override
public String getSymbol() {
return "X";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
return amount;
}
}

View File

@ -1,122 +1,123 @@
package inf101.v18.rogue101.examples;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.grid.GridDirection;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
import inf101.v18.rogue101.object.NonPlayerCharacter;
import inf101.v18.rogue101.state.AttackType;
import inf101.v18.util.NPCHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.grid.GridDirection;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.objects.INonPlayer;
import inf101.v18.rogue101.shared.NPC;
import inf101.v18.rogue101.states.Attack;
public class Rabbit implements NonPlayerCharacter {
private int food = 0;
private int hp = getMaxHealth();
private static final List<Class<?>> validItems = new ArrayList<>();
public class Rabbit implements INonPlayer {
private int food = 0;
private int hp = getMaxHealth();
private static final List<Class<?>> validItems = new ArrayList<>();
static {
validItems.add(Carrot.class);
}
static {
validItems.add(Carrot.class);
}
@Override
public void doTurn(IGame game) {
if (food == 0) {
hp--;
} else {
food--;
}
if (hp < 1) {
return;
}
@Override
public void doTurn(Game game) {
if (food == 0) {
hp--;
} else {
food--;
}
if (hp < 1) {
return;
}
if (NPC.tryAttack(game, 1, Attack.MELEE)) {
return;
}
if (NPCHelper.tryAttack(game, 1, AttackType.MELEE)) {
return;
}
for (IItem item : game.getLocalItems()) {
if (item instanceof Carrot) {
System.out.println("found carrot!");
int eaten = item.handleDamage(game, this, getDamage());
if (eaten > 0) {
System.out.println("ate carrot worth " + eaten + "!");
food += eaten;
game.displayMessage("You hear a faint crunching (" + getName() + " eats " + item.getArticle() + " " + item.getName() + ")");
return;
}
}
}
for (Item item : game.getLocalItems()) {
if (item instanceof Carrot) {
System.out.println("found carrot!");
int eaten = item.handleDamage(game, this, getDamage());
if (eaten > 0) {
System.out.println("ate carrot worth " + eaten + "!");
food += eaten;
game.displayMessage("You hear a faint crunching (" + getName() + " eats " + item.getArticle() + " " + item.getName() + ")");
return;
}
}
}
if (NPC.trackItem(game, validItems)) {
return;
}
if (NPCHelper.trackItem(game, validItems)) {
return;
}
List<GridDirection> possibleMoves = game.getPossibleMoves();
if (!possibleMoves.isEmpty()) {
Collections.shuffle(possibleMoves);
game.move(possibleMoves.get(0));
}
}
List<GridDirection> possibleMoves = game.getPossibleMoves();
if (!possibleMoves.isEmpty()) {
Collections.shuffle(possibleMoves);
game.move(possibleMoves.get(0));
}
}
@Override
public boolean draw(ITurtle painter, double w, double h) {
return false;
}
@Override
public boolean draw(ITurtle painter, double w, double h) {
return false;
}
@Override
public int getAttack() {
return 10;
}
@Override
public int getAttack() {
return 10;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDamage() {
return 5;
}
@Override
public int getDamage() {
return 5;
}
@Override
public int getDefence() {
return 10;
}
@Override
public int getDefense() {
return 10;
}
@Override
public int getMaxHealth() {
return 30;
}
@Override
public int getMaxHealth() {
return 30;
}
@Override
public String getName() {
return "Rabbit";
}
@Override
public String getName() {
return "Rabbit";
}
@Override
public int getSize() {
return 4;
}
@Override
public int getSize() {
return 4;
}
@Override
public int getVision() {
return 4;
}
@Override
public int getVision() {
return 4;
}
@Override
public IItem getItem(Class<?> type) {
return null;
}
@Override
public Item getItem(Class<?> type) {
return null;
}
@Override
public String getSymbol() {
return hp > 0 ? "R" : "¤";
}
@Override
public String getSymbol() {
return hp > 0 ? "R" : "¤";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
return amount;
}
@Override
public int handleDamage(Game game, Item source, int amount) {
hp -= amount;
return amount;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,340 +0,0 @@
package inf101.v18.rogue101.game;
import java.util.List;
import java.util.Random;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.textmode.Printer;
import inf101.v18.grid.GridDirection;
import inf101.v18.grid.ILocation;
import inf101.v18.rogue101.map.IMapView;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.objects.IActor;
import inf101.v18.rogue101.objects.INonPlayer;
import inf101.v18.rogue101.objects.IPlayer;
import inf101.v18.rogue101.states.Attack;
/**
* Game interface
* <p>
* The game has a map and a current {@link IActor} (the player or non-player
* whose turn it currently is). The game also knows the current location of the
* actor. Most methods that deal with the map will use this current location
* they are meant to be used by the current actor for exploring or interacting
* with its surroundings.
* <p>
* In other words, you should avoid calling most of these methods if you're not
* the current actor. You know you're the current actor when you're inside your
* {@link IPlayer#keyPressed()} or {@link INonPlayer#doTurn()} method.
*
* @author anya
*
*/
public interface IGame {
/**
* Add an item to the current location
* <p>
* If the item is an actor, it won't move until the next turn.
*
* @param item
*/
void addItem(IItem item);
/**
* Add a new item (identified by symbol) to the current location
* <p>
* If the item is an actor, it won't move until the next turn.
*
* @param sym
*/
void addItem(String sym);
/**
* Perform an attack on the target.
* <p>
* Will use your {@link IActor#getAttack()} against the target's
* {@link IItem#getDefence()}, and then possiblyu find the damage you're dealing
* with {@link IActor#getDamage()} and inform the target using
* {@link IItem#handleDamage(IGame, IItem, int)}
*
* @param dir
* Direction
* @param target
* A target item, which should be in the neighbouring square in the
* given direction
* @return Your new location if the attack resulted in you moving
*/
ILocation attack(GridDirection dir, IItem target);
/**
* @param dir
* @return True if it's possible to move in the given direction
*/
boolean canGo(GridDirection dir);
/**
* Create a new item based on a text symbol
* <p>
* The item won't be added to the map unless you call {@link #addItem(IItem)}.
*
* @param symbol
* @return The new item
*/
IItem createItem(String symbol);
/**
* Displays a message in the debug area on the screen (bottom line)
*
* @param s
* A message
*/
void displayDebug(String s);
/**
* Displays a message in the message area on the screen (below the map and the
* status line)
*
* @param s
* A message
*/
void displayMessage(String s);
/**
* Displays a status message in the status area on the screen (right below the
* map)
*
* @param s
* A message
*/
void displayStatus(String s);
/**
* Displays a message in the message area on the screen (below the map and the
* status line)
*
* @param s
* A message
* @see String#format(String, Object...)
*/
void formatDebug(String s, Object... args);
/**
* Displays a formatted message in the message area on the screen (below the map
* and the status line)
*
* @param s
* A message
* @see String#format(String, Object...)
*/
void formatMessage(String s, Object... args);
/**
* Displays a formatted status message in the status area on the screen (right
* below the map)
*
* @param s
* A message
* @see String#format(String, Object...)
*/
void formatStatus(String s, Object... args);
/**
* Pick up an item
* <p>
* This should be used by IActors who want to pick up an item and carry it. The
* item will be returned if picking it succeeded (the actor <em>might</em> also
* make a mistake and pick up the wrong item!).
*
* @param item
* An item, should be in the current map location
* @return The item that was picked up (normally <code>item</code>), or
* <code>null</code> if it failed
*/
IItem pickUp(IItem item);
/**
* Drop an item
* <p>
* This should be used by IActors who are carrying an item and want to put it on
* the ground. Check the return value to see if it succeeded.
*
* @param item
* An item, should be carried by the current actor and not already be
* on the map
* @return True if the item was placed on the map, false means you're still
* holding it
*/
boolean drop(IItem item);
/**
* Does the same as drop, but for a specified location.
*
* @param loc The location to drop the location
* @param item The item to drop
* @return True if the item was dropped. False otherwise
*/
boolean dropAt(ILocation loc, IItem item);
/**
* Clear the unused graphics area (you can fill it with whatever you want!)
*/
void clearFreeGraphicsArea();
/**
* Clear the unused text area (you can fill it with whatever you want!)
*/
void clearFreeTextArea();
/**
* Get the bounds of the free graphics area.
* <p>
* You can fill this with whatever you want, using {@link #getPainter()} and
* {@link #clearFreeGraphicsArea()}.
*
* @return Array of coordinates; ([0],[1]) are the top-left corner, and
* ([2],[3]) are the bottom-right corner (exclusive).
*/
double[] getFreeGraphicsAreaBounds();
/**
* Get the bounds of the free text area.
* <p>
* You can fill this with whatever you want, using {@link #getPrinter()} and
* {@link #clearFreeTextArea()}.
* <p>
* You'll probably want to use something like:
*
* <pre>
* int[] bounds = getFreeTextArea();
* int x = bounds[0];
* int y = bounds[1];
* game.getPrinter().printAt(x, y++, "Hello");
* game.getPrinter().printAt(x, y++, "Do you have any carrot cake?", Color.ORANGE);
* </pre>
*
* @return Array of column/line numbers; ([0],[1]) is the top-left corner, and
* ([2],[3]) is the bottom-right corner (inclusive).
*/
int[] getFreeTextAreaBounds();
/**
* See {@link #getFreeGraphicsAreaBounds()}, {@link #clearFreeGraphicsArea()}.
*
* @return A Turtle, for painting graphics
*/
ITurtle getPainter();
/**
* See {@link #getFreeTextAreaBounds()}, {@link #clearFreeTextArea()}.
*
* @return A printer, for printing text
*/
Printer getPrinter();
/**
* @return The height of the map
*/
int getHeight();
/**
* @return A list of the non-actor items at the current map location
*/
List<IItem> getLocalItems();
/**
* Get the current actor's location.
* <p>
* You should only call this from an IActor that is currently doing its move.
*
* @return Location of the current actor
*/
ILocation getLocation();
/**
* Get the current actor
* <p>
* You can check if it's your move by doing game.getActor()==this.
*
* @return The current actor (i.e., the (IPlayer/INonPlayer) player who's turn it currently is)
*/
IActor getActor();
/**
* Get the neighbouring map location in direction <code>dir</code>
* <p>
* Same as <code>getLocation().go(dir)</code>
*
* @param dir
* A direction
* @return A location, or <code>null</code> if the location would be outside the
* map
*/
ILocation getLocation(GridDirection dir);
/**
* @return The map
*/
IMapView getMap();
/**
* @return A list of directions we can move in, for use with
* {@link #move(GridDirection)}
*/
List<GridDirection> getPossibleMoves();
/**
* Get a list of all locations that are visible from the current location.
* <p>
* The location list is sorted so that nearby locations come earlier in the
* list. E.g., if <code>l = getVisible()<code> and <code>i < j</code>then
* <code>getLocation().gridDistanceTo(l.get(i)) < getLocation().gridDistanceTo(l.get(j))</code>
*
* @return A list of grid cells visible from the {@link #getLocation()}
*/
List<ILocation> getVisible();
/**
* @return Width of the map
*/
int getWidth();
/**
* Move the current actor in the given direction.
* <p>
* The new location will be returned.
*
* @param dir
* @return A new location
* @throws IllegalMoveException
* if moving in that direction is illegal
*/
ILocation move(GridDirection dir);
/**
* Perform a ranged attack on the target.
* <p>
* Rules for this are up to you!
*
* @param dir
* Direction
* @param target
* A target item, which should in some square in the given direction
* @return Your new location if the attack resulted in you moving (unlikely)
*/
ILocation rangedAttack(GridDirection dir, IItem target, Attack type);
/**
* @return A random generator
*/
Random getRandom();
/**
* Gets a list of the best directions to go from current to neighbour.
* If the target is positioned diagonally from the start, the direction requiring the most steps is chosen.
*
* @param current The location to go from
* @param neighbour The location to go to
* @return A direction
*/
List<GridDirection> locationDirection(ILocation current, ILocation neighbour);
}

View File

@ -3,18 +3,17 @@ package inf101.v18.rogue101.game;
/**
* An exception to be thrown when an moving object tries to do an illegal move,
* for example to a position outside the map.
*
* @author larsjaffke
*
* @author larsjaffke
*/
public class IllegalMoveException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 7641529271996915740L;
/**
*
*/
private static final long serialVersionUID = 7641529271996915740L;
public IllegalMoveException(String message) {
super(message);
}
public IllegalMoveException(String message) {
super(message);
}
}

View File

@ -0,0 +1,852 @@
package inf101.v18.rogue101.game;
import inf101.v18.gfx.Screen;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.gfxmode.TurtlePainter;
import inf101.v18.gfx.textmode.Printer;
import inf101.v18.grid.GridDirection;
import inf101.v18.grid.IGrid;
import inf101.v18.grid.Location;
import inf101.v18.rogue101.Main;
import inf101.v18.rogue101.enemies.Boss;
import inf101.v18.rogue101.enemies.Girl;
import inf101.v18.rogue101.examples.Carrot;
import inf101.v18.rogue101.examples.Rabbit;
import inf101.v18.rogue101.items.buff.Binoculars;
import inf101.v18.rogue101.items.buff.BuffItem;
import inf101.v18.rogue101.items.buff.Shield;
import inf101.v18.rogue101.items.consumable.HealthPotion;
import inf101.v18.rogue101.items.consumable.Manga;
import inf101.v18.rogue101.items.container.Chest;
import inf101.v18.rogue101.items.container.Static;
import inf101.v18.rogue101.items.weapon.BasicBow;
import inf101.v18.rogue101.items.weapon.BasicSword;
import inf101.v18.rogue101.items.weapon.FireStaff;
import inf101.v18.rogue101.items.weapon.MagicWeapon;
import inf101.v18.rogue101.items.weapon.MeleeWeapon;
import inf101.v18.rogue101.items.weapon.RangedWeapon;
import inf101.v18.rogue101.items.weapon.Weapon;
import inf101.v18.rogue101.map.AGameMap;
import inf101.v18.rogue101.map.GameMap;
import inf101.v18.rogue101.map.MapReader;
import inf101.v18.rogue101.map.MapView;
import inf101.v18.rogue101.object.Actor;
import inf101.v18.rogue101.object.Dust;
import inf101.v18.rogue101.object.FakeWall;
import inf101.v18.rogue101.object.Item;
import inf101.v18.rogue101.object.NonPlayerCharacter;
import inf101.v18.rogue101.object.Player;
import inf101.v18.rogue101.object.PlayerCharacter;
import inf101.v18.rogue101.object.StairsDown;
import inf101.v18.rogue101.object.StairsUp;
import inf101.v18.rogue101.object.Wall;
import inf101.v18.rogue101.state.AttackType;
import inf101.v18.rogue101.state.Sound;
import inf101.v18.util.NPCHelper;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.function.Supplier;
public class RogueGame implements Game {
/**
* All the IActors that have things left to do this turn
*/
private List<Actor> actors = Collections.synchronizedList(new ArrayList<>());
/**
* For fancy solution to factory problem
*/
private final Map<String, Supplier<Item>> itemFactories = new HashMap<>();
/**
* Useful random generator
*/
private final Random random = new Random();
/**
* Saves the last three messages
*/
private final List<String> lastMessages = new ArrayList<>();
/**
* The game map. {@link GameMap} gives us a few more details than
* {@link MapView} (write access to item lists); the game needs this but
* individual items don't.
*/
private GameMap map;
private final List<GameMap> maps = new ArrayList<>();
private int currentLVL = 0;
private Actor currentActor;
private Location currentLocation;
private int movePoints = 0;
private final ITurtle painter;
private final Printer printer;
private int numberOfPlayers = 0;
private boolean won = false;
private List<Location> visible = null;
public RogueGame(Screen screen, ITurtle painter, Printer printer) {
this.painter = painter;
this.printer = printer;
addFactory();
// NOTE: in a more realistic situation, we will have multiple levels (one map
// per level), and (at least for a Roguelike game) the levels should be
// generated
//
// inputGrid will be filled with single-character strings indicating what (if
// anything)
// should be placed at that map square
loadMap("level1.txt", 1);
loadMap("level2.txt", 2);
loadMap("level3.txt", 3);
loadMap("level4.txt", 4);
loadMap("level5.txt", 5);
map = maps.get(0);
map.add(map.getLocation(3, 3), new Player()); //We must be sure there is never more than one player
// Prints some helpful information.
String[] info = {"Controls:", "WASD or arrow keys for movement", "E to pick up an item", "Q to drop an item", "1-0 to choose an item (10=0)", "N to change name", "ENTER to confirm", "R to use a ranged attack", "F to use a magic attack", "C to use a consumable"};
for (int i = 0; i < info.length; i++) {
this.printer.printAt(Main.COLUMN_RIGHT_SIDE_START, 1 + i, info[i]);
}
}
public RogueGame(String mapString) {
printer = new Printer(1280, 720);
painter = new TurtlePainter(1280, 720);
addFactory();
IGrid<String> inputGrid = MapReader.readString(mapString);
this.map = new AGameMap(inputGrid.getArea());
for (Location loc : inputGrid.locations()) {
Item item = createItem(inputGrid.get(loc));
if (item != null) {
map.add(loc, item);
}
}
}
@Override
public void addItem(Item item) {
map.add(currentLocation, item);
}
@Override
public void addItem(String sym) {
Item item = createItem(sym);
if (item != null) {
map.add(currentLocation, item);
}
}
/**
* Goes up one floor if possible.
*/
public void goUp() {
if (currentLVL + 1 < maps.size()) {
map = maps.get(++currentLVL);
if (!map.has(currentLocation, currentActor)) {
map.add(currentLocation, currentActor);
}
actors = new ArrayList<>();
displayMessage("You went up the stairs");
}
}
/**
* Goes down one floor if possible.
*/
public void goDown() {
if (currentLVL > 0) {
map = maps.get(--currentLVL);
if (!map.has(currentLocation, currentActor)) {
map.add(currentLocation, currentActor);
}
actors = new ArrayList<>();
displayMessage("You went down the stairs");
}
}
/**
* Calculates the attack of an IActor based on equipped items.
*
* @return The attack
*/
private int getAttack(AttackType type) {
int attack = currentActor.getAttack() + random.nextInt(20) + 1;
Weapon weapon = NPCHelper.getWeapon(type, currentActor);
if (weapon != null) {
attack += weapon.getWeaponAttack();
}
return attack;
}
/**
* Gets the defence of the current target.
*
* @param target The target to evaluate
* @return The defence of the target
*/
private int getDefence(Item target) {
int defence = target.getDefense() + 10;
Actor actor = (Actor) target;
BuffItem item = (BuffItem) actor.getItem(BuffItem.class);
if (item != null) {
defence += item.getBuffDefene();
}
return defence;
}
/**
* Gets the damage done against the current target.
*
* @param target The target to evaluate.
* @return The damage done to the target.
*/
private int getDamage(Item target, AttackType type) {
int damage = currentActor.getDamage();
Weapon weapon = NPCHelper.getWeapon(type, currentActor);
if (weapon != null) {
damage += weapon.getWeaponDamage();
}
BuffItem buff = (BuffItem) currentActor.getItem(BuffItem.class);
if (buff != null) {
damage += buff.getBuffDamage();
}
BuffItem item = (BuffItem) ((Actor) target).getItem(BuffItem.class);
if (item != null) {
damage -= item.getBuffDamageReduction();
}
return damage;
}
@Override
public Location attack(GridDirection dir, Item target) {
Location loc = currentLocation.go(dir);
if (!map.has(loc, target)) {
throw new IllegalMoveException("Target isn't there!");
}
Weapon weapon = (Weapon) currentActor.getItem(MeleeWeapon.class);
if (weapon != null) {
weapon.getSound().play();
} else {
Sound.MELEE_NO_WEAPON.play();
}
if (getAttack(AttackType.MELEE) >= getDefence(target)) {
int actualDamage = target.handleDamage(this, target, getDamage(target, AttackType.MELEE));
if (currentActor != null) {
formatMessage("%s hits %s for %d damage", currentActor.getName(), target.getName(), actualDamage);
}
} else {
formatMessage("%s tried to hit %s, but missed", currentActor.getName(), target.getName());
}
map.clean(loc);
if (target.isDestroyed() && currentLocation != null) {
return move(dir);
} else {
movePoints--;
return currentLocation;
}
}
@Override
public Location rangedAttack(GridDirection dir, Item target, AttackType type) {
Location loc = currentLocation;
Weapon weapon = null;
switch (type) {
case MAGIC:
weapon = (Weapon) currentActor.getItem(MagicWeapon.class);
break;
case RANGED:
weapon = (Weapon) currentActor.getItem(RangedWeapon.class);
}
if (weapon != null) {
weapon.getSound().play();
} else {
Sound.RANGED_NO_WEAPON.play();
}
if (getAttack(type) >= getDefence(target)) {
int damage = getDamage(target, type) / loc.gridDistanceTo(map.getLocation(target));
int actualDamage = target.handleDamage(this, target, damage);
formatMessage("%s hits %s for %d damage", currentActor.getName(), target.getName(), actualDamage);
} else {
formatMessage("%s tried to hit %s, but missed", currentActor.getName(), target.getName());
}
map.clean(map.getLocation(target));
if (target.isDestroyed() && map.has(currentLocation.go(dir), target)) {
return move(dir);
} else {
return currentLocation;
}
}
/**
* Begin a new game turn, or continue to the previous turn
*
* @return True if the game should wait for more user input
*/
public boolean doTurn() {
do {
if (actors.isEmpty()) {
// System.err.println("new turn!");
// no one in the queue, we're starting a new turn!
// first collect all the actors:
beginTurn();
}
/*if (random.nextInt(100) < 20) {
ILocation loc = map.getLocation(random.nextInt(map.getWidth()), random.nextInt(map.getHeight()));
if (!map.hasActors(loc) && !map.hasItems(loc) && !map.hasWall(loc)) {
map.add(loc, new Carrot());
}
}*/ //We don't want this in the actual game.
// process actors one by one; for the IPlayer, we return and wait for keypresses
// Possible for INonPlayer, we could also return early (returning
// *false*), and then insert a little timer delay between each non-player move
// (the timer
// is already set up in Main)
if (numberOfPlayers == 0 && !won) {
kill();
}
while (!actors.isEmpty()) {
// get the next player or non-player in the queue
currentActor = actors.remove(0);
if (currentActor == null) {
return false; //TODO: Find out why a girl suddenly becomes null (only after map change, not caught in beginTurn, happens randomly)
}
// skip if it's dead
if (currentActor.isDestroyed()) {
continue;
}
currentLocation = map.getLocation(currentActor);
if (currentLocation == null) {
displayDebug("doTurn(): Whoops! Actor has disappeared from the map: " + currentActor);
}
movePoints = 1; // everyone gets to do one thing
visible = null;
if (currentActor instanceof NonPlayerCharacter) {
// computer-controlled players do their stuff right away
((NonPlayerCharacter) currentActor).doTurn(this);
// remove any dead items from current location
map.clean(currentLocation);
return false;
} else if (currentActor instanceof PlayerCharacter) {
if (!currentActor.isDestroyed()) {
// For the human player, we need to wait for input, so we just return.
// Further keypresses will cause keyPressed() to be called, and once the human
// makes a move, it'll lose its movement point and doTurn() will be called again
//
// NOTE: currentActor and currentLocation are set to the IPlayer (above),
// so the game remembers who the player is whenever new keypresses occur. This
// is also how e.g., getLocalItems() work the game always keeps track of
// whose turn it is.
return true;
}
} else {
displayDebug("doTurn(): Hmm, this is a very strange actor: " + currentActor);
}
}
} while (numberOfPlayers > 0); // we can safely repeat if we have players, since we'll return (and break out of
// the loop) once we hit the player
return true;
}
/**
* Player is dead. It needs to be properly killed off.
*/
private void kill() {
map.remove(currentLocation, currentActor);
currentActor = null;
currentLocation = null;
actors = new ArrayList<>();
loadMap("gameover.txt");
Sound.GAME_OVER.play();
}
public void win() { //Trigger when the boss dies
map.remove(currentLocation, currentActor);
currentActor = null;
currentLocation = null;
actors = new ArrayList<>();
loadMap("victory.txt");
map.draw(painter, printer);
Sound.WIN.play();
won = true;
}
/**
* Loads a map with the desired name
*
* @param mapName Name of map, including extension.
*/
private void loadMap(String mapName) {
IGrid<String> inputGrid = MapReader.readFile("maps/" + mapName);
if (inputGrid == null) {
System.err.println("Map not found falling back to builtin map");
inputGrid = MapReader.readString(Main.BUILTIN_MAP);
}
GameMap map = new AGameMap(inputGrid.getArea());
for (Location loc : inputGrid.locations()) {
Item item = createItem(inputGrid.get(loc));
if (item != null) {
map.add(loc, item);
}
}
this.map = map;
}
private void loadMap(String mapName, int lvl) {
IGrid<String> inputGrid = MapReader.readFile("maps/" + mapName);
if (inputGrid == null) {
System.err.println("Map not found falling back to builtin map");
inputGrid = MapReader.readString(Main.BUILTIN_MAP);
}
GameMap map = new AGameMap(inputGrid.getArea());
for (Location loc : inputGrid.locations()) {
Item item = createItem(inputGrid.get(loc));
if (item instanceof Chest) {
((Chest) item).fill(lvl);
} else if (item instanceof Girl) {
((Girl) item).giveWeapon(lvl);
}
if (item != null) {
map.add(loc, item);
}
}
maps.add(map);
}
/**
* Go through the map and collect all the actors.
*/
private void beginTurn() {
numberOfPlayers = 0;
// this extra fancy iteration over each map location runs *in parallel* on
// multicore systems!
// that makes some things more tricky, hence the "synchronized" block and
// "Collections.synchronizedList()" in the initialization of "actors".
// NOTE: If you want to modify this yourself, it might be a good idea to replace
// "parallelStream()" by "stream()", because weird things can happen when many
// things happen
// at the same time! (or do INF214 or DAT103 to learn about locks and threading)
map.getArea().parallelStream().forEach((loc) -> { // will do this for each location in map
List<Item> list = map.getAllModifiable(loc); // all items at loc
Iterator<Item> li = list.iterator(); // manual iterator lets us remove() items
while (li.hasNext()) { // this is what "for(IItem item : list)" looks like on the inside
Item item = li.next();
if (item.getCurrentHealth() < 0) {
// normally, we expect these things to be removed when they are destroyed, so
// this shouldn't happen
synchronized (this) {
formatDebug("beginTurn(): found and removed leftover destroyed item %s '%s' at %s%n",
item.getName(), item.getSymbol(), loc);
}
li.remove();
map.remove(loc, item); // need to do this too, to update item map
} else if (item instanceof PlayerCharacter) {
actors.add(0, (Actor) item); // we let the human player go first
synchronized (this) {
numberOfPlayers++;
}
} else if (item instanceof Actor) {
actors.add((Actor) item); // add other actors to the end of the list
} else if (item instanceof Carrot) {
((Carrot) item).doTurn();
}
}
});
}
@Override
public boolean canGo(GridDirection dir) {
return map.canGo(currentLocation, dir);
}
private void addFactory() {
itemFactories.put("#", Wall::new);
itemFactories.put("@", Player::new);
itemFactories.put("C", Carrot::new);
itemFactories.put("R", Rabbit::new);
itemFactories.put("M", Manga::new);
itemFactories.put("G", Girl::new);
itemFactories.put(".", Dust::new);
itemFactories.put("S", BasicSword::new);
itemFactories.put("c", Chest::new);
itemFactories.put("B", Boss::new);
itemFactories.put("s", FireStaff::new);
itemFactories.put("b", BasicBow::new);
itemFactories.put("H", HealthPotion::new);
itemFactories.put("=", FakeWall::new);
itemFactories.put("<", StairsUp::new);
itemFactories.put(">", StairsDown::new);
itemFactories.put("m", Binoculars::new);
itemFactories.put("f", Shield::new);
}
@Override
public Item createItem(String symbol) {
if (" ".equals(symbol)) {
return null;
}// alternative/advanced method
Supplier<Item> factory = itemFactories.get(symbol);
if (factory != null) {
return factory.get();
} else {
System.err.println("createItem: Don't know how to create a '" + symbol + "'");
return null;
}
}
@Override
public void displayDebug(String s) {
printer.clearLine(Main.LINE_DEBUG);
printer.printAt(1, Main.LINE_DEBUG, s, Color.DARKRED);
System.err.println(s);
}
@Override
public void displayMessage(String s) {
if (lastMessages.size() >= 3) {
lastMessages.remove(2);
}
lastMessages.add(0, s);
printer.clearLine(Main.LINE_MSG1);
printer.clearLine(Main.LINE_MSG2);
printer.clearLine(Main.LINE_MSG3);
int maxLen = 80; //The maximum length of a message to not overflow.
boolean secondLineWritten = false;
boolean thirdLineWritten = false;
//Makes long messages overflow to the next line.
if (lastMessages.size() > 0) {
String message = lastMessages.get(0);
if (message.length() > 2 * maxLen) {
printer.printAt(1, Main.LINE_MSG1, message.substring(0, maxLen));
printer.printAt(1, Main.LINE_MSG2, message.substring(maxLen, 2 * maxLen));
printer.printAt(1, Main.LINE_MSG3, message.substring(2 * maxLen));
secondLineWritten = thirdLineWritten = true;
} else if (message.length() > maxLen) {
printer.printAt(1, Main.LINE_MSG1, message.substring(0, maxLen));
printer.printAt(1, Main.LINE_MSG2, message.substring(maxLen));
secondLineWritten = true;
} else {
printer.printAt(1, Main.LINE_MSG1, message);
}
}
if (lastMessages.size() > 1 && !secondLineWritten) {
String message = lastMessages.get(1);
if (message.length() > maxLen) {
printer.printAt(1, Main.LINE_MSG2, message.substring(0, maxLen));
printer.printAt(1, Main.LINE_MSG3, message.substring(maxLen));
thirdLineWritten = true;
} else {
printer.printAt(1, Main.LINE_MSG2, message);
}
}
if (lastMessages.size() > 2 && !thirdLineWritten) {
printer.printAt(1, Main.LINE_MSG3, lastMessages.get(2));
}
//System.out.println("Message: «" + s + "»");
}
@Override
public void displayStatus(String s) {
printer.clearLine(Main.LINE_STATUS);
printer.printAt(1, Main.LINE_STATUS, s);
//System.out.println("Status: «" + s + "»");
}
public void draw() {
if (numberOfPlayers == 0) {
map.draw(painter, printer);
} else {
((AGameMap) map).drawVisible(painter, printer);
}
}
@Override
public boolean drop(Item item) {
if (item != null) {
map.add(currentLocation, item);
return true;
} else {
return false;
}
}
@Override
public boolean dropAt(Location loc, Item item) {
if (item != null) {
map.add(loc, item);
return true;
} else {
return false;
}
}
@Override
public void formatDebug(String s, Object... args) {
displayDebug(String.format(s, args));
}
@Override
public void formatMessage(String s, Object... args) {
displayMessage(String.format(s, args));
}
@Override
public void formatStatus(String s, Object... args) {
displayStatus(String.format(s, args));
}
@Override
public int getHeight() {
return map.getHeight();
}
@Override
public List<Item> getLocalItems() {
return map.getItems(currentLocation);
}
@Override
public Location getLocation() {
return currentLocation;
}
@Override
public Location getLocation(GridDirection dir) {
if (currentLocation.canGo(dir)) {
return currentLocation.go(dir);
} else {
return null;
}
}
/**
* Return the game map. {@link GameMap} gives us a few more details than
* {@link MapView} (write access to item lists); the game needs this but
* individual items don't.
*/
@Override
public MapView getMap() {
return map;
}
@Override
public List<GridDirection> getPossibleMoves() {
List<GridDirection> moves = new ArrayList<>();
for (GridDirection dir : GridDirection.FOUR_DIRECTIONS) {
if (canGo(dir)) {
moves.add(dir);
}
}
return moves;
}
@Override
public List<Location> getVisible() {
if (this.visible != null) {
return this.visible;
}
List<Location> neighbours = this.map.getNeighbourhood(this.currentLocation, this.currentActor.getVision());
List<Location> invalid = new ArrayList<>();
for (Location neighbour : neighbours) {
for (Location tile : this.currentLocation.gridLineTo(neighbour)) {
if (this.map.hasWall(tile)) {
invalid.add(neighbour);
break;
}
}
}
neighbours.removeAll(invalid);
this.visible = neighbours;
return neighbours;
}
@Override
public int getWidth() {
return this.map.getWidth();
}
public boolean keyPressed(KeyCode code) {
// only an IPlayer/human can handle keypresses, and only if it's the human's
// turn
return !(currentActor instanceof PlayerCharacter) || !((PlayerCharacter) currentActor).keyPressed(this, code);
}
@Override
public Location move(GridDirection dir) {
if (movePoints < 1) {
throw new IllegalMoveException("You're out of moves!");
}
Location newLoc = map.go(currentLocation, dir);
map.remove(currentLocation, currentActor);
map.add(newLoc, currentActor);
currentLocation = newLoc;
movePoints--;
return currentLocation;
}
@Override
public Item pickUp(Item item) {
if (item != null && map.has(currentLocation, item) && !(item instanceof Static)) {
if (item instanceof Actor) {
if (item.getCurrentHealth() / item.getMaxHealth() < 3) {
map.remove(currentLocation, item);
return item;
} else {
return null;
}
} else if (currentActor.getAttack() > item.getDefense()) {
map.remove(currentLocation, item);
return item;
} else {
return null;
}
} else {
return null;
}
}
@Override
public ITurtle getPainter() {
return painter;
}
@Override
public Printer getPrinter() {
return printer;
}
@Override
public int[] getFreeTextAreaBounds() {
int[] area = new int[4];
area[0] = getWidth() + 1;
area[1] = 1;
area[2] = printer.getLineWidth();
area[3] = printer.getPageHeight() - 5;
return area;
}
@Override
public void clearFreeTextArea() {
printer.clearRegion(getWidth() + 1, 1, printer.getLineWidth() - getWidth(), printer.getPageHeight() - 5);
}
@Override
public void clearFreeGraphicsArea() {
painter.as(GraphicsContext.class).clearRect(getWidth() * printer.getCharWidth(), 0,
painter.getWidth() - getWidth() * printer.getCharWidth(),
(printer.getPageHeight() - 5) * printer.getCharHeight());
}
@Override
public double[] getFreeGraphicsAreaBounds() {
double[] area = new double[4];
area[0] = getWidth() * printer.getCharWidth();
area[1] = 0;
area[2] = painter.getWidth();
area[3] = getHeight() * printer.getCharHeight();
return area;
}
@Override
public Actor getActor() {
return currentActor;
}
public Location setCurrent(Actor actor) {
currentLocation = map.getLocation(actor);
if (currentLocation != null) {
currentActor = actor;
movePoints = 1;
}
return currentLocation;
}
public Actor setCurrent(Location loc) {
List<Actor> list = map.getActors(loc);
if (!list.isEmpty()) {
currentActor = list.get(0);
currentLocation = loc;
movePoints = 1;
}
return currentActor;
}
public Actor setCurrent(int x, int y) {
return setCurrent(map.getLocation(x, y));
}
@Override
public Random getRandom() {
return random;
}
@Override
public List<GridDirection> locationDirection(Location start, Location target) {
int targetX = target.getX(), targetY = target.getY();
int startX = start.getX(), startY = start.getY();
List<GridDirection> dirs = new ArrayList<>();
boolean yDifferenceIsLarger = Math.abs(targetX - startX) < Math.abs(targetY - startY);
if (targetX > startX && targetY > startY) {
if (yDifferenceIsLarger) {
dirs.add(GridDirection.SOUTH);
dirs.add(GridDirection.EAST);
} else {
dirs.add(GridDirection.EAST);
dirs.add(GridDirection.SOUTH);
}
} else if (targetX > startX && targetY < startY) {
if (yDifferenceIsLarger) {
dirs.add(GridDirection.NORTH);
dirs.add(GridDirection.EAST);
} else {
dirs.add(GridDirection.EAST);
dirs.add(GridDirection.NORTH);
}
} else if (targetX < startX && targetY > startY) {
if (yDifferenceIsLarger) {
dirs.add(GridDirection.SOUTH);
dirs.add(GridDirection.WEST);
} else {
dirs.add(GridDirection.WEST);
dirs.add(GridDirection.SOUTH);
}
} else if (targetX < startX && targetY < startY) {
if (yDifferenceIsLarger) {
dirs.add(GridDirection.NORTH);
dirs.add(GridDirection.WEST);
} else {
dirs.add(GridDirection.WEST);
dirs.add(GridDirection.NORTH);
}
} else if (targetX > startX) {
dirs.add(GridDirection.EAST);
} else if (targetX < startX) {
dirs.add(GridDirection.WEST);
} else if (targetY > startY) {
dirs.add(GridDirection.SOUTH);
} else if (targetY < startY) {
dirs.add(GridDirection.NORTH);
}
return dirs;
}
}

View File

@ -1,9 +0,0 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.objects.IItem;
public interface IConsumable extends IItem {
int hpIncrease();
int attackIncrease();
int defenceIncrease();
}

View File

@ -1,12 +0,0 @@
package inf101.v18.rogue101.items;
/**
* An interface to extinguish different weapons for specific NPC.
*/
public interface IMagicWeapon extends IWeapon {
@Override
default String getSound() {
return "audio/Large Fireball-SoundBible.com-301502490.wav";
}
}

View File

@ -1,12 +0,0 @@
package inf101.v18.rogue101.items;
/**
* An interface to extinguish different weapons for specific NPC.
*/
public interface IMeleeWeapon extends IWeapon {
@Override
default String getSound() {
return "audio/Sword Swing-SoundBible.com-639083727.wav";
}
}

View File

@ -1,12 +0,0 @@
package inf101.v18.rogue101.items;
/**
* An interface to extinguish different weapons for specific NPC.
*/
public interface IRangedWeapon extends IWeapon {
@Override
default String getSound() {
return "audio/Bow_Fire_Arrow-Stephan_Schutze-2133929391.wav";
}
}

View File

@ -1,15 +0,0 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.objects.IItem;
public interface IStatic extends IItem {
@Override
default int getDefence() {
return 0;
}
@Override
default int getSize() {
return 10000;
}
}

View File

@ -1,26 +0,0 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.objects.IItem;
public interface IWeapon extends IItem {
/**
* Retrieves the damage points of a weapon.
*
* @return An int
*/
int getWeaponDamage();
/**
* Returns the attack ponts of a weapon.
*
* @return an int
*/
int getWeaponAttack();
/**
* Retrieves the string path of the sound to play upon an attack.
*
* @return A string path
*/
String getSound();
}

View File

@ -1,9 +1,9 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.buff;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
public class Binoculars implements IBuffItem {
public class Binoculars implements BuffItem {
@Override
public int getBuffVisibility() {
@ -16,7 +16,7 @@ public class Binoculars implements IBuffItem {
}
@Override
public int getDefence() {
public int getDefense() {
return 0;
}
@ -46,7 +46,7 @@ public class Binoculars implements IBuffItem {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
return 0;
}
}

View File

@ -1,12 +1,16 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.buff;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.object.Item;
/**
* An item that increases one or more of a player's stats
*/
public interface BuffItem extends Item {
public interface IBuffItem extends IItem {
/**
* Retrieve damage increase done by the buff item.
*
* @return An int, May be 0
* @return An int, May be 0
*/
default int getBuffDamage() {
return 0;
@ -15,16 +19,16 @@ public interface IBuffItem extends IItem {
/**
* Retrieve defence increase done by the buff item.
*
* @return An int, May be 0
* @return An int, May be 0
*/
default int getBuffDefence() {
default int getBuffDefene() {
return 0;
}
/**
* Retrieve defence increase done by the buff item.
*
* @return An int, May be 0
* @return An int, May be 0
*/
default int getBuffDamageReduction() {
return 0;
@ -33,9 +37,10 @@ public interface IBuffItem extends IItem {
/**
* Retrieve visibility increase done by the buff item.
*
* @return An int, May be 0
* @return An int, May be 0
*/
default int getBuffVisibility() {
return 0;
}
}

View File

@ -1,13 +1,13 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.buff;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
public class Shield implements IBuffItem {
public class Shield implements BuffItem {
private final int hp = getMaxHealth();
@Override
public int getBuffDefence() {
public int getBuffDefene() {
return 10;
}
@ -22,7 +22,7 @@ public class Shield implements IBuffItem {
}
@Override
public int getDefence() {
public int getDefense() {
return 0;
}
@ -52,7 +52,7 @@ public class Shield implements IBuffItem {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
return 0;
}
}

View File

@ -0,0 +1,11 @@
package inf101.v18.rogue101.items.consumable;
import inf101.v18.rogue101.object.Item;
public interface Consumable extends Item {
int hpIncrease();
int attackIncrease();
int defenseIncrease();
}

View File

@ -1,9 +1,13 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.consumable;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
/**
* A consumable that restores 100 health points
*/
public class HealthPotion implements Consumable {
public class HealthPotion implements IConsumable {
@Override
public int hpIncrease() {
return 100;
@ -15,7 +19,7 @@ public class HealthPotion implements IConsumable {
}
@Override
public int defenceIncrease() {
public int defenseIncrease() {
return 0;
}
@ -25,7 +29,7 @@ public class HealthPotion implements IConsumable {
}
@Override
public int getDefence() {
public int getDefense() {
return 0;
}
@ -50,7 +54,8 @@ public class HealthPotion implements IConsumable {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
return 0;
}
}

View File

@ -1,9 +1,13 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.consumable;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
/**
* A consumable that increases attack and defense permanently
*/
public class Manga implements Consumable {
public class Manga implements IConsumable {
private int hp = getMaxHealth();
@Override
@ -12,7 +16,7 @@ public class Manga implements IConsumable {
}
@Override
public int getDefence() {
public int getDefense() {
return 0;
}
@ -42,7 +46,7 @@ public class Manga implements IConsumable {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
hp -= amount;
return amount;
}
@ -58,7 +62,8 @@ public class Manga implements IConsumable {
}
@Override
public int defenceIncrease() {
public int defenseIncrease() {
return 5;
}
}

View File

@ -1,17 +1,17 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.container;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Backpack implements IContainer {
public class Backpack implements Container {
/**
* A list containing everything in the backpack.
*/
private final List<IItem> content = new ArrayList<>();
private final List<Item> content = new ArrayList<>();
/**
* The maximum amount of items allowed in a single backpack.
*/
@ -23,7 +23,7 @@ public class Backpack implements IContainer {
}
@Override
public int getDefence() {
public int getDefense() {
return 0;
}
@ -48,7 +48,7 @@ public class Backpack implements IContainer {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
return 0;
}
@ -64,7 +64,7 @@ public class Backpack implements IContainer {
/**
* Checks if the Backpack is empty
*
* @return True if empty. False otherwise
* @return True if empty. False otherwise
*/
public boolean isEmpty() {
return content.isEmpty();
@ -73,10 +73,10 @@ public class Backpack implements IContainer {
/**
* Tries to add an item to the Backpack
*
* @param item The item to add
* @return True if the item was added. False if the backpack is full
* @param item The item to add
* @return True if the item was added. False if the backpack is full
*/
public boolean add(IItem item) {
public boolean add(Item item) {
if (size() < MAX_SIZE) {
content.add(item);
return true;
@ -93,9 +93,9 @@ public class Backpack implements IContainer {
/**
* Removes item from the backpack.
*
* @param item The item to remove
* @param item The item to remove
*/
public void remove(IItem item) {
public void remove(Item item) {
content.remove(item);
}
@ -103,14 +103,14 @@ public class Backpack implements IContainer {
* Gets a T at index i,
*
* @param i The index of an element
* @return An object of type T
* @return An object of type T
*/
public IItem get(int i) {
public Item get(int i) {
return content.get(i);
}
@Override
public boolean addItem(IItem item) {
public boolean addItem(Item item) {
if (content.size() < MAX_SIZE) {
content.add(item);
return true;
@ -122,9 +122,9 @@ public class Backpack implements IContainer {
/**
* Gets the content List for direct manipulation.
*
* @return A list of T
* @return A list of T
*/
public List<IItem> getContent() {
public List<Item> getContent() {
return Collections.unmodifiableList(content);
}
@ -134,8 +134,8 @@ public class Backpack implements IContainer {
}
@Override
public IItem getFirst(Class<?> clazz) {
for (IItem item : content) {
public Item getFirst(Class<?> clazz) {
for (Item item : content) {
if (clazz.isInstance(item)) {
return item;
}

View File

@ -1,15 +1,22 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.container;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.items.buff.Binoculars;
import inf101.v18.rogue101.items.buff.Shield;
import inf101.v18.rogue101.items.consumable.HealthPotion;
import inf101.v18.rogue101.items.consumable.Manga;
import inf101.v18.rogue101.items.weapon.BasicBow;
import inf101.v18.rogue101.items.weapon.BasicSword;
import inf101.v18.rogue101.items.weapon.FireStaff;
import inf101.v18.rogue101.object.Item;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Chest implements IContainer, IStatic {
private final List<IItem> container;
public class Chest implements Container, Static {
private final List<Item> container;
private final int MAX_SIZE = 10;
public Chest() {
@ -19,15 +26,15 @@ public class Chest implements IContainer, IStatic {
/**
* Randomly fills chest with random items based on dungeon level.
*
* @param lvl The current dungeon level
* @param lvl The current dungeon level
*/
public void fill (int lvl) {
public void fill(int lvl) {
Random random = new Random();
int itemChance = 3;
List<IItem> items = new ArrayList<>();
items.add(new Staff());
items.add(new Sword());
items.add(new Bow());
List<Item> items = new ArrayList<>();
items.add(new FireStaff());
items.add(new BasicSword());
items.add(new BasicBow());
items.add(new Binoculars());
items.add(new Shield());
items.add(new Manga());
@ -49,12 +56,12 @@ public class Chest implements IContainer, IStatic {
}
@Override
public IItem get(int i) {
public Item get(int i) {
return container.get(i);
}
@Override
public List<IItem> getContent() {
public List<Item> getContent() {
return Collections.unmodifiableList(container);
}
@ -64,8 +71,8 @@ public class Chest implements IContainer, IStatic {
}
@Override
public IItem getFirst(Class<?> clazz) {
for (IItem item : container) {
public Item getFirst(Class<?> clazz) {
for (Item item : container) {
if (clazz.isInstance(item)) {
return item;
}
@ -103,12 +110,12 @@ public class Chest implements IContainer, IStatic {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
return 0;
}
@Override
public boolean addItem(IItem item) {
public boolean addItem(Item item) {
if (container.size() < MAX_SIZE) {
container.add(item);
return true;

View File

@ -1,10 +1,10 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.container;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.object.Item;
import java.util.List;
public interface IContainer extends IItem {
public interface Container extends Item {
/**
* Retrieves an item from a container in index i
*
@ -12,22 +12,22 @@ public interface IContainer extends IItem {
* @return An IItem
* @throws IndexOutOfBoundsException If the index is out of range.
*/
IItem get(int i);
Item get(int i);
/**
* Adds an item to a container.
*
* @return True if the container was not full
* @param item The item to add to the container
* @return True if the container was not full
*/
boolean addItem(IItem item);
boolean addItem(Item item);
/**
* Gets a list with everything inside a container.
*
* @return A list of Objects extending IItem
*/
List<IItem> getContent();
List<Item> getContent();
/**
* Checks if we can add anything at all to the container.
@ -51,7 +51,7 @@ public interface IContainer extends IItem {
* @param clazz The class type to accept
* @return An IItem or null
*/
IItem getFirst(Class<?> clazz);
Item getFirst(Class<?> clazz);
/**
* Removes an element at index i from the container.

View File

@ -0,0 +1,20 @@
package inf101.v18.rogue101.items.container;
import inf101.v18.rogue101.object.Item;
/**
* A static item that cannot be kept in a player's inventory
*/
public interface Static extends Item {
@Override
default int getDefense() {
return 0;
}
@Override
default int getSize() {
return 10000;
}
}

View File

@ -1,11 +1,11 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.weapon;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
import java.util.Random;
public class Bow implements IRangedWeapon {
public class BasicBow implements RangedWeapon {
private static final Random random = new Random();
private final int damage = 3 + random.nextInt(20);
private final int hp = getMaxHealth();
@ -26,7 +26,7 @@ public class Bow implements IRangedWeapon {
}
@Override
public int getDefence() {
public int getDefense() {
return 0;
}
@ -56,7 +56,7 @@ public class Bow implements IRangedWeapon {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
return 0;
}
}

View File

@ -1,11 +1,11 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.weapon;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
import java.util.Random;
public class Sword implements IMeleeWeapon {
public class BasicSword implements MeleeWeapon {
private static final Random random = new Random();
private final int damage = 5 + random.nextInt(25);
private int hp = getMaxHealth();
@ -26,7 +26,7 @@ public class Sword implements IMeleeWeapon {
}
@Override
public int getDefence() {
public int getDefense() {
return 0;
}
@ -56,7 +56,7 @@ public class Sword implements IMeleeWeapon {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
hp -= amount;
return amount;
}

View File

@ -1,11 +1,11 @@
package inf101.v18.rogue101.items;
package inf101.v18.rogue101.items.weapon;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.object.Item;
import java.util.Random;
public class Staff implements IMagicWeapon {
public class FireStaff implements MagicWeapon {
private static final Random random = new Random();
private final int damage = 5 + random.nextInt(25);
private int hp = getMaxHealth();
@ -26,7 +26,7 @@ public class Staff implements IMagicWeapon {
}
@Override
public int getDefence() {
public int getDefense() {
return 0;
}
@ -56,7 +56,7 @@ public class Staff implements IMagicWeapon {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
hp -= amount;
return amount;
}

View File

@ -0,0 +1,15 @@
package inf101.v18.rogue101.items.weapon;
import inf101.v18.rogue101.state.Sound;
/**
* An interface to extinguish different weapons for specific NPC.
*/
public interface MagicWeapon extends Weapon {
@Override
default Sound getSound() {
return Sound.RANGED_STAFF;
}
}

View File

@ -0,0 +1,15 @@
package inf101.v18.rogue101.items.weapon;
import inf101.v18.rogue101.state.Sound;
/**
* An interface to extinguish different weapons for specific NPC.
*/
public interface MeleeWeapon extends Weapon {
@Override
default Sound getSound() {
return Sound.MELEE_SWORD;
}
}

View File

@ -0,0 +1,14 @@
package inf101.v18.rogue101.items.weapon;
import inf101.v18.rogue101.state.Sound;
/**
* An interface to extinguish different weapons for specific NPC.
*/
public interface RangedWeapon extends Weapon {
@Override
default Sound getSound() {
return Sound.RANGED_BOW;
}
}

View File

@ -0,0 +1,29 @@
package inf101.v18.rogue101.items.weapon;
import inf101.v18.rogue101.object.Item;
import inf101.v18.rogue101.state.Sound;
public interface Weapon extends Item {
/**
* Retrieves the damage points of a weapon.
*
* @return An int
*/
int getWeaponDamage();
/**
* Returns the attack points of a weapon
*
* @return <p>The attack points as an integer</p>
*/
int getWeaponAttack();
/**
* Retrieves the sound to play upon an attack
*
* @return <p>The sound to use</p>
*/
Sound getSound();
}

View File

@ -0,0 +1,446 @@
package inf101.v18.rogue101.map;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.textmode.Printer;
import inf101.v18.grid.GridDirection;
import inf101.v18.grid.IArea;
import inf101.v18.grid.IMultiGrid;
import inf101.v18.grid.Location;
import inf101.v18.grid.MultiGrid;
import inf101.v18.rogue101.Main;
import inf101.v18.rogue101.examples.Carrot;
import inf101.v18.rogue101.game.IllegalMoveException;
import inf101.v18.rogue101.items.buff.Shield;
import inf101.v18.rogue101.items.consumable.Manga;
import inf101.v18.rogue101.items.container.Backpack;
import inf101.v18.rogue101.items.container.Chest;
import inf101.v18.rogue101.items.weapon.BasicBow;
import inf101.v18.rogue101.items.weapon.BasicSword;
import inf101.v18.rogue101.items.weapon.FireStaff;
import inf101.v18.rogue101.object.Actor;
import inf101.v18.rogue101.object.FakeWall;
import inf101.v18.rogue101.object.Item;
import inf101.v18.rogue101.object.PlayerCharacter;
import inf101.v18.rogue101.object.Wall;
import javafx.scene.canvas.GraphicsContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
public class AGameMap implements GameMap {
/**
* The grid that makes up our map
*/
private final IMultiGrid<Item> grid;
/**
* These locations have changed, and need to be redrawn
*/
private final Set<Location> dirtyLocs = new HashSet<>();
/**
* An index of all the items in the map and their locations.
*/
// an IdentityHashMap uses object identity as a lookup key, so items are
// considered equal if they are the same object (a == b)
private final Map<Item, Location> items = new IdentityHashMap<>();
public AGameMap(IArea area) {
grid = new MultiGrid<>(area);
}
public AGameMap(int width, int height) {
grid = new MultiGrid<>(width, height);
}
@Override
public void add(Location loc, Item item) {
// keep track of location of all items
items.put(item, loc);
// also keep track of whether we need to redraw this cell
dirtyLocs.add(loc);
// do the actual adding
List<Item> list = grid.get(loc);
for (int i = 0; i < list.size(); i++) {
if (item.compareTo(list.get(i)) >= 0) {
list.add(i, item);
return;
}
}
list.add(item);
}
public void addRandomItems(Location loc) {
if (!this.hasActors(loc) && !this.hasWall(loc)) {
Random random = new Random();
if (random.nextInt(10) < 2) {
this.add(loc, new Carrot());
}
if (random.nextInt(10) < 1) {
this.add(loc, new Manga());
}
if (random.nextInt(2) < 1) {
this.add(loc, new Chest());
}
if (random.nextInt(2) < 1) {
this.add(loc, new BasicSword());
}
if (random.nextInt(2) < 1) {
this.add(loc, new Shield());
}
if (random.nextInt(2) < 1) {
this.add(loc, new FireStaff());
}
if (random.nextInt(2) < 1) {
this.add(loc, new BasicBow());
}
if (random.nextInt(2) < 1) {
this.add(loc, new Backpack());
}
}
}
@Override
public boolean canGo(Location to) {
return !grid.contains(to, (i) -> ((i instanceof Wall && !(i instanceof FakeWall)) || i instanceof Actor));
}
@Override
public boolean hasNeighbour(Location from, GridDirection dir) {
return from.canGo(dir);
}
@Override
public boolean canGo(Location from, GridDirection dir) {
if (!from.canGo(dir)) {
return false;
}
Location loc = from.go(dir);
return canGo(loc);
}
@Override
public void draw(ITurtle painter, Printer printer) {
Iterable<Location> cells;
if (Main.MAP_DRAW_ONLY_DIRTY_CELLS) {
if (dirtyLocs.isEmpty()) {
return;
} else {
cells = dirtyLocs;
}
} else {
cells = grid.locations();
painter.as(GraphicsContext.class).clearRect(0, 0, getWidth() * printer.getCharWidth(),
getHeight() * printer.getCharHeight());
printer.clearRegion(1, 1, getWidth(), getHeight());
}
GraphicsContext ctx = painter.as(GraphicsContext.class);
double h = printer.getCharHeight();
double w = printer.getCharWidth();
if (Main.MAP_AUTO_SCALE_ITEM_DRAW) {
ctx.save();
ctx.scale(w / h, 1.0);
w = h;
}
try {
for (Location loc : cells) {
List<Item> list = grid.get(loc);
String sym = " ";
if (!list.isEmpty()) {
if (Main.MAP_DRAW_ONLY_DIRTY_CELLS) {
ctx.clearRect(loc.getX() * w, loc.getY() * h, w, h);
// ctx.fillRect(loc.getX() * w, loc.getY() * h, w, h);
}
painter.save();
painter.jumpTo((loc.getX() + 0.5) * w, (loc.getY() + 0.5) * h);
boolean dontPrint = list.get(0).draw(painter, w, h);
painter.restore();
if (!dontPrint) {
sym = list.get(0).getPrintSymbol();
}
}
printer.printAt(loc.getX() + 1, loc.getY() + 1, sym);
}
} finally {
if (Main.MAP_AUTO_SCALE_ITEM_DRAW) {
ctx.restore();
}
}
dirtyLocs.clear();
}
/**
* Writes a black void unto the whole map.
* Properly draws only the tiles visible to the player.
*
* @param painter A painter
* @param printer A printer
*/
public void drawVisible(ITurtle painter, Printer printer) {
Iterable<Location> cells;
if (Main.MAP_DRAW_ONLY_DIRTY_CELLS) {
if (dirtyLocs.isEmpty()) {
return;
} else {
cells = dirtyLocs;
}
} else {
cells = grid.locations();
painter.as(GraphicsContext.class).clearRect(0, 0, getWidth() * printer.getCharWidth(),
getHeight() * printer.getCharHeight());
printer.clearRegion(1, 1, getWidth(), getHeight());
}
GraphicsContext ctx = painter.as(GraphicsContext.class);
double h = printer.getCharHeight();
double w = printer.getCharWidth();
if (Main.MAP_AUTO_SCALE_ITEM_DRAW) {
ctx.save();
ctx.scale(w / h, 1.0);
w = h;
}
try {
PlayerCharacter player = null;
Location playerPos = null;
for (Location loc : cells) {
printer.printAt(loc.getX() + 1, loc.getY() + 1, " ");
//We need to get the player and its location from somewhere.
if (this.hasActors(loc) && this.getActors(loc).get(0) instanceof PlayerCharacter) {
player = (PlayerCharacter) this.getActors(loc).get(0);
playerPos = loc;
}
}
if (player == null) {
return;
}
List<Location> positions = getVisible(getNeighbourhood(playerPos, player.getVision()), playerPos);
positions.add(playerPos);
for (Location loc : positions) {
List<Item> list = grid.get(loc);
String sym = ".";
if (!list.isEmpty()) {
if (Main.MAP_DRAW_ONLY_DIRTY_CELLS) {
ctx.clearRect(loc.getX() * w, loc.getY() * h, w, h);
// ctx.fillRect(loc.getX() * w, loc.getY() * h, w, h);
}
painter.save();
painter.jumpTo((loc.getX() + 0.5) * w, (loc.getY() + 0.5) * h);
boolean dontPrint = list.get(0).draw(painter, w, h);
painter.restore();
if (!dontPrint) {
sym = list.get(0).getPrintSymbol();
}
}
printer.printAt(loc.getX() + 1, loc.getY() + 1, sym);
}
} finally {
if (Main.MAP_AUTO_SCALE_ITEM_DRAW) {
ctx.restore();
}
}
dirtyLocs.clear();
}
private List<Location> getVisible(List<Location> neighbours, Location loc) {
List<Location> invalid = new ArrayList<>();
for (Location neighbour : neighbours) {
if (!hasWall(neighbour)) {
for (Location tile : loc.gridLineTo(neighbour)) {
if (hasWall(tile)) {
invalid.add(neighbour);
break;
}
}
}
}
neighbours.removeAll(invalid);
return neighbours;
}
@Override
public List<Actor> getActors(Location loc) {
List<Actor> items = new ArrayList<>();
for (Item item : grid.get(loc)) {
if (item instanceof Actor) {
items.add((Actor) item);
}
}
return items;
}
@Override
public List<Item> getAll(Location loc) {
return Collections.unmodifiableList(grid.get(loc));
}
@Override
public List<Item> getAllModifiable(Location loc) {
dirtyLocs.add(loc);
return grid.get(loc);
}
@Override
public void clean(Location loc) {
// remove any items that have health < 0:
if (grid.get(loc).removeIf((item) -> {
if (item.isDestroyed()) {
items.remove(item);
return true;
} else {
return false;
}
})) {
dirtyLocs.add(loc);
}
}
@Override
public IArea getArea() {
return grid.getArea();
}
@Override
public int getHeight() {
return grid.getHeight();
}
@Override
public List<Item> getItems(Location loc) {
List<Item> items = new ArrayList<>(grid.get(loc));
items.removeIf((i) -> i instanceof Actor);
return items;
}
@Override
public Location getLocation(Item item) {
return items.get(item);
}
@Override
public Location getLocation(int x, int y) {
return grid.getArea().location(x, y);
}
@Override
public Location getNeighbour(Location from, GridDirection dir) {
if (!hasNeighbour(from, dir)) {
return null;
} else {
return from.go(dir);
}
}
@Override
public int getWidth() {
return grid.getWidth();
}
@Override
public Location go(Location from, GridDirection dir) throws IllegalMoveException {
if (!from.canGo(dir)) {
throw new IllegalMoveException("Cannot move outside map!");
}
Location loc = from.go(dir);
if (!canGo(loc)) {
throw new IllegalMoveException("Occupied!");
}
return loc;
}
@Override
public boolean has(Location loc, Item target) {
return grid.contains(loc, target);
}
@Override
public boolean hasActors(Location loc) {
return grid.contains(loc, (i) -> i instanceof Actor);
}
@Override
public boolean hasItems(Location loc) {
// true if grid cell contains an item which is not an IActor
return grid.contains(loc, (i) -> !(i instanceof Actor));
}
@Override
public boolean hasWall(Location loc) {
return grid.contains(loc, (i) -> i instanceof Wall);
}
@Override
public void remove(Location loc, Item item) {
grid.remove(loc, item);
items.remove(item);
dirtyLocs.add(loc);
}
@Override
public List<Location> getNeighbourhood(Location startLocation, int distance) {
if (distance < 0 || startLocation == null) {
throw new IllegalArgumentException();
} else if (distance == 0) {
return new ArrayList<>(); // empty!
}
// Run BFS to find all neighbors within the specified distance
Queue<Location> queue = new LinkedList<>();
List<Location> explored = new ArrayList<>();
explored.add(startLocation);
queue.add(startLocation);
while (!queue.isEmpty()) {
Location location = queue.poll();
// The required distance has been reached
if (Math.abs(startLocation.getX() - location.getX()) >= distance ||
Math.abs(startLocation.getY() - location.getY()) >= distance) {
break;
}
for (GridDirection gridDirection : GridDirection.EIGHT_DIRECTIONS) {
addIfValid(queue, explored, location, gridDirection);
}
}
// While the BFS requires the start location, it's not considered its own neighbor
explored.remove(startLocation);
return explored;
}
/**
* Adds the specified location to the queue if valid
*
* @param queue <p>The queue to add the location to</p>
* @param explored <p>The already explored locations</p>
* @param startLocation <p>The location to start at</p>
* @param direction <p>The direction to go</p>
*/
private void addIfValid(Queue<Location> queue, List<Location> explored, Location startLocation,
GridDirection direction) {
Location location;
// If going in the specified direction would exit the map, just return
try {
location = startLocation.go(direction);
} catch (IndexOutOfBoundsException ignored) {
return;
}
if (!explored.contains(location) && grid.isValid(location)) {
explored.add(location);
queue.add(location);
}
}
}

View File

@ -1,393 +1,48 @@
package inf101.v18.rogue101.map;
import java.util.*;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.textmode.Printer;
import inf101.v18.grid.GridDirection;
import inf101.v18.grid.IArea;
import inf101.v18.grid.ILocation;
import inf101.v18.grid.IMultiGrid;
import inf101.v18.grid.MultiGrid;
import inf101.v18.rogue101.Main;
import inf101.v18.rogue101.examples.Carrot;
import inf101.v18.rogue101.game.IllegalMoveException;
import inf101.v18.rogue101.items.*;
import inf101.v18.rogue101.items.Manga;
import inf101.v18.rogue101.objects.*;
import javafx.scene.canvas.GraphicsContext;
import inf101.v18.grid.Location;
import inf101.v18.rogue101.object.Item;
public class GameMap implements IGameMap {
/**
* The grid that makes up our map
*/
private final IMultiGrid<IItem> grid;
/**
* These locations have changed, and need to be redrawn
*/
private final Set<ILocation> dirtyLocs = new HashSet<>();
/**
* An index of all the items in the map and their locations.
*/
// an IdentityHashMap uses object identity as a lookup key, so items are
// considered equal if they are the same object (a == b)
private final Map<IItem, ILocation> items = new IdentityHashMap<>();
import java.util.List;
public GameMap(IArea area) {
grid = new MultiGrid<>(area);
}
/**
* Extra map methods that are for the game class only!
*
* @author anya
*/
public interface GameMap extends MapView {
public GameMap(int width, int height) {
grid = new MultiGrid<>(width, height);
}
/**
* Draw the map
*
* @param painter
* @param printer
*/
void draw(ITurtle painter, Printer printer);
@Override
public void add(ILocation loc, IItem item) {
/**
* Get a modifiable list of items
*
* @param loc
* @return
*/
List<Item> getAllModifiable(Location loc);
// keep track of location of all items
items.put(item, loc);
// also keep track of whether we need to redraw this cell
dirtyLocs.add(loc);
/**
* Remove any destroyed items at the given location (items where {@link Item#isDestroyed()} is true)
*
* @param loc
*/
void clean(Location loc);
// do the actual adding
List<IItem> list = grid.get(loc);
/**
* Remove an item
*
* @param loc
* @param item
*/
void remove(Location loc, Item item);
for (int i = 0; i < list.size(); i++) {
if (item.compareTo(list.get(i)) >= 0) {
list.add(i, item);
return;
}
}
list.add(item);
}
public void addRandomItems(ILocation loc) {
if (!this.hasActors(loc) && !this.hasWall(loc)) {
Random random = new Random();
if (random.nextInt(10) < 2) {
this.add(loc, new Carrot());
}
if (random.nextInt(10) < 1) {
this.add(loc, new Manga());
}
if (random.nextInt(2) < 1) {
this.add(loc, new Chest());
}
if (random.nextInt(2) < 1) {
this.add(loc, new Sword());
}
if (random.nextInt(2) < 1) {
this.add(loc, new Shield());
}
if (random.nextInt(2) < 1) {
this.add(loc, new Staff());
}
if (random.nextInt(2) < 1) {
this.add(loc, new Bow());
}
if (random.nextInt(2) < 1) {
this.add(loc, new Backpack());
}
}
}
@Override
public boolean canGo(ILocation to) {
return !grid.contains(to, (i) -> (i instanceof Wall || i instanceof IActor));
}
@Override
public boolean hasNeighbour(ILocation from, GridDirection dir) {
return from.canGo(dir);
}
@Override
public boolean canGo(ILocation from, GridDirection dir) {
if (!from.canGo(dir))
return false;
ILocation loc = from.go(dir);
return canGo(loc);
}
@Override
public void draw(ITurtle painter, Printer printer) {
Iterable<ILocation> cells;
if (Main.MAP_DRAW_ONLY_DIRTY_CELLS) {
if (dirtyLocs.isEmpty())
return;
else
cells = dirtyLocs;
} else {
cells = grid.locations();
painter.as(GraphicsContext.class).clearRect(0, 0, getWidth() * printer.getCharWidth(),
getHeight() * printer.getCharHeight());
printer.clearRegion(1, 1, getWidth(), getHeight());
}
GraphicsContext ctx = painter.as(GraphicsContext.class);
double h = printer.getCharHeight();
double w = printer.getCharWidth();
if (Main.MAP_AUTO_SCALE_ITEM_DRAW) {
ctx.save();
ctx.scale(w / h, 1.0);
w = h;
}
try {
for (ILocation loc : cells) {
List<IItem> list = grid.get(loc);
String sym = " ";
if (!list.isEmpty()) {
if (Main.MAP_DRAW_ONLY_DIRTY_CELLS) {
ctx.clearRect(loc.getX() * w, loc.getY() * h, w, h);
// ctx.fillRect(loc.getX() * w, loc.getY() * h, w, h);
}
painter.save();
painter.jumpTo((loc.getX() + 0.5) * w, (loc.getY() + 0.5) * h);
boolean dontPrint = list.get(0).draw(painter, w, h);
painter.restore();
if (!dontPrint) {
sym = list.get(0).getPrintSymbol();
}
}
printer.printAt(loc.getX() + 1, loc.getY() + 1, sym);
}
} finally {
if (Main.MAP_AUTO_SCALE_ITEM_DRAW) {
ctx.restore();
}
}
dirtyLocs.clear();
}
/**
* Writes a black void unto the whole map.
* Properly draws only the tiles visible to the player.
*
* @param painter A painter
* @param printer A printer
*/
public void drawVisible(ITurtle painter, Printer printer) {
Iterable<ILocation> cells;
if (Main.MAP_DRAW_ONLY_DIRTY_CELLS) {
if (dirtyLocs.isEmpty())
return;
else
cells = dirtyLocs;
} else {
cells = grid.locations();
painter.as(GraphicsContext.class).clearRect(0, 0, getWidth() * printer.getCharWidth(),
getHeight() * printer.getCharHeight());
printer.clearRegion(1, 1, getWidth(), getHeight());
}
GraphicsContext ctx = painter.as(GraphicsContext.class);
double h = printer.getCharHeight();
double w = printer.getCharWidth();
if (Main.MAP_AUTO_SCALE_ITEM_DRAW) {
ctx.save();
ctx.scale(w / h, 1.0);
w = h;
}
try {
IPlayer player = null;
ILocation playerPos = null;
for (ILocation loc : cells) {
printer.printAt(loc.getX() + 1, loc.getY() + 1, " ");
//We need to get the player and its location from somewhere.
if (this.hasActors(loc) && this.getActors(loc).get(0) instanceof IPlayer) {
player = (IPlayer) this.getActors(loc).get(0);
playerPos = loc;
}
}
if (player == null) {
return;
}
List<ILocation> positions = getVisible(getNeighbourhood(playerPos,player.getVision()), playerPos);
positions.add(playerPos);
for (ILocation loc : positions) {
List<IItem> list = grid.get(loc);
String sym = ".";
if (!list.isEmpty()) {
if (Main.MAP_DRAW_ONLY_DIRTY_CELLS) {
ctx.clearRect(loc.getX() * w, loc.getY() * h, w, h);
// ctx.fillRect(loc.getX() * w, loc.getY() * h, w, h);
}
painter.save();
painter.jumpTo((loc.getX() + 0.5) * w, (loc.getY() + 0.5) * h);
boolean dontPrint = list.get(0).draw(painter, w, h);
painter.restore();
if (!dontPrint) {
sym = list.get(0).getPrintSymbol();
}
}
printer.printAt(loc.getX() + 1, loc.getY() + 1, sym);
}
} finally {
if (Main.MAP_AUTO_SCALE_ITEM_DRAW) {
ctx.restore();
}
}
dirtyLocs.clear();
}
private List<ILocation> getVisible(List<ILocation> neighbours, ILocation loc) {
List<ILocation> invalid = new ArrayList<>();
for (ILocation neighbour : neighbours) {
if (!hasWall(neighbour)) {
for (ILocation tile : loc.gridLineTo(neighbour)) {
if (hasWall(tile)) {
invalid.add(neighbour);
break;
}
}
}
}
neighbours.removeAll(invalid);
return neighbours;
}
@Override
public List<IActor> getActors(ILocation loc) {
List<IActor> items = new ArrayList<>();
for (IItem item : grid.get(loc)) {
if (item instanceof IActor)
items.add((IActor) item);
}
return items;
}
@Override
public List<IItem> getAll(ILocation loc) {
return Collections.unmodifiableList(grid.get(loc));
}
@Override
public List<IItem> getAllModifiable(ILocation loc) {
dirtyLocs.add(loc);
return grid.get(loc);
}
@Override
public void clean(ILocation loc) {
// remove any items that have health < 0:
if (grid.get(loc).removeIf((item) -> {
if (item.isDestroyed()) {
items.remove(item);
return true;
} else {
return false;
}
})) {
dirtyLocs.add(loc);
}
}
@Override
public IArea getArea() {
return grid.getArea();
}
@Override
public int getHeight() {
return grid.getHeight();
}
@Override
public List<IItem> getItems(ILocation loc) {
List<IItem> items = new ArrayList<>(grid.get(loc));
items.removeIf((i) -> i instanceof IActor);
return items;
}
@Override
public ILocation getLocation(IItem item) {
return items.get(item);
}
@Override
public ILocation getLocation(int x, int y) {
return grid.getArea().location(x, y);
}
@Override
public ILocation getNeighbour(ILocation from, GridDirection dir) {
if (!hasNeighbour(from, dir))
return null;
else
return from.go(dir);
}
@Override
public int getWidth() {
return grid.getWidth();
}
@Override
public ILocation go(ILocation from, GridDirection dir) throws IllegalMoveException {
if (!from.canGo(dir))
throw new IllegalMoveException("Cannot move outside map!");
ILocation loc = from.go(dir);
if (!canGo(loc))
throw new IllegalMoveException("Occupied!");
return loc;
}
@Override
public boolean has(ILocation loc, IItem target) {
return grid.contains(loc, target);
}
@Override
public boolean hasActors(ILocation loc) {
return grid.contains(loc, (i) -> i instanceof IActor);
}
@Override
public boolean hasItems(ILocation loc) {
// true if grid cell contains an item which is not an IActor
return grid.contains(loc, (i) -> !(i instanceof IActor));
}
@Override
public boolean hasWall(ILocation loc) {
return grid.contains(loc, (i) -> i instanceof Wall || i instanceof FakeWall);
}
@Override
public void remove(ILocation loc, IItem item) {
grid.remove(loc, item);
items.remove(item);
dirtyLocs.add(loc);
}
@Override
public List<ILocation> getNeighbourhood(ILocation loc, int dist) {
if (dist < 0 || loc == null) {
throw new IllegalArgumentException();
} else if (dist == 0) {
return new ArrayList<>(); // empty!
}
List<ILocation> neighbours = new ArrayList<>();
int startX = loc.getX();
int startY = loc.getY();
for (int i = 1; i <= dist; i++) {
for (int x = startX - i + 1; x < startX + i; x++) { //Top and bottom
if (grid.isValid(x, startY - i)) {
neighbours.add(getLocation(x, startY - i));
}
if (grid.isValid(x, startY + i)) {
neighbours.add(getLocation(x, startY + i));
}
}
for (int y = startY - i; y <= startY + i; y++) { //Sides
if (grid.isValid(startX - i, y)) {
neighbours.add(getLocation(startX - i, y));
}
if (grid.isValid(startX + i, y)) {
neighbours.add(getLocation(startX + i, y));
}
}
}
return neighbours;
}
}

View File

@ -1,48 +0,0 @@
package inf101.v18.rogue101.map;
import java.util.List;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.textmode.Printer;
import inf101.v18.grid.ILocation;
import inf101.v18.rogue101.objects.IItem;
/**
* Extra map methods that are for the game class only!
*
* @author anya
*
*/
public interface IGameMap extends IMapView {
/**
* Draw the map
*
* @param painter
* @param printer
*/
void draw(ITurtle painter, Printer printer);
/**
* Get a modifiable list of items
*
* @param loc
* @return
*/
List<IItem> getAllModifiable(ILocation loc);
/**
* Remove any destroyed items at the given location (items where {@link IItem#isDestroyed()} is true)
*
* @param loc
*/
void clean(ILocation loc);
/**
* Remove an item
* @param loc
* @param item
*/
void remove(ILocation loc, IItem item);
}

View File

@ -1,190 +0,0 @@
package inf101.v18.rogue101.map;
import java.util.List;
import inf101.v18.grid.GridDirection;
import inf101.v18.grid.IArea;
import inf101.v18.grid.ILocation;
import inf101.v18.rogue101.game.IllegalMoveException;
import inf101.v18.rogue101.objects.IActor;
import inf101.v18.rogue101.objects.IItem;
public interface IMapView {
/**
* Add an item to the map.
*
* @param loc
* A location
* @param item
* the item
*/
void add(ILocation loc, IItem item);
/**
* Check if it's legal for an IActor to go into the given location
*
* @param to
* A location
* @return True if the location isn't already occupied
*/
boolean canGo(ILocation to);
/**
* Check if it's legal for an IActor to go in the given direction from the given
* location
*
* @param from
* Current location
* @param dir
* Direction we want to move in
* @return True if the next location exists and isn't occupied
*/
boolean canGo(ILocation from, GridDirection dir);
/**
* Get all IActors at the given location
* <p>
* The returned list either can't be modified, or modifying it won't affect the
* map.
*
* @param loc
* @return A list of actors
*/
List<IActor> getActors(ILocation loc);
/**
* Get all items (both IActors and other IItems) at the given location
* <p>
* The returned list either can't be modified, or modifying it won't affect the
* map.
*
* @param loc
* @return A list of items
*/
List<IItem> getAll(ILocation loc);
/**
* Get all non-IActor items at the given location
* <p>
* The returned list either can't be modified, or modifying it won't affect the
* map.
*
* @param loc
* @return A list of items, non of which are instanceof IActor
*/
List<IItem> getItems(ILocation loc);
/**
* @return A 2D-area defining the legal map locations
*/
IArea getArea();
/**
* @return Height of the map, same as
* {@link #getArea()}.{@link IArea#getHeight()}
*/
int getHeight();
/**
* @return Width of the map, same as {@link #getArea()}.{@link IArea#getWidth()}
*/
int getWidth();
/**
* Find location of an item
*
* @param item
* The item
* @return It's location, or <code>null</code> if it's not on the map
*/
ILocation getLocation(IItem item);
/**
* Translate (x,y)-coordinates to ILocation
*
* @param x
* @param y
* @return an ILocation
* @throws IndexOutOfBoundsException
* if (x,y) is outside {@link #getArea()}
*/
ILocation getLocation(int x, int y);
/**
* Get the neighbouring location in the given direction
*
* @param from
* A location
* @param dir
* the Direction
* @return from's neighbour in direction dir, or null, if this would be outside
* the map
*/
ILocation getNeighbour(ILocation from, GridDirection dir);
/**
* Compute new location of an IActor moving the given direction
*
* @param from
* Original location
* @param dir
* Direction we're moving in
* @return The new location
* @throws IllegalMoveException
* if !{@link #canGo(ILocation, GridDirection)}
*/
ILocation go(ILocation from, GridDirection dir) throws IllegalMoveException;
/**
* Check if an item exists at a location
*
* @param loc
* The location
* @param target
* The item we're interested in
* @return True if target would appear in {@link #getAll(loc)}
*/
boolean has(ILocation loc, IItem target);
/**
* Check for actors.
*
* @param loc
* @return True if {@link #getActors(loc)} would be non-empty
*/
boolean hasActors(ILocation loc);
/**
* Check for non-actors
*
* @param loc
* @return True if {@link #getItem(loc)} would be non-empty
*/
boolean hasItems(ILocation loc);
/**
* Check for walls
*
* @param loc
* @return True if there is a wall at the given location ({@link #getAll(loc)}
* would contain an instance of {@link Wall})
*/
boolean hasWall(ILocation loc);
/**
* Check if a neighbour exists on the map
*
* @param from A location
* @param dir A direction
* @return True if {@link #getNeighbour(from, dir)} would return non-null
*/
boolean hasNeighbour(ILocation from, GridDirection dir);
/**
* Get all locations within i steps from the given centre
* @param centre
* @param dist
* @return A list of locations, all at most i grid cells away from centre
*/
List<ILocation> getNeighbourhood(ILocation centre, int dist);
}

View File

@ -1,23 +1,23 @@
package inf101.v18.rogue101.map;
import inf101.v18.grid.IGrid;
import inf101.v18.grid.MyGrid;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import inf101.v18.grid.IGrid;
import inf101.v18.grid.MyGrid;
/**
* A class to read a Boulder Dash map from a file. After the file is read, the
* map is stored as an {@link #IGrid} whose entries are characters. This can
* then be used to be passed to the constructor in {@link #BDMap}.
*
* <p>
* The first line of the file should could contain two numbers. First the width
* and then the height of the map. After that follows a matrix of characters
* describing which object goes where in the map. '*' for wall, ' ' for empty,
* 'P' for the player, 'b' for a bug, 'r' for a rock, and '#' for sand. For
* example
*
*
* <pre>
* {@code
* 5 6
@ -26,75 +26,77 @@ import inf101.v18.grid.MyGrid;
* *####
* * *
* * d
* b
* b
* }
* </pre>
*
*
* @author larsjaffke (original boulderdash version, 2017)
* @author anya (Rogue101 update, 2018)
*/
public class MapReader {
/**
* This method fills the previously initialized {@link #symbolMap} with the
* characters read from the file.
*/
private static void fillMap(IGrid<String> symbolMap, Scanner in) {
// we need to store x and y in an object (array) rather than as variables,
// otherwise the foreach and lambda below won't work.
int[] xy = new int[2]; // xy[0] is x, xy[1] is y
xy[1] = 0;
while (in.hasNextLine()) {
xy[0] = 0;
in.nextLine().codePoints().forEach((codePoint) -> {
if (xy[0] < symbolMap.getWidth())
symbolMap.set(xy[0]++, xy[1], String.valueOf(Character.toChars(codePoint)));
});
xy[1]++;
}
}
/**
* This method fills the previously initialized {@link #symbolMap} with the
* characters read from the file.
*/
private static void fillMap(IGrid<String> symbolMap, Scanner in) {
// we need to store x and y in an object (array) rather than as variables,
// otherwise the foreach and lambda below won't work.
int[] xy = new int[2]; // xy[0] is x, xy[1] is y
xy[1] = 0;
while (in.hasNextLine()) {
xy[0] = 0;
in.nextLine().codePoints().forEach((codePoint) -> {
if (xy[0] < symbolMap.getWidth()) {
symbolMap.set(xy[0]++, xy[1], String.valueOf(Character.toChars(codePoint)));
}
});
xy[1]++;
}
}
/**
* Load map from file.
* <p>
* Files are search for relative to the folder containing the MapReader class.
*
* @return the dungeon map as a grid of characters read from the file, or null
* if it failed
*/
public static IGrid<String> readFile(String path) {
IGrid<String> symbolMap = null;
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream stream = classloader.getResourceAsStream(path);
if (stream == null)
return null;
try (Scanner in = new Scanner(stream, "UTF-8")) {
int width = in.nextInt();
int height = in.nextInt();
// System.out.println(width + " " + height);
symbolMap = new MyGrid<String>(width, height, " ");
in.nextLine();
fillMap(symbolMap, in);
}
try {
stream.close();
} catch (IOException e) {
}
return symbolMap;
}
/**
* Load map from file.
* <p>
* Files are search for relative to the folder containing the MapReader class.
*
* @return the dungeon map as a grid of characters read from the file, or null
* if it failed
*/
public static IGrid<String> readFile(String path) {
IGrid<String> symbolMap = null;
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream stream = classloader.getResourceAsStream(path);
if (stream == null) {
return null;
}
try (Scanner in = new Scanner(stream, "UTF-8")) {
int width = in.nextInt();
int height = in.nextInt();
// System.out.println(width + " " + height);
symbolMap = new MyGrid<String>(width, height, " ");
in.nextLine();
fillMap(symbolMap, in);
}
try {
stream.close();
} catch (IOException e) {
}
return symbolMap;
}
/**
* @return the dungeon map as a grid of characters read from the input string,
* or null if it failed
*/
public static IGrid<String> readString(String input) {
IGrid<String> symbolMap = null;
try (Scanner in = new Scanner(input)) {
int width = in.nextInt();
int height = in.nextInt();
symbolMap = new MyGrid<String>(width, height, " ");
in.nextLine();
fillMap(symbolMap, in);
}
return symbolMap;
}
/**
* @return the dungeon map as a grid of characters read from the input string,
* or null if it failed
*/
public static IGrid<String> readString(String input) {
IGrid<String> symbolMap = null;
try (Scanner in = new Scanner(input)) {
int width = in.nextInt();
int height = in.nextInt();
symbolMap = new MyGrid<String>(width, height, " ");
in.nextLine();
fillMap(symbolMap, in);
}
return symbolMap;
}
}

View File

@ -0,0 +1,177 @@
package inf101.v18.rogue101.map;
import inf101.v18.grid.GridDirection;
import inf101.v18.grid.IArea;
import inf101.v18.grid.Location;
import inf101.v18.rogue101.game.IllegalMoveException;
import inf101.v18.rogue101.object.Actor;
import inf101.v18.rogue101.object.Item;
import java.util.List;
public interface MapView {
/**
* Add an item to the map.
*
* @param loc A location
* @param item the item
*/
void add(Location loc, Item item);
/**
* Check if it's legal for an IActor to go into the given location
*
* @param to A location
* @return True if the location isn't already occupied
*/
boolean canGo(Location to);
/**
* Check if it's legal for an IActor to go in the given direction from the given
* location
*
* @param from Current location
* @param dir Direction we want to move in
* @return True if the next location exists and isn't occupied
*/
boolean canGo(Location from, GridDirection dir);
/**
* Get all IActors at the given location
* <p>
* The returned list either can't be modified, or modifying it won't affect the
* map.
*
* @param loc
* @return A list of actors
*/
List<Actor> getActors(Location loc);
/**
* Get all items (both IActors and other IItems) at the given location
* <p>
* The returned list either can't be modified, or modifying it won't affect the
* map.
*
* @param loc
* @return A list of items
*/
List<Item> getAll(Location loc);
/**
* Get all non-IActor items at the given location
* <p>
* The returned list either can't be modified, or modifying it won't affect the
* map.
*
* @param loc
* @return A list of items, non of which are instanceof IActor
*/
List<Item> getItems(Location loc);
/**
* @return A 2D-area defining the legal map locations
*/
IArea getArea();
/**
* @return Height of the map, same as
* {@link #getArea()}.{@link IArea#getHeight()}
*/
int getHeight();
/**
* @return Width of the map, same as {@link #getArea()}.{@link IArea#getWidth()}
*/
int getWidth();
/**
* Find location of an item
*
* @param item The item
* @return It's location, or <code>null</code> if it's not on the map
*/
Location getLocation(Item item);
/**
* Translate (x,y)-coordinates to ILocation
*
* @param x
* @param y
* @return an ILocation
* @throws IndexOutOfBoundsException if (x,y) is outside {@link #getArea()}
*/
Location getLocation(int x, int y);
/**
* Get the neighbouring location in the given direction
*
* @param from A location
* @param dir the Direction
* @return from's neighbour in direction dir, or null, if this would be outside
* the map
*/
Location getNeighbour(Location from, GridDirection dir);
/**
* Compute new location of an IActor moving the given direction
*
* @param from Original location
* @param dir Direction we're moving in
* @return The new location
* @throws IllegalMoveException if !{@link #canGo(Location, GridDirection)}
*/
Location go(Location from, GridDirection dir) throws IllegalMoveException;
/**
* Check if an item exists at a location
*
* @param loc The location
* @param target The item we're interested in
* @return True if target would appear in {@link #getAll(loc)}
*/
boolean has(Location loc, Item target);
/**
* Check for actors.
*
* @param loc
* @return True if {@link #getActors(loc)} would be non-empty
*/
boolean hasActors(Location loc);
/**
* Check for non-actors
*
* @param loc
* @return True if {@link #getItem(loc)} would be non-empty
*/
boolean hasItems(Location loc);
/**
* Check for walls
*
* @param loc
* @return True if there is a wall at the given location ({@link #getAll(loc)}
* would contain an instance of {@link Wall})
*/
boolean hasWall(Location loc);
/**
* Check if a neighbour exists on the map
*
* @param from A location
* @param dir A direction
* @return True if {@link #getNeighbour(from, dir)} would return non-null
*/
boolean hasNeighbour(Location from, GridDirection dir);
/**
* Get all locations within i steps from the given centre
*
* @param centre
* @param dist
* @return A list of locations, all at most i grid cells away from centre
*/
List<Location> getNeighbourhood(Location centre, int dist);
}

View File

@ -0,0 +1,43 @@
package inf101.v18.rogue101.object;
import inf101.v18.rogue101.game.Game;
/**
* An actor is an Item that can also do something, either controlled by the
* computer (NonPlayerCharacter) or the user (PlayerCharacter).
*
* @author anya
*/
public interface Actor extends Item {
/**
* @return This actor's attack score (used against an item's
* {@link #getDefense()} score to see if an attack is successful)
*/
int getAttack();
/**
* @return The damage this actor deals on a successful attack (used together
* with
* {@link #handleDamage(Game, Item, int)} on
* the target)
*/
int getDamage();
/**
* How many tiles the IActor is able to see in each direction.
*
* @return Number of tiles
*/
default int getVision() {
return 1;
}
/**
* Gets an item of the specified type, if the actor has the item.
*
* @return An IItem or null
*/
Item getItem(Class<?> type);
}

View File

@ -0,0 +1,49 @@
package inf101.v18.rogue101.object;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.textmode.BlocksAndBoxes;
import inf101.v18.rogue101.game.Game;
public class Dust implements Item {
@Override
public boolean draw(ITurtle painter, double w, double h) {
return false;
}
@Override
public int getCurrentHealth() {
return 0;
}
@Override
public int getDefense() {
return 0;
}
@Override
public int getMaxHealth() {
return 0;
}
@Override
public String getName() {
return "thick layer of dust";
}
@Override
public int getSize() {
return 1;
}
@Override
public String getSymbol() {
return BlocksAndBoxes.BLOCK_HALF;
}
@Override
public int handleDamage(Game game, Item source, int amount) {
return 0;
}
}

View File

@ -0,0 +1,31 @@
package inf101.v18.rogue101.object;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.textmode.BlocksAndBoxes;
/**
* An objects that works like a wall in every sense, except it can be passed through
*/
public class FakeWall extends Wall {
@Override
public boolean draw(ITurtle painter, double w, double h) {
return false;
}
@Override
public int getMaxHealth() {
return 1;
}
@Override
public String getName() {
return "fake wall";
}
@Override
public String getSymbol() {
return BlocksAndBoxes.BLOCK_HALF;
}
}

View File

@ -0,0 +1,175 @@
package inf101.v18.rogue101.object;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.rogue101.events.IEvent;
import inf101.v18.rogue101.game.Game;
/**
* An {@link Item} is something that can be placed on the map or into a
* container of items.
* <p>
* An {@link Actor} is a special case of {@link Item} used for things that are
* alive, such as the player or AI-controlled monsters/NPCs.
* <p>
* By default, all items have a hit point / health system (they can be damaged),
* and can be picked up. So you could potentially destroy an item or pick up a
* monster.
*
* @author anya
*/
public interface Item extends Comparable<Item> {
@Override
default int compareTo(Item other) {
return Integer.compare(getSize(), other.getSize());
}
/**
* Draw this item on the screen.
* <p>
* The turtle-painter will be positioned in the centre of the cell. You should
* avoid drawing outside the cell (size is indicated by the <code>w</code> and
* <code>h</code> parameters, so you can move ±w/2 and ±h/2 from the initial
* position). If you want to start in the lower left corner of the cell, you can
* start by doing <code>painter.jump(-w/2,h/2)</code> ((0,0) is in the top-left
* corner of the screen, so negative X points left and positive Y points down).
* <p>
* If this method returns <code>true</code>, the game will <em>not</em> print
* {@link #getSymbol()} in the cell.
* <p>
* All calls to <code>painter.save()</code> must be matched by a call to
* <code>painter.restore()</code>.
*
* @param painter A turtle-painter for drawing
* @param w The width of the cell
* @param h The height of the cell
* @return False if the letter from {@link #getSymbol()} should be drawn instead
*/
default boolean draw(ITurtle painter, double w, double h) {
return false;
}
/**
* @return "a" or "an", depending on the name
*/
default String getArticle() {
return "a";
}
/**
* Get current remaining health points.
* <p>
* An object's <em>health points</em> determines how much damage it can take
* before it is destroyed / broken / killed.
*
* @return Current health points for this item
*/
int getCurrentHealth();
/**
* The defence score determines how hard an object/actor is to hit or grab.
*
* @return Defence score of this object
*/
int getDefense();
/**
* Get item health as a 0.0..1.0 proportion.
*
* <li><code>getHealth() >= 1.0</code> means perfect condition
* <li><code>getHealth() <= 0.0</code> means broken or dead
* <li><code>0.0 < getHealth() < 1.0</code> means partially damaged
*
* @return Health, in the range 0.0 to 1.0
*/
default double getHealthStatus() {
return getMaxHealth() > 0 ? getCurrentHealth() / getMaxHealth() : 0;
}
/**
* Get maximum health points.
* <p>
* An object's <em>health points</em> determines how much damage it can take
* before it is destroyed / broken / killed.
*
* @return Max health points for this item
*/
int getMaxHealth();
/**
* Get a (user-friendly) name for the item
* <p>
* Used for things like <code>"You see " + getArticle() + " " + getName()</code>
*
* @return Item's name
*/
String getName();
/**
* Get a map symbol used for printing this item on the screen.
* <p>
* This is usually the same as {@link #getSymbol()}, but could also include
* special control characters for changing the text colour, for example.
*
* @return A string to be displayed for this item on the screen (should be only
* one column wide when printed)
* @see <a href="https://en.wikipedia.org/wiki/ANSI_escape_code#Colors">ANSI
* escape code (on Wikipedia)</a>
*/
default String getPrintSymbol() {
return getSymbol();
}
/**
* Get the size of the object.
* <p>
* The size determines how much space an item will use if put into a container.
*
* @return Size of the item
*/
int getSize();
/**
* Get the map symbol of this item.
* <p>
* The symbol can be used on a text-only map, or when loading a map from text.
* <p>
* The symbol should be a single Unicode codepoint (i.e.,
* <code>getSymbol().codePointCount(0, getSymbol().length()) == 1</code>). In
* most cases this means that the symbol should be a single character (i.e.,
* getSymbol().length() == 1); but there are a few Unicode characters (such as
* many emojis and special symbols) that require two Java <code>char</code>s.
*
* @return A single-codepoint string with the item's symbol
*/
String getSymbol();
/**
* Inform the item that it has been damaged
*
* @param game The game
* @param source The item (usually an IActor) that caused the damage
* @param amount How much damage the item should take
* @return Amount of damage actually taken (could be less than
* <code>amount</code> due to armour/protection effects)
*/
int handleDamage(Game game, Item source, int amount);
/**
* Inform the item that something has happened.
*
* @param event An object describing the event.
* @return
*/
default <T> T handleEvent(IEvent<T> event) {
return event.getData();
}
/**
* @return True if this item has been destroyed, and should be removed from the map
*/
default boolean isDestroyed() {
return getCurrentHealth() < 0;
}
}

View File

@ -0,0 +1,22 @@
package inf101.v18.rogue101.object;
import inf101.v18.rogue101.game.Game;
/**
* An actor controlled by the computer
*
* @author anya
*/
public interface NonPlayerCharacter extends Actor {
/**
* Do one turn for this non-player
* <p>
* This INonPlayer will be the game's current actor ({@link Game#getActor()})
* for the duration of this method call.
*
* @param game Game, for interacting with the world
*/
void doTurn(Game game);
}

View File

@ -1,31 +1,40 @@
package inf101.v18.rogue101.objects;
package inf101.v18.rogue101.object;
import inf101.v18.gfx.textmode.Printer;
import inf101.v18.grid.GridDirection;
import inf101.v18.grid.ILocation;
import inf101.v18.grid.Location;
import inf101.v18.rogue101.Main;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.items.*;
import inf101.v18.rogue101.shared.NPC;
import inf101.v18.rogue101.states.Attack;
import inf101.v18.rogue101.game.RogueGame;
import inf101.v18.rogue101.items.buff.BuffItem;
import inf101.v18.rogue101.items.consumable.Consumable;
import inf101.v18.rogue101.items.container.Backpack;
import inf101.v18.rogue101.items.container.Container;
import inf101.v18.rogue101.items.container.Static;
import inf101.v18.rogue101.items.weapon.MagicWeapon;
import inf101.v18.rogue101.items.weapon.RangedWeapon;
import inf101.v18.rogue101.items.weapon.Weapon;
import inf101.v18.rogue101.state.AttackType;
import inf101.v18.util.NPCHelper;
import javafx.scene.input.KeyCode;
import java.util.List;
public class Player implements IPlayer {
private int hp = getMaxHealth();
public class Player implements PlayerCharacter {
private int healthPoints = getMaxHealth();
private int attack = 40;
private int defence = 20;
private final Backpack equipped = new Backpack();
private boolean dropping = false; //True if the player wants to drop something using the digit keys
private boolean picking = false; //True if the player wants to pick up something using the digit keys
private boolean writing = false; //True if the user is writing a name
private boolean exploringChest = false;
private boolean exploringChest = false;
private String text = "";
private String name = "Player";
@Override
public boolean keyPressed(IGame game, KeyCode key) {
public boolean keyPressed(Game game, KeyCode key) {
boolean turnConsumed = false;
if (writing) {
write(game, key);
@ -72,9 +81,9 @@ public class Player implements IPlayer {
game.displayMessage("Please enter your name: ");
writing = true;
} else if (key == KeyCode.R) {
turnConsumed = nonMeleeAttack(game, getVision(), Attack.RANGED, "ranged");
turnConsumed = nonMeleeAttack(game, getVision(), AttackType.RANGED, "ranged");
} else if (key == KeyCode.F) {
turnConsumed = nonMeleeAttack(game, getVision() / 2 + getVision() % 2 == 0 ? 0 : 1, Attack.MAGIC, "magic");
turnConsumed = nonMeleeAttack(game, getVision() / 2 + getVision() % 2 == 0 ? 0 : 1, AttackType.MAGIC, "magic");
}
showStatus(game);
return turnConsumed;
@ -83,21 +92,21 @@ public class Player implements IPlayer {
/**
* Attacks if the user is able to use the desired attack.
*
* @param game An IGame object
* @param range The range of the weapon
* @param type The type of the attack
* @param weapon The required weapon type
* @return True if an attack was possible. False otherwise
* @param game An IGame object
* @param range The range of the weapon
* @param type The type of the attack
* @param weapon The required weapon type
* @return True if an attack was possible. False otherwise
*/
private boolean nonMeleeAttack(IGame game, int range, Attack type, String weapon) {
private boolean nonMeleeAttack(Game game, int range, AttackType type, String weapon) {
boolean turnConsumed = false;
IItem item = null;
Item item = null;
switch (type) {
case RANGED:
item = getItem(IRangedWeapon.class);
item = getItem(RangedWeapon.class);
break;
case MAGIC:
item = getItem(IMagicWeapon.class);
item = getItem(MagicWeapon.class);
}
if (item == null) {
game.displayMessage("You do not have a " + weapon + " weapon.");
@ -113,10 +122,10 @@ public class Player implements IPlayer {
/**
* Lets the user write his/her name.
*
* @param game An IGame object
* @param key The key pressed
* @param game An IGame object
* @param key The key pressed
*/
private void write(IGame game, KeyCode key) {
private void write(Game game, KeyCode key) {
if (key == KeyCode.BACK_SPACE) {
if (text.length() > 0) {
text = text.substring(0, text.length() - 1);
@ -140,22 +149,22 @@ public class Player implements IPlayer {
/**
* Initializes the interaction with an item, and does what is needed.
*
* @param game An IGame object
* @return True if a turn was consumed. False otherwise
* @param game An IGame object
* @return True if a turn was consumed. False otherwise
*/
private boolean interactInit(IGame game) {
List<IItem> items = game.getLocalItems();
private boolean interactInit(Game game) {
List<Item> items = game.getLocalItems();
if (items.size() < 1) {
game.displayMessage("There is nothing to pick up");
} else {
IItem item = items.get(0);
if (item instanceof IStatic && item instanceof IContainer) { //A Static item is always the biggest (and hopefully the only) item on a tile.
Item item = items.get(0);
if (item instanceof Static && item instanceof Container) { //A Static item is always the biggest (and hopefully the only) item on a tile.
openChest(game, items);
} else if (item instanceof IStatic && item instanceof StairsUp) {
((Game)game).goUp();
} else if (item instanceof StairsUp) {
((RogueGame) game).goUp();
return true;
} else if (item instanceof IStatic && item instanceof StairsDown) {
((Game)game).goDown();
} else if (item instanceof StairsDown) {
((RogueGame) game).goDown();
return true;
} else {
if (items.size() == 1) {
@ -173,18 +182,18 @@ public class Player implements IPlayer {
/**
* Uses the first consumable from the player's inventory
*
* @param game An IGame object
* @return True if a potion was used. False otherwise
* @param game An IGame object
* @return True if a potion was used. False otherwise
*/
private boolean useConsumable(IGame game) {
IConsumable consumable = (IConsumable) equipped.getFirst(IConsumable.class);
private boolean useConsumable(Game game) {
Consumable consumable = (Consumable) equipped.getFirst(Consumable.class);
if (consumable != null) {
hp += consumable.hpIncrease();
if (hp > getMaxHealth()) {
hp = getMaxHealth();
healthPoints += consumable.hpIncrease();
if (healthPoints > getMaxHealth()) {
healthPoints = getMaxHealth();
}
attack += consumable.attackIncrease();
defence += consumable.defenceIncrease();
defence += consumable.defenseIncrease();
equipped.remove(consumable);
game.displayMessage("Used " + consumable.getName());
return true;
@ -200,8 +209,8 @@ public class Player implements IPlayer {
* @param game An IGame object
* @param items A list of items on the current tile
*/
private void openChest(IGame game, List<IItem> items) {
IContainer container = (IContainer) items.get(0);
private void openChest(Game game, List<Item> items) {
Container container = (Container) items.get(0);
items = container.getContent();
game.displayMessage(container.getInteractMessage() + niceList(items, 10));
exploringChest = true;
@ -210,11 +219,11 @@ public class Player implements IPlayer {
/**
* Creates a string containing a set number of item names from a list.
*
* @param list The list of items
* @param max The maximum number of items to print
* @return A string
* @param list The list of items
* @param max The maximum number of items to print
* @return A string
*/
private String niceList(List<IItem> list, int max) {
private String niceList(List<Item> list, int max) {
StringBuilder msg = new StringBuilder();
for (int i = 0; i < Math.min(list.size(), max); i++) {
msg.append(" [").append(i + 1).append("] ").append(firstCharToUpper(list.get(i).getName()));
@ -225,10 +234,10 @@ public class Player implements IPlayer {
/**
* Initialized the dropping of an item, and does what is needed.
*
* @param game An IGame object
* @return True if a turn was consumed. False otherwise
* @param game An IGame object
* @return True if a turn was consumed. False otherwise
*/
private boolean dropInit(IGame game) {
private boolean dropInit(Game game) {
if (equipped.size() == 1) {
drop(game, 0);
return true;
@ -244,14 +253,14 @@ public class Player implements IPlayer {
/**
* Picks up an item at index i.
*
* @param game An IGame object
* @param i The wanted index
* @param game An IGame object
* @param i The wanted index
*/
private void pickUp(IGame game, int i) {
private void pickUp(Game game, int i) {
if (equipped.hasSpace()) {
List<IItem> items = game.getLocalItems();
List<Item> items = game.getLocalItems();
if (items.size() >= i) {
IItem pickedUp = game.pickUp(items.get(i));
Item pickedUp = game.pickUp(items.get(i));
if (pickedUp != null) {
equipped.add(pickedUp);
game.displayMessage("Picked up " + pickedUp.getName());
@ -269,11 +278,11 @@ public class Player implements IPlayer {
/**
* Takes an item from a chest, and gives it to the player.
*/
private void loot(IGame game, int i) {
private void loot(Game game, int i) {
if (equipped.hasSpace()) {
IContainer container = getStaticContainer(game);
Container container = getStaticContainer(game);
if (container != null && i < container.getContent().size()) {
IItem loot = container.getContent().get(i);
Item loot = container.getContent().get(i);
equipped.add(loot);
container.remove(i);
game.displayMessage("Looted " + loot.getName());
@ -286,17 +295,17 @@ public class Player implements IPlayer {
/**
* Gets any static containers on the current tile.
*
* @param game An IGame object
* @return A static container
* @param game An IGame object
* @return A static container
*/
private IContainer getStaticContainer(IGame game) {
List<IItem> items = game.getLocalItems();
private Container getStaticContainer(Game game) {
List<Item> items = game.getLocalItems();
if (items.size() < 1) {
return null;
}
IItem item = items.get(0);
if (item instanceof IStatic && item instanceof IContainer) {
return (IContainer) item;
Item item = items.get(0);
if (item instanceof Static && item instanceof Container) {
return (Container) item;
} else {
return null;
}
@ -305,12 +314,12 @@ public class Player implements IPlayer {
/**
* Drops an item at index i.
*
* @param game An IGame object
* @param i The wanted index
* @param game An IGame object
* @param i The wanted index
*/
private void drop(IGame game, int i) {
private void drop(Game game, int i) {
if (!equipped.isEmpty() && equipped.size() > i) {
IContainer container = getStaticContainer(game);
Container container = getStaticContainer(game);
if (container != null) {
if (container.addItem(equipped.get(i))) {
game.displayMessage(equipped.get(i).getName() + " stored in " + container.getName());
@ -335,18 +344,18 @@ public class Player implements IPlayer {
/**
* Updates the status bar with the Player's current stats.
*
* @param game An IGame object
* @param game An IGame object
*/
private void showStatus(IGame game) {
private void showStatus(Game game) {
game.formatStatus("HP: %s ATK: %d RATK: %d MATK: %d DEF: %s DMG: %s RDMG: %s MDMG: %s",
NPC.hpBar(this),
getAttack(Attack.MELEE),
getAttack(Attack.RANGED),
getAttack(Attack.MAGIC),
getDefence(),
getDamage(Attack.MELEE),
getDamage(Attack.RANGED),
getDamage(Attack.MAGIC)
NPCHelper.hpBar(this),
getAttack(AttackType.MELEE),
getAttack(AttackType.RANGED),
getAttack(AttackType.MAGIC),
getDefense(),
getDamage(AttackType.MELEE),
getDamage(AttackType.RANGED),
getDamage(AttackType.MAGIC)
);
printInventory(game);
}
@ -356,13 +365,13 @@ public class Player implements IPlayer {
*
* @param game An IGame object
*/
private void printInventory(IGame game) {
private void printInventory(Game game) {
Printer printer = game.getPrinter();
List<IItem> items = equipped.getContent();
printer.clearRegion(Main.COLUMN_RIGHTSIDE_START, 13, 45, 5);
printer.printAt(Main.COLUMN_RIGHTSIDE_START, 12, "Inventory:");
List<Item> items = equipped.getContent();
printer.clearRegion(Main.COLUMN_RIGHT_SIDE_START, 13, 45, 5);
printer.printAt(Main.COLUMN_RIGHT_SIDE_START, 12, "Inventory:");
for (int i = 0; i < items.size(); i++) {
printer.printAt(Main.COLUMN_RIGHTSIDE_START, 13 + i, items.get(i).getName());
printer.printAt(Main.COLUMN_RIGHT_SIDE_START, 13 + i, items.get(i).getName());
}
}
@ -370,11 +379,11 @@ public class Player implements IPlayer {
* Changes the first character in a string to uppercase.
*
* @param input The input string
* @return The input string with the first character uppercased
* @return The input string with the first character uppercased
*/
private String firstCharToUpper(String input) {
if (input.length() < 1) {
return input;
return input;
} else {
return Character.toUpperCase(input.charAt(0)) + input.substring(1);
}
@ -383,24 +392,24 @@ public class Player implements IPlayer {
/**
* Lets the user move or attack if possible.
*
* @param game An IGame object
* @param dir The direction the player wants to go
* @param game An IGame object
* @param dir The direction the player wants to go
*/
private void tryToMove(IGame game, GridDirection dir) {
ILocation loc = game.getLocation();
private void tryToMove(Game game, GridDirection dir) {
Location loc = game.getLocation();
if (game.canGo(dir)) {
game.move(dir);
} else if (loc.canGo(dir) && game.getMap().hasActors(loc.go(dir))) {
game.attack(dir, game.getMap().getActors(loc.go(dir)).get(0));
} else {
game.displayMessage("Umm, it is not possible to move in that direction.");
game.displayMessage("Umm, it is not possible to move in that direction.");
}
}
@Override
public int getAttack() {
IBuffItem buff = (IBuffItem)getItem(IBuffItem.class);
BuffItem buff = (BuffItem) getItem(BuffItem.class);
if (buff != null) {
return attack + buff.getBuffDamage();
} else {
@ -411,11 +420,11 @@ public class Player implements IPlayer {
/**
* Gets the attack with added weapon attack
*
* @param type The attack type corresponding to the weapon type.
* @return Attack as int
* @param type The attack type corresponding to the weapon type.
* @return Attack as int
*/
private int getAttack(Attack type) {
IWeapon weapon = NPC.getWeapon(type, this);
private int getAttack(AttackType type) {
Weapon weapon = NPCHelper.getWeapon(type, this);
if (weapon != null) {
return getAttack() + weapon.getWeaponAttack();
} else {
@ -431,11 +440,11 @@ public class Player implements IPlayer {
/**
* Gets the damage with added weapon damage
*
* @param type The attack type corresponding to the weapon type.
* @return Damage as int
* @param type The attack type corresponding to the weapon type.
* @return Damage as int
*/
private int getDamage(Attack type) {
IWeapon weapon = NPC.getWeapon(type, this);
private int getDamage(AttackType type) {
Weapon weapon = NPCHelper.getWeapon(type, this);
if (weapon != null) {
return getDamage() + weapon.getWeaponDamage();
} else {
@ -444,8 +453,8 @@ public class Player implements IPlayer {
}
@Override
public IItem getItem(Class<?> type) {
for (IItem item : equipped.getContent()) {
public Item getItem(Class<?> type) {
for (Item item : equipped.getContent()) {
if (type.isInstance(item)) {
return item;
}
@ -455,12 +464,12 @@ public class Player implements IPlayer {
@Override
public int getCurrentHealth() {
return hp;
return healthPoints;
}
@Override
public int getDefence() {
IBuffItem buff = (IBuffItem)getItem(IBuffItem.class);
public int getDefense() {
BuffItem buff = (BuffItem) getItem(BuffItem.class);
if (buff != null) {
return defence + buff.getBuffDamage();
} else {
@ -485,7 +494,7 @@ public class Player implements IPlayer {
@Override
public String getPrintSymbol() {
return "\u001b[96m" + "@" + "\u001b[0m";
return "\u001b[96m" + "@" + "\u001b[0m";
}
@Override
@ -494,10 +503,10 @@ public class Player implements IPlayer {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
public int handleDamage(Game game, Item source, int amount) {
healthPoints -= amount;
showStatus(game);
if (hp < 1) {
if (healthPoints < 1) {
game.displayStatus("Game Over");
}
return amount;
@ -505,7 +514,7 @@ public class Player implements IPlayer {
@Override
public int getVision() {
IBuffItem item = (IBuffItem) getItem(IBuffItem.class);
BuffItem item = (BuffItem) getItem(BuffItem.class);
if (item != null) {
return 3 + item.getBuffVisibility();
} else {
@ -516,19 +525,19 @@ public class Player implements IPlayer {
/**
* Performs a ranged attack on the nearest visible enemy (if any);
*
* @param game An IGame object
* @param range The range of the attack
* @param type The attack type
* @return True if the player attacked. False otherwise
* @param game An IGame object
* @param range The range of the attack
* @param type The attack type
* @return True if the player attacked. False otherwise
*/
private boolean rangedAttack(IGame game, int range, Attack type) {
List<ILocation> neighbours = game.getVisible();
for (ILocation neighbour : neighbours) {
private boolean rangedAttack(Game game, int range, AttackType type) {
List<Location> neighbours = game.getVisible();
for (Location neighbour : neighbours) {
if (game.getMap().hasActors(neighbour)) {
ILocation current = game.getLocation();
Location current = game.getLocation();
List<GridDirection> dirs = game.locationDirection(current, neighbour);
IActor actor = game.getMap().getActors(neighbour).get(0); //We assume there is only one actor.
if (actor instanceof INonPlayer && current.gridDistanceTo(neighbour) <= range) {
Actor actor = game.getMap().getActors(neighbour).get(0); //We assume there is only one actor.
if (actor instanceof NonPlayerCharacter && current.gridDistanceTo(neighbour) <= range) {
GridDirection dir = dirs.get(0); //Only ever has one item
game.rangedAttack(dir, actor, type);
return true;

View File

@ -0,0 +1,25 @@
package inf101.v18.rogue101.object;
import inf101.v18.rogue101.game.Game;
import javafx.scene.input.KeyCode;
public interface PlayerCharacter extends Actor {
/**
* Send key presses from the human player to the player object.
* <p>
* The player object should interpret the key presses, and then perform its
* moves or whatever, according to the game's rules and the player's
* instructions.
* <p>
* This IPlayer will be the game's current actor ({@link Game#getActor()}) and
* be at {@link Game#getLocation()}, when this method is called.
* <p>
* This method may be called many times in a single turn; the turn ends
* {@link #keyPressed(Game, KeyCode)} returns and the player has used its
* movement points (e.g., by calling {@link Game#move(inf101.v18.grid.GridDirection)}).
*
* @param game Game, for interacting with the world
* @return True if the player has done anything consuming a turn. False otherwise
*/
boolean keyPressed(Game game, KeyCode key);
}

View File

@ -1,16 +1,20 @@
package inf101.v18.rogue101.objects;
package inf101.v18.rogue101.object;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.items.IStatic;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.items.container.Static;
/**
* Stairs going downwards to the previous floor
*/
public class StairsDown implements Item, Static {
public class StairsDown implements IItem, IStatic {
@Override
public int getCurrentHealth() {
return 0;
}
@Override
public int getDefence() {
public int getDefense() {
return 0;
}
@ -35,7 +39,8 @@ public class StairsDown implements IItem, IStatic {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
return 0;
}
}

View File

@ -1,16 +1,20 @@
package inf101.v18.rogue101.objects;
package inf101.v18.rogue101.object;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.items.IStatic;
import inf101.v18.rogue101.game.Game;
import inf101.v18.rogue101.items.container.Static;
/**
* Stairs going upwards to the next floor
*/
public class StairsUp implements Item, Static {
public class StairsUp implements IItem, IStatic {
@Override
public int getCurrentHealth() {
return 0;
}
@Override
public int getDefence() {
public int getDefense() {
return 0;
}
@ -35,7 +39,8 @@ public class StairsUp implements IItem, IStatic {
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
return 0;
}
}

View File

@ -1,10 +1,14 @@
package inf101.v18.rogue101.objects;
package inf101.v18.rogue101.object;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.textmode.BlocksAndBoxes;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.game.Game;
/**
* A solid wall blocking passage
*/
public class Wall implements Item {
public class FakeWall implements IItem {
private int hp = getMaxHealth();
@Override
@ -18,18 +22,18 @@ public class FakeWall implements IItem {
}
@Override
public int getDefence() {
public int getDefense() {
return 10;
}
@Override
public int getMaxHealth() {
return 1;
return 1000;
}
@Override
public String getName() {
return "fake wall";
return "wall";
}
@Override
@ -39,12 +43,13 @@ public class FakeWall implements IItem {
@Override
public String getSymbol() {
return "\u001b[47m" + BlocksAndBoxes.BLOCK_FULL + "\u001b[0m";
return BlocksAndBoxes.BLOCK_FULL;
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
public int handleDamage(Game game, Item source, int amount) {
hp -= amount;
return amount;
}
}

View File

@ -1,49 +0,0 @@
package inf101.v18.rogue101.objects;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.textmode.BlocksAndBoxes;
import inf101.v18.rogue101.game.IGame;
public class Dust implements IItem {
@Override
public boolean draw(ITurtle painter, double w, double h) {
return false;
}
@Override
public int getCurrentHealth() {
return 0;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 0;
}
@Override
public String getName() {
return "thick layer of dust";
}
@Override
public int getSize() {
return 1;
}
@Override
public String getSymbol() {
return BlocksAndBoxes.BLOCK_HALF;
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
return 0;
}
}

View File

@ -1,40 +0,0 @@
package inf101.v18.rogue101.objects;
/**
* An actor is an IItem that can also do something, either controlled by the
* computer (INonPlayer) or the user (IPlayer).
*
* @author anya
*
*/
public interface IActor extends IItem {
/**
* @return This actor's attack score (used against an item's
* {@link #getDefence()} score to see if an attack is successful)
*/
int getAttack();
/**
* @return The damage this actor deals on a successful attack (used together
* with
* {@link #handleDamage(inf101.v18.rogue101.game.IGame, IItem, int)} on
* the target)
*/
int getDamage();
/**
* How many tiles the IActor is able to see in each direction.
*
* @return Number of tiles
*/
default int getVision() {
return 1;
}
/**
* Gets an item of the specified type, if the actor has the item.
*
* @return An IItem or null
*/
IItem getItem(Class<?> type);
}

View File

@ -1,181 +0,0 @@
package inf101.v18.rogue101.objects;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.rogue101.events.IEvent;
import inf101.v18.rogue101.game.IGame;
/**
* An {@link IItem} is something that can be placed on the map or into a
* container of items.
* <p>
* An {@link IActor} is a special case of {@link IItem} used for things that are
* alive, such as the player or AI-controlled monsters/NPCs.
* <p>
* By default, all items have a hit point / health system (they can be damaged),
* and can be picked up. So you could potentially destroy an item or pick up a
* monster.
*
* @author anya
*/
public interface IItem extends Comparable<IItem> {
@Override
default int compareTo(IItem other) {
return Integer.compare(getSize(), other.getSize());
}
/**
* Draw this item on the screen.
* <p>
* The turtle-painter will be positioned in the centre of the cell. You should
* avoid drawing outside the cell (size is indicated by the <code>w</code> and
* <code>h</code> parameters, so you can move ±w/2 and ±h/2 from the initial
* position). If you want to start in the lower left corner of the cell, you can
* start by doing <code>painter.jump(-w/2,h/2)</code> ((0,0) is in the top-left
* corner of the screen, so negative X points left and positive Y points down).
* <p>
* If this method returns <code>true</code>, the game will <em>not</em> print
* {@link #getSymbol()} in the cell.
* <p>
* All calls to <code>painter.save()</code> must be matched by a call to
* <code>painter.restore()</code>.
*
* @param painter
* A turtle-painter for drawing
* @param w
* The width of the cell
* @param h
* The height of the cell
* @return False if the letter from {@link #getSymbol()} should be drawn instead
*/
default boolean draw(ITurtle painter, double w, double h) {
return false;
}
/**
* @return "a" or "an", depending on the name
*/
default String getArticle() {
return "a";
}
/**
* Get current remaining health points.
* <p>
* An object's <em>health points</em> determines how much damage it can take
* before it is destroyed / broken / killed.
*
* @return Current health points for this item
*/
int getCurrentHealth();
/**
* The defence score determines how hard an object/actor is to hit or grab.
*
* @return Defence score of this object
*/
int getDefence();
/**
* Get item health as a 0.0..1.0 proportion.
*
* <li><code>getHealth() >= 1.0</code> means perfect condition
* <li><code>getHealth() <= 0.0</code> means broken or dead
* <li><code>0.0 < getHealth() < 1.0</code> means partially damaged
*
* @return Health, in the range 0.0 to 1.0
*/
default double getHealthStatus() {
return getMaxHealth() > 0 ? getCurrentHealth() / getMaxHealth() : 0;
}
/**
* Get maximum health points.
*
* An object's <em>health points</em> determines how much damage it can take
* before it is destroyed / broken / killed.
*
* @return Max health points for this item
*/
int getMaxHealth();
/**
* Get a (user-friendly) name for the item
* <p>
* Used for things like <code>"You see " + getArticle() + " " + getName()</code>
*
* @return Item's name
*/
String getName();
/**
* Get a map symbol used for printing this item on the screen.
* <p>
* This is usually the same as {@link #getSymbol()}, but could also include
* special control characters for changing the text colour, for example.
*
*
* @return A string to be displayed for this item on the screen (should be only
* one column wide when printed)
* @see <a href="https://en.wikipedia.org/wiki/ANSI_escape_code#Colors">ANSI
* escape code (on Wikipedia)</a>
*/
default String getPrintSymbol() {
return getSymbol();
}
/**
* Get the size of the object.
* <p>
* The size determines how much space an item will use if put into a container.
*
* @return Size of the item
*/
int getSize();
/**
* Get the map symbol of this item.
* <p>
* The symbol can be used on a text-only map, or when loading a map from text.
* <p>
* The symbol should be a single Unicode codepoint (i.e.,
* <code>getSymbol().codePointCount(0, getSymbol().length()) == 1</code>). In
* most cases this means that the symbol should be a single character (i.e.,
* getSymbol().length() == 1); but there are a few Unicode characters (such as
* many emojis and special symbols) that require two Java <code>char</code>s.
*
* @return A single-codepoint string with the item's symbol
*/
String getSymbol();
/**
* Inform the item that it has been damaged
*
* @param game
* The game
* @param source
* The item (usually an IActor) that caused the damage
* @param amount
* How much damage the item should take
* @return Amount of damage actually taken (could be less than
* <code>amount</code> due to armour/protection effects)
*/
int handleDamage(IGame game, IItem source, int amount);
/**
* Inform the item that something has happened.
*
* @param event
* An object describing the event.
* @return
*/
default <T> T handleEvent(IEvent<T> event) {
return event.getData();
}
/**
* @return True if this item has been destroyed, and should be removed from the map
*/
default boolean isDestroyed() {
return getCurrentHealth() < 0;
}
}

View File

@ -1,22 +0,0 @@
package inf101.v18.rogue101.objects;
import inf101.v18.rogue101.game.IGame;
/**
* An actor controlled by the computer
*
* @author anya
*
*/
public interface INonPlayer extends IActor {
/**
* Do one turn for this non-player
* <p>
* This INonPlayer will be the game's current actor ({@link IGame#getActor()})
* for the duration of this method call.
*
* @param game
* Game, for interacting with the world
*/
void doTurn(IGame game);
}

View File

@ -1,26 +0,0 @@
package inf101.v18.rogue101.objects;
import inf101.v18.rogue101.game.IGame;
import javafx.scene.input.KeyCode;
public interface IPlayer extends IActor {
/**
* Send key presses from the human player to the player object.
* <p>
* The player object should interpret the key presses, and then perform its
* moves or whatever, according to the game's rules and the player's
* instructions.
* <p>
* This IPlayer will be the game's current actor ({@link IGame#getActor()}) and
* be at {@link IGame#getLocation()}, when this method is called.
* <p>
* This method may be called many times in a single turn; the turn ends
* {@link #keyPressed(IGame, KeyCode)} returns and the player has used its
* movement points (e.g., by calling {@link IGame#move(inf101.v18.grid.GridDirection)}).
*
* @param game
* Game, for interacting with the world
* @return True if the player has done anything consuming a turn. False otherwise
*/
boolean keyPressed(IGame game, KeyCode key);
}

View File

@ -1,50 +0,0 @@
package inf101.v18.rogue101.objects;
import inf101.v18.gfx.gfxmode.ITurtle;
import inf101.v18.gfx.textmode.BlocksAndBoxes;
import inf101.v18.rogue101.game.IGame;
public class Wall implements IItem {
private int hp = getMaxHealth();
@Override
public boolean draw(ITurtle painter, double w, double h) {
return false;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
return 10;
}
@Override
public int getMaxHealth() {
return 1000;
}
@Override
public String getName() {
return "wall";
}
@Override
public int getSize() {
return Integer.MAX_VALUE;
}
@Override
public String getSymbol() {
return BlocksAndBoxes.BLOCK_FULL;
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
return amount;
}
}

View File

@ -1,226 +0,0 @@
package inf101.v18.rogue101.shared;
import inf101.v18.gfx.textmode.BlocksAndBoxes;
import inf101.v18.grid.GridDirection;
import inf101.v18.grid.ILocation;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.items.*;
import inf101.v18.rogue101.map.IMapView;
import inf101.v18.rogue101.objects.IActor;
import inf101.v18.rogue101.objects.IItem;
import inf101.v18.rogue101.objects.IPlayer;
import inf101.v18.rogue101.states.Attack;
import javafx.scene.media.AudioClip;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.List;
/**
* A holder class for methods used by IActors.
*/
public class NPC {
private NPC() {}
/**
* Performs a ranged attack on the closest actor (if any) observable by the current actor if range is > 1.
* Performs a melee attack on an actor (if any) on a neighbouring tile if range == 1.
* Moves closer to an enemy if an attack is not possible.
*
* @param game An IGame object
* @param range The range of the equipped weapon
* @return True if an attack or a move towards an enemy was successful. False otherwise
*/
public static boolean tryAttack(IGame game, int range, Attack type) {
List<ILocation> neighbours = game.getVisible();
for (ILocation neighbour : neighbours) {
IMapView map = game.getMap();
if (map.hasActors(neighbour) && map.getActors(neighbour).get(0) instanceof IPlayer) {
ILocation current = game.getLocation();
List<GridDirection> dirs = game.locationDirection(current, neighbour);
IActor actor = game.getMap().getActors(neighbour).get(0); //We assume there is only one actor.
for (GridDirection dir : dirs) {
if (type == Attack.MELEE
&& current.gridDistanceTo(neighbour) <= 1
&& current.canGo(dir)
&& game.getMap().has(current.go(dir), actor)
) {
game.attack(dir, actor);
return true;
}
if (range > 1 && current.gridDistanceTo(neighbour) <= range) {
game.rangedAttack(dir, actor, type);
return true;
}
}
for (GridDirection dir : dirs) {
if (game.canGo(dir)) {
game.move(dir);
return true;
}
}
}
}
return false;
}
/**
* Tries to find and reach an item of a specified class.
*
* @param game An IGame object
* @param validItems A list of classes the NPC should look for
* @return True if an appropriate item was found in the range of the current actor. False otherwise.
*/
public static boolean trackItem(IGame game, List<Class<?>> validItems) {
List<ILocation> neighbours = game.getVisible();
for (ILocation neighbour : neighbours) {
for (IItem item : game.getMap().getAll(neighbour)) {
for (Class<?> validItem : validItems) {
if (validItem.isInstance(item)) {
ILocation current = game.getLocation();
List<GridDirection> dirs = game.locationDirection(current, neighbour);
for (GridDirection dir : dirs) {
if (game.canGo(dir)) {
game.move(dir);
return true;
}
}
}
}
}
}
return false;
}
/**
* Picks up an item of one of the specified class types.
*
* @param game An IGame object
* @param validItems A list of classes the NPC should accept
* @return An item if it was successfully picked up. Null otherwise
*/
public static IItem pickUp(IGame game, List<Class<?>> validItems) {
for (IItem item : game.getLocalItems()) {
for (Class<?> validItem : validItems) {
if (validItem.isInstance(item)) {
return game.pickUp(item);
}
}
}
return null;
}
/**
* Makes an IActor go to the opposite direction of the closest enemy.
* Will return false if there are no visible enemies.
*
* @param game An IGame object
* @return True if the IActor fled. False otherwise
*/
public static boolean flee(IGame game) {
List<ILocation> neighbours = game.getVisible();
for (ILocation neighbour : neighbours) {
if (game.getMap().hasActors(neighbour)) {
ILocation current = game.getLocation();
List<GridDirection> dirs = reverseDir(game.locationDirection(current, neighbour));
for (GridDirection dir : dirs) {
if (game.canGo(dir)) {
game.move(dir);
return true;
}
}
}
}
return false;
}
/**
* Reverses a list of directions.
*
* @param dirs A list directions
* @return A list of the opposite directions
*/
private static List<GridDirection> reverseDir(List<GridDirection> dirs) {
for (int i = 0; i < dirs.size(); i++) {
GridDirection dir = dirs.get(i);
switch (dir) {
case SOUTH:
dirs.set(i, GridDirection.NORTH);
break;
case NORTH:
dirs.set(i, GridDirection.SOUTH);
break;
case WEST:
dirs.set(i, GridDirection.EAST);
break;
case EAST:
dirs.set(i, GridDirection.WEST);
}
}
return dirs;
}
/**
* Plays a sound.
*
* @param filename The String path of the audio file to play
*/
public static void playSound(String filename) {
URL url = NPC.class.getClassLoader().getResource(filename);
if (url != null) {
AudioClip clip = new AudioClip(url.toString());
clip.play();
} else {
System.out.println("Could not play audio file " + filename);
}
}
/**
* Generates a hp bar based on item's current hp
*
* @return HP bar as string
*/
public static String hpBar(IItem item) {
StringBuilder str = new StringBuilder(BlocksAndBoxes.BLOCK_HALF);
int hp = item.getCurrentHealth();
int hpLen = (int)((float)hp/item.getMaxHealth() * 10.0);
if (hp > 0 && hp < 100) {
str.append("\u001b[91m" + BlocksAndBoxes.BLOCK_BOTTOM + "\u001b[0m");
hpLen++;
} else {
for (int i = 0; i < hpLen; i++) {
str.append("\u001b[91m" + BlocksAndBoxes.BLOCK_HALF + "\u001b[0m");
}
}
for (int i = 0; i < 10 - hpLen; i++) {
str.append(" ");
}
str.append(BlocksAndBoxes.BLOCK_HALF);
return str.toString();
}
/**
* Gets the weapon appropriate for the used attack.
*
* @param type The attack type
* @return An IWeapon or null
*/
public static IWeapon getWeapon(Attack type, IActor actor) {
IWeapon weapon = null;
switch (type) {
case MELEE:
weapon = (IWeapon)actor.getItem(IMeleeWeapon.class);
break;
case RANGED:
weapon = (IWeapon)actor.getItem(IRangedWeapon.class);
break;
case MAGIC:
weapon = (IWeapon)actor.getItem(IMagicWeapon.class);
}
return weapon;
}
}

View File

@ -0,0 +1,12 @@
package inf101.v18.rogue101.state;
/**
* The type of a given attack
*/
public enum AttackType {
MELEE,
MAGIC,
RANGED
}

View File

@ -1,16 +1,18 @@
package inf101.v18.rogue101.states;
package inf101.v18.rogue101.state;
import java.util.Random;
/**
* An enum to distinguish different enemies of the same type.
* The age of an enemy, which alters some stats
*/
public enum Age {
public enum LifeStage {
TODDLER, CHILD, TEEN, ADULT, ELDER;
private static final Random random = new Random();
public static Age getRandom() {
public static LifeStage getRandom() {
return values()[random.nextInt(values().length)];
}
}

View File

@ -0,0 +1,31 @@
package inf101.v18.rogue101.state;
import java.util.Random;
/**
* The occupation of an enemy, which decides the type of attack it uses
*/
public enum Occupation {
/**
* A knight that always uses melee attacks
*/
KNIGHT,
/**
* A mage that always uses magic attacks
*/
MAGE,
/**
* An archer that always uses ranged attacks
*/
ARCHER;
private static final Random random = new Random();
public static Occupation getRandom() {
return values()[random.nextInt(values().length)];
}
}

View File

@ -0,0 +1,31 @@
package inf101.v18.rogue101.state;
import java.util.Random;
/**
* The personality of an enemy, which defines its combat behavior
*/
public enum Personality {
/**
* An enemy that attacks on sight
*/
AGGRESSIVE,
/**
* An enemy that attacks if attacked
*/
CALM,
/**
* An enemy that flees from battle
*/
AFRAID;
private static final Random random = new Random();
public static Personality getRandom() {
return values()[random.nextInt(values().length)];
}
}

View File

@ -0,0 +1,63 @@
package inf101.v18.rogue101.state;
import inf101.v18.util.NPCHelper;
import javafx.scene.media.AudioClip;
import java.net.URL;
/**
* A sound that can be played
*/
public enum Sound {
MELEE_NO_WEAPON("Realistic_Punch-Mark_DiAngelo-1609462330.wav"),
MELEE_SWORD("Sword Swing-SoundBible.com-639083727.wav"),
RANGED_NO_WEAPON("Snow Ball Throw And Splat-SoundBible.com-992042947.wav"),
RANGED_BOW("Bow_Fire_Arrow-Stephan_Schutze-2133929391.wav"),
RANGED_STAFF("Large Fireball-SoundBible.com-301502490.wav"),
GAME_OVER("Dying-SoundBible.com-1255481835.wav"),
WIN("1_person_cheering-Jett_Rifkin-1851518140.wav"),
NPC_DEATH("oh-no-113125.wav"),
;
private final String soundFile;
private AudioClip audioClip = null;
/**
* Instantiates a new sound file
*
* @param soundFile <p>The file containing this sound</p>
*/
Sound(String soundFile) {
this.soundFile = soundFile;
}
/**
* Gets the sound file for this sound
*
* @return <p>The sound file for this sound</p>
*/
public String getSoundFile() {
return "audio/" + soundFile;
}
/**
* Plays this sound
*/
public void play() {
if (audioClip == null) {
URL url = NPCHelper.class.getClassLoader().getResource(getSoundFile());
if (url != null) {
audioClip = new AudioClip(url.toString());
} else {
System.out.println("Could not play audio file " + getSoundFile());
}
}
// Play the sound in a new thread if it could be loaded
if (audioClip != null) {
new Thread(() -> audioClip.play()).start();
}
}
}

View File

@ -1,5 +0,0 @@
package inf101.v18.rogue101.states;
public enum Attack {
MELEE, MAGIC, RANGED
}

View File

@ -1,16 +0,0 @@
package inf101.v18.rogue101.states;
import java.util.Random;
/**
* An enum to distinguish different enemies of the same type.
*/
public enum Occupation {
KNIGHT, MAGE, BOWSMAN;
private static final Random random = new Random();
public static Occupation getRandom() {
return values()[random.nextInt(values().length)];
}
}

View File

@ -1,16 +0,0 @@
package inf101.v18.rogue101.states;
import java.util.Random;
/**
* An enum to distinguish different enemies of the same type.
*/
public enum Personality {
AGRESSIVE, CALM, AFRAID;
private static final Random random = new Random();
public static Personality getRandom() {
return values()[random.nextInt(values().length)];
}
}

View File

@ -0,0 +1,27 @@
package inf101.v18.util;
import java.util.Random;
/**
* An interface for generators of random data values (to be used in testing).
*
* @param <T> The type of data generated.
*/
public interface Generator<T> {
/**
* Generate a random object.
*
* @return An object of type T
*/
T generate();
/**
* Generate a random object.
*
* @param r A random generator
* @return An object of type T
*/
T generate(Random r);
}

View File

@ -1,53 +0,0 @@
package inf101.v18.util;
import java.util.List;
import java.util.Random;
/**
* An interface for generators of random data values (to be used in testing).
*
* @param <T>
* The type of data generated.
*/
public interface IGenerator<T> {
/**
* Generate a random object.
*
* @return An object of type T
*/
T generate();
/**
* Generate a random object.
*
* @param r
* A random generator
* @return An object of type T
*/
T generate(Random r);
/**
* Generate a number of equal objects.
*
* @param n
* The number of objects to generate.
* @return A list of objects, with the property that for any two objects a,b in
* the collection a.equals(b).
*
*/
List<T> generateEquals(int n);
/**
* Generate a number of equal objects.
*
* @param r
* A random generator
* @param n
* The number of objects to generate.
* @return A list of objects, with the property that for any two objects a,b in
* the collection a.equals(b).
*
*/
List<T> generateEquals(Random r, int n);
}

Some files were not shown because too many files have changed in this diff Show More