Cleans up project

This commit is contained in:
2020-02-14 01:01:38 +01:00
parent de6607442b
commit dfa7a142c3
126 changed files with 147 additions and 825 deletions

View File

@@ -0,0 +1,38 @@
package inf101.v18.gfx;
public interface IPaintLayer {
/**
* 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 front, so it will be drawn on top of any other layers.
*/
void layerToFront();
/**
* @return Width (in pixels) of graphics layer
*/
double getWidth();
/**
* @return Height (in pixels) of graphics layer
*/
double getHeight();
}

View File

@@ -0,0 +1,678 @@
package inf101.v18.gfx;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import inf101.v18.gfx.gfxmode.TurtlePainter;
import inf101.v18.gfx.textmode.Printer;
import inf101.v18.rogue101.AppInfo;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Bounds;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.SubScene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
public class Screen {
private static final double STD_CANVAS_WIDTH = 1280;
private static final List<Double> STD_ASPECTS = Arrays.asList(16.0 / 9.0, 16.0 / 10.0, 4.0 / 3.0);
/** 16:9 */
public static final int ASPECT_WIDE = 0;
/** 16:10 */
public static final int ASPECT_MEDIUM = 1;
/** 4:3 */
public static final int ASPECT_CLASSIC = 2;
public static final int ASPECT_NATIVE = 2;
private static final int CONFIG_ASPECT_SHIFT = 0;
/** Screen's initial aspect ratio should be 16:9 */
public static final int CONFIG_ASPECT_WIDE = 0 << CONFIG_ASPECT_SHIFT;
/** Screen's initial aspect ratio should be 16:10 */
public static final int CONFIG_ASPECT_MEDIUM = 1 << CONFIG_ASPECT_SHIFT;
/** Screen's initial aspect ratio should be 4:3 */
public static final int CONFIG_ASPECT_CLASSIC = 2 << CONFIG_ASPECT_SHIFT;
/** Screen's initial aspect ratio should be the same as the device display. */
public static final int CONFIG_ASPECT_DEVICE = 3 << CONFIG_ASPECT_SHIFT;
private static final int CONFIG_ASPECT_MASK = 3 << CONFIG_ASPECT_SHIFT;
private static final int CONFIG_SCREEN_SHIFT = 2;
/** Screen should start in a window. */
public static final int CONFIG_SCREEN_WINDOWED = 0 << CONFIG_SCREEN_SHIFT;
/** Screen should start in a borderless window. */
public static final int CONFIG_SCREEN_BORDERLESS = 1 << CONFIG_SCREEN_SHIFT;
/** Screen should start in a transparent window. */
public static final int CONFIG_SCREEN_TRANSPARENT = 2 << CONFIG_SCREEN_SHIFT;
/** Screen should start fullscreen. */
public static final int CONFIG_SCREEN_FULLSCREEN = 3 << CONFIG_SCREEN_SHIFT;
/**
* Screen should start fullscreen, without showing a "Press ESC to exit
* fullscreen" hint.
*/
public static final int CONFIG_SCREEN_FULLSCREEN_NO_HINT = 4 << CONFIG_SCREEN_SHIFT;
private static final int CONFIG_SCREEN_MASK = 7 << CONFIG_SCREEN_SHIFT;
private static final int CONFIG_PIXELS_SHIFT = 5;
/**
* Canvas size / number of pixels should be determined the default way.
*
* The default is {@link #CONFIG_PIXELS_DEVICE} for
* {@link #CONFIG_SCREEN_FULLSCREEN} and {@link #CONFIG_COORDS_DEVICE}, and
* {@link #CONFIG_PIXELS_STEP_SCALED} otherwise.
*/
public static final int CONFIG_PIXELS_DEFAULT = 0 << CONFIG_PIXELS_SHIFT;
/**
* Canvas size / number of pixels will be an integer multiple or fraction of the
* logical canvas size that fits the native display size.
*
* Scaling by whole integers makes it less likely that we get artifacts from
* rounding errors or JavaFX's antialiasing (e.g., fuzzy lines).
*/
public static final int CONFIG_PIXELS_STEP_SCALED = 1 << CONFIG_PIXELS_SHIFT;
/** Canvas size / number of pixels will the same as the native display size. */
public static final int CONFIG_PIXELS_DEVICE = 2 << CONFIG_PIXELS_SHIFT;
/**
* Canvas size / number of pixels will the same as the logical canvas size
* (typically 1280x960).
*/
public static final int CONFIG_PIXELS_LOGICAL = 3 << CONFIG_PIXELS_SHIFT;
/**
* Canvas size / number of pixels will be scaled to fit the native display size.
*/
public static final int CONFIG_PIXELS_SCALED = 4 << CONFIG_PIXELS_SHIFT;
private static final int CONFIG_PIXELS_MASK = 7 << CONFIG_PIXELS_SHIFT;
private static final int CONFIG_COORDS_SHIFT = 8;
/**
* The logical canvas coordinate system will be in logical units (i.e., 1280
* pixels wide regardless of how many pixels wide the screen actually is)
*/
public static final int CONFIG_COORDS_LOGICAL = 0 << CONFIG_COORDS_SHIFT;
/** The logical canvas coordinate system will match the display. */
public static final int CONFIG_COORDS_DEVICE = 1 << CONFIG_COORDS_SHIFT;
private static final int CONFIG_COORDS_MASK = 1 << CONFIG_COORDS_SHIFT;
private static final int CONFIG_FLAG_SHIFT = 9;
public static final int CONFIG_FLAG_HIDE_MOUSE = 1 << CONFIG_FLAG_SHIFT;
public static final int CONFIG_FLAG_NO_AUTOHIDE_MOUSE = 2 << CONFIG_FLAG_SHIFT;
public static final int CONFIG_FLAG_DEBUG = 4 << CONFIG_FLAG_SHIFT;
private static final int CONFIG_FLAG_MASK = 7;
/**
* Get the resolution of this screen, in DPI (pixels per inch).
*
* @return The primary display's DPI
* @see javafx.stage.Screen#getDpi()
*/
public static double getDisplayDpi() {
return javafx.stage.Screen.getPrimary().getDpi();
}
/**
* Get the height of the display, in pixels.
*
* <p>
* This takes into account such things as toolbars, menus and such (on a
* desktop), and pixel density (e.g., on high resolution mobile devices).
*
* @return Height of the display
* @see javafx.stage.Screen#getVisualBounds()
*/
public static double getDisplayHeight() {
return javafx.stage.Screen.getPrimary().getVisualBounds().getHeight();
}
/**
* Get the width of the display, in pixels.
*
* <p>
* This takes into account such things as toolbars, menus and such (on a
* desktop), and pixel density (e.g., on high resolution mobile devices).
*
* @return Width of the display
* @see javafx.stage.Screen#getVisualBounds()
*/
public static double getDisplayWidth() {
return javafx.stage.Screen.getPrimary().getVisualBounds().getWidth();
}
/**
* Get the native physical height of the screen, in pixels.
*
* <p>
* This will not include such things as toolbars, menus and such (on a desktop),
* or take pixel density into account (e.g., on high resolution mobile devices).
*
* @return Raw width of the display
* @see javafx.stage.Screen#getBounds()
*/
public static double getRawDisplayHeight() {
return javafx.stage.Screen.getPrimary().getBounds().getHeight();
}
/**
* Get the native physical width of the screen, in pixels.
*
* <p>
* This will not include such things as toolbars, menus and such (on a desktop),
* or take pixel density into account (e.g., on high resolution mobile devices).
*
* @return Raw width of the display
* @see javafx.stage.Screen#getBounds()
*/
public static double getRawDisplayWidth() {
return javafx.stage.Screen.getPrimary().getBounds().getWidth();
}
/**
* Start the paint display system.
*
* This will open a window on the screen, and set up background, text and paint
* layers, and listener to handle keyboard input.
*
* @param stage
* A JavaFX {@link javafx.stage.Stage}, typically obtained from the
* {@link javafx.application.Application#start(Stage)} method
* @return A screen for drawing on
*/
public static Screen startPaintScene(Stage stage) {
return startPaintScene(stage, CONFIG_SCREEN_FULLSCREEN_NO_HINT);
}
/**
* Start the paint display system.
*
* This will open a window on the screen, and set up background, text and paint
* layers, and listener to handle keyboard input.
*
* @param stage
* A JavaFX {@link javafx.stage.Stage}, typically obtained from the
* {@link javafx.application.Application#start(Stage)} method
* @return A screen for drawing on
*/
public static Screen startPaintScene(Stage stage, int configuration) {
int configAspect = (configuration & CONFIG_ASPECT_MASK);
int configScreen = (configuration & CONFIG_SCREEN_MASK);
int configPixels = (configuration & CONFIG_PIXELS_MASK);
int configCoords = (configuration & CONFIG_COORDS_MASK);
int configFlags = (configuration & CONFIG_FLAG_MASK);
boolean debug = (configFlags & CONFIG_FLAG_DEBUG) != 0;
if (configPixels == CONFIG_PIXELS_DEFAULT) {
if (configCoords == CONFIG_COORDS_DEVICE || configScreen == CONFIG_SCREEN_FULLSCREEN)
configPixels = CONFIG_PIXELS_DEVICE;
else
configPixels = CONFIG_PIXELS_STEP_SCALED;
}
double rawWidth = getRawDisplayWidth();
double rawHeight = getRawDisplayHeight();
double width = getDisplayWidth() - 40;
double height = getDisplayHeight() - 100;
double canvasAspect = configAspect == CONFIG_ASPECT_DEVICE ? rawWidth / rawHeight
: STD_ASPECTS.get(configAspect);
double xScale = (height * canvasAspect) / Screen.STD_CANVAS_WIDTH;
double yScale = (width / canvasAspect) / (Screen.STD_CANVAS_WIDTH / canvasAspect);
double scale = Math.min(xScale, yScale);
if (configPixels == CONFIG_PIXELS_STEP_SCALED) {
if (scale > 1.0)
scale = Math.max(1, Math.floor(scale));
else if (scale < 1.0)
scale = 1 / Math.max(1, Math.floor(1 / scale));
}
double winWidth = Math.floor(Screen.STD_CANVAS_WIDTH * scale);
double winHeight = Math.floor((Screen.STD_CANVAS_WIDTH / canvasAspect) * scale);
double canvasWidth = Screen.STD_CANVAS_WIDTH;
double canvasHeight = Math.floor(3 * Screen.STD_CANVAS_WIDTH / 4);
double pixWidth = canvasWidth;
double pixHeight = canvasHeight;
if (configPixels == CONFIG_PIXELS_SCALED || configPixels == CONFIG_PIXELS_STEP_SCALED) {
pixWidth *= scale;
pixHeight *= scale;
} else if (configPixels == CONFIG_PIXELS_DEVICE) {
pixWidth = rawWidth;
pixHeight = rawHeight;
}
if (configCoords == CONFIG_COORDS_DEVICE) {
canvasWidth = pixWidth;
canvasHeight = pixHeight;
}
if (debug) {
System.out.printf("Screen setup:%n");
System.out.printf(" Display: %.0fx%.0f (raw %.0fx%.0f)%n", width, height, rawWidth, rawHeight);
System.out.printf(" Window: %.0fx%.0f%n", winWidth, winHeight);
System.out.printf(" Canvas: physical %.0fx%.0f, logical %.0fx%.0f%n", pixWidth, pixHeight, canvasWidth,
canvasHeight);
System.out.printf(" Aspect: %.5f Scale: %.5f%n", canvasAspect, scale);
}
Group root = new Group();
Scene scene = new Scene(root, winWidth, winHeight, Color.BLACK);
stage.setScene(scene);
stage.setTitle(AppInfo.APP_NAME);
if ((configFlags & CONFIG_FLAG_HIDE_MOUSE) != 0) {
scene.setCursor(Cursor.NONE);
}
Screen pScene = new Screen(scene.getWidth(), scene.getHeight(), //
pixWidth, pixHeight, //
canvasWidth, canvasHeight);
pScene.subScene.widthProperty().bind(scene.widthProperty());
pScene.subScene.heightProperty().bind(scene.heightProperty());
pScene.debug = debug;
pScene.hideFullScreenMouseCursor = (configFlags & CONFIG_FLAG_NO_AUTOHIDE_MOUSE) == 0;
root.getChildren().add(pScene.subScene);
boolean[] suppressKeyTyped = { false };
switch (configScreen) {
case CONFIG_SCREEN_WINDOWED:
break;
case CONFIG_SCREEN_BORDERLESS:
stage.initStyle(StageStyle.UNDECORATED);
break;
case CONFIG_SCREEN_TRANSPARENT:
stage.initStyle(StageStyle.TRANSPARENT);
break;
case CONFIG_SCREEN_FULLSCREEN_NO_HINT:
stage.setFullScreenExitHint("");
// fall-through
case CONFIG_SCREEN_FULLSCREEN:
stage.setFullScreen(true);
break;
}
scene.setOnKeyPressed((KeyEvent event) -> {
if (!event.isConsumed() && pScene.keyOverride != null && pScene.keyOverride.test(event)) {
event.consume();
}
if (!event.isConsumed() && pScene.minimalKeyHandler(event)) {
event.consume();
}
if (!event.isConsumed() && pScene.keyPressedHandler != null && pScene.keyPressedHandler.test(event)) {
event.consume();
}
if (pScene.logKeyEvents)
System.err.println(event);
suppressKeyTyped[0] = event.isConsumed();
});
scene.setOnKeyTyped((KeyEvent event) -> {
if (suppressKeyTyped[0]) {
suppressKeyTyped[0] = false;
event.consume();
}
if (!event.isConsumed() && pScene.keyTypedHandler != null && pScene.keyTypedHandler.test(event)) {
event.consume();
}
if (pScene.logKeyEvents)
System.err.println(event);
});
scene.setOnKeyReleased((KeyEvent event) -> {
suppressKeyTyped[0] = false;
if (!event.isConsumed() && pScene.keyReleasedHandler != null && pScene.keyReleasedHandler.test(event)) {
event.consume();
}
if (pScene.logKeyEvents)
System.err.println(event);
});
return pScene;
}
private final double rawCanvasWidth;
private final double rawCanvasHeight;
private boolean logKeyEvents = false;
private final SubScene subScene;
private final List<Canvas> canvases = new ArrayList<>();
private final Map<IPaintLayer, Canvas> layerCanvases = new IdentityHashMap<>();
private final Canvas background;
private final Group root;
//private Paint bgColor = Color.CORNFLOWERBLUE;
private Paint bgColor = Color.BLACK;
private int aspect = 0;
private double scaling = 0;
private double currentScale = 1.0;
private double currentFit = 1.0;
private double resolutionScale = 1.0;
private int maxScale = 1;
private Predicate<KeyEvent> keyOverride = null;
private Predicate<KeyEvent> keyPressedHandler = null;
private Predicate<KeyEvent> keyTypedHandler = null;
private Predicate<KeyEvent> keyReleasedHandler = null;
private boolean debug = true;
private List<Double> aspects;
private boolean hideFullScreenMouseCursor = true;
private Cursor oldCursor;
public Screen(double width, double height, double pixWidth, double pixHeight, double canvasWidth,
double canvasHeight) {
root = new Group();
subScene = new SubScene(root, Math.floor(width), Math.floor(height));
resolutionScale = pixWidth / canvasWidth;
this.rawCanvasWidth = Math.floor(pixWidth);
this.rawCanvasHeight = Math.floor(pixHeight);
double aspectRatio = width / height;
aspect = 0;
for (double a : STD_ASPECTS)
if (Math.abs(aspectRatio - a) < 0.01) {
break;
} else {
aspect++;
}
aspects = new ArrayList<>(STD_ASPECTS);
if (aspect >= STD_ASPECTS.size()) {
aspects.add(aspectRatio);
}
background = new Canvas(rawCanvasWidth, rawCanvasHeight);
background.getGraphicsContext2D().scale(resolutionScale, resolutionScale);
setBackground(bgColor);
clearBackground();
root.getChildren().add(background);
subScene.layoutBoundsProperty()
.addListener((ObservableValue<? extends Bounds> observable, Bounds oldBounds, Bounds bounds) -> {
recomputeLayout(false);
});
}
public void clearBackground() {
getBackgroundContext().setFill(bgColor);
getBackgroundContext().fillRect(0.0, 0.0, background.getWidth(), background.getHeight());
}
public TurtlePainter createPainter() {
Canvas canvas = new Canvas(rawCanvasWidth, rawCanvasHeight);
canvas.getGraphicsContext2D().scale(resolutionScale, resolutionScale);
canvases.add(canvas);
root.getChildren().add(canvas);
return new TurtlePainter(this, canvas);
}
public Printer createPrinter() {
Canvas canvas = new Canvas(rawCanvasWidth, rawCanvasHeight);
canvas.getGraphicsContext2D().scale(resolutionScale, resolutionScale);
canvases.add(canvas);
root.getChildren().add(canvas);
return new Printer(this, canvas);
}
public void cycleAspect() {
aspect = (aspect + 1) % aspects.size();
recomputeLayout(false);
}
public void fitScaling() {
scaling = 0;
recomputeLayout(true);
}
public int getAspect() {
return aspect;
}
public GraphicsContext getBackgroundContext() {
return background.getGraphicsContext2D();
}
public double getHeight() {
return Math.floor(getRawHeight() / resolutionScale);
}
/** @return the keyOverride */
public Predicate<KeyEvent> getKeyOverride() {
return keyOverride;
}
/** @return the keyHandler */
public Predicate<KeyEvent> getKeyPressedHandler() {
return keyPressedHandler;
}
/** @return the keyReleasedHandler */
public Predicate<KeyEvent> getKeyReleasedHandler() {
return keyReleasedHandler;
}
/** @return the keyTypedHandler */
public Predicate<KeyEvent> getKeyTypedHandler() {
return keyTypedHandler;
}
public double getRawHeight() {
return Math.floor(rawCanvasWidth / aspects.get(aspect));
}
public double getRawWidth() {
return rawCanvasWidth;
}
public double getWidth() {
return Math.floor(getRawWidth() / resolutionScale);
}
public void hideMouseCursor() {
subScene.getScene().setCursor(Cursor.NONE);
}
public boolean isFullScreen() {
Window window = subScene.getScene().getWindow();
if (window instanceof Stage)
return ((Stage) window).isFullScreen();
else
return false;
}
public boolean minimalKeyHandler(KeyEvent event) {
KeyCode code = event.getCode();
if (event.isShortcutDown()) {
if (code == KeyCode.Q) {
System.exit(0);
} else if (code == KeyCode.PLUS) {
zoomIn();
return true;
} else if (code == KeyCode.MINUS) {
zoomOut();
return true;
}
} else if (!(event.isAltDown() || event.isControlDown() || event.isMetaDown() || event.isShiftDown())) {
if (code == KeyCode.F11) {
setFullScreen(!isFullScreen());
return true;
}
}
return false;
}
public void moveToBack(IPaintLayer layer) {
Canvas canvas = layerCanvases.get(layer);
if (canvas != null) {
canvas.toBack();
background.toBack();
}
}
public void moveToFront(IPaintLayer layer) {
Canvas canvas = layerCanvases.get(layer);
if (canvas != null) {
canvas.toFront();
}
}
private void recomputeLayout(boolean resizeWindow) {
double xScale = subScene.getWidth() / getRawWidth();
double yScale = subScene.getHeight() / getRawHeight();
double xMaxScale = getDisplayWidth() / getRawWidth();
double yMaxScale = getDisplayHeight() / getRawHeight();
currentFit = Math.min(xScale, yScale);
maxScale = (int) Math.max(1, Math.ceil(Math.min(xMaxScale, yMaxScale)));
currentScale = scaling == 0 ? currentFit : scaling;
if (resizeWindow) {
Scene scene = subScene.getScene();
Window window = scene.getWindow();
double hBorder = window.getWidth() - scene.getWidth();
double vBorder = window.getHeight() - scene.getHeight();
double myWidth = getRawWidth() * currentScale;
double myHeight = getRawHeight() * currentScale;
if (debug)
System.out.printf(
"Resizing before: screen: %1.0fx%1.0f, screen: %1.0fx%1.0f, scene: %1.0fx%1.0f, window: %1.0fx%1.0f,%n border: %1.0fx%1.0f, new window size: %1.0fx%1.0f, canvas size: %1.0fx%1.0f%n", //
javafx.stage.Screen.getPrimary().getVisualBounds().getWidth(),
javafx.stage.Screen.getPrimary().getVisualBounds().getHeight(), subScene.getWidth(),
subScene.getHeight(), scene.getWidth(), scene.getHeight(), window.getWidth(),
window.getHeight(), hBorder, vBorder, myWidth, myHeight, getRawWidth(), getRawHeight());
// this.setWidth(myWidth);
// this.setHeight(myHeight);
window.setWidth(myWidth + hBorder);
window.setHeight(myHeight + vBorder);
if (debug)
System.out.printf(
"Resizing after : screen: %1.0fx%1.0f, screen: %1.0fx%1.0f, scene: %1.0fx%1.0f, window: %1.0fx%1.0f,%n border: %1.0fx%1.0f, new window size: %1.0fx%1.0f, canvas size: %1.0fx%1.0f%n",
javafx.stage.Screen.getPrimary().getVisualBounds().getWidth(),
javafx.stage.Screen.getPrimary().getVisualBounds().getHeight(), subScene.getWidth(),
subScene.getHeight(), scene.getWidth(), scene.getHeight(), window.getWidth(),
window.getHeight(), hBorder, vBorder, myWidth, myHeight, getRawWidth(), getRawHeight());
}
if (debug)
System.out.printf("Rescaling: subscene %1.2fx%1.2f, scale %1.2f, aspect %.4f (%d), canvas %1.0fx%1.0f%n",
subScene.getWidth(), subScene.getHeight(), currentScale, aspects.get(aspect), aspect, getRawWidth(),
getRawHeight());
for (Node n : root.getChildren()) {
n.relocate(Math.floor(subScene.getWidth() / 2),
Math.floor(subScene.getHeight() / 2 + (rawCanvasHeight - getRawHeight()) * currentScale / 2));
n.setTranslateX(-Math.floor(rawCanvasWidth / 2));
n.setTranslateY(-Math.floor(rawCanvasHeight / 2));
if (debug)
System.out.printf(" * layout %1.2fx%1.2f, translate %1.2fx%1.2f%n", n.getLayoutX(), n.getLayoutY(),
n.getTranslateX(), n.getTranslateY());
n.setScaleX(currentScale);
n.setScaleY(currentScale);
}
}
public void setAspect(int aspect) {
this.aspect = (aspect) % aspects.size();
recomputeLayout(false);
}
public void setBackground(Paint bgColor) {
this.bgColor = bgColor;
subScene.setFill(bgColor instanceof Color ? ((Color) bgColor).darker() : bgColor);
}
public void setFullScreen(boolean fullScreen) {
Window window = subScene.getScene().getWindow();
if (window instanceof Stage) {
((Stage) window).setFullScreenExitHint("");
((Stage) window).setFullScreen(fullScreen);
if (hideFullScreenMouseCursor) {
if (fullScreen) {
oldCursor = subScene.getScene().getCursor();
subScene.getScene().setCursor(Cursor.NONE);
} else if (oldCursor != null) {
subScene.getScene().setCursor(oldCursor);
oldCursor = null;
} else {
subScene.getScene().setCursor(Cursor.DEFAULT);
}
}
}
}
public void setHideFullScreenMouseCursor(boolean hideIt) {
if (hideIt != hideFullScreenMouseCursor && isFullScreen()) {
if (hideIt) {
oldCursor = subScene.getScene().getCursor();
subScene.getScene().setCursor(Cursor.NONE);
} else if (oldCursor != null) {
subScene.getScene().setCursor(oldCursor);
oldCursor = null;
} else {
subScene.getScene().setCursor(Cursor.DEFAULT);
}
}
hideFullScreenMouseCursor = hideIt;
}
/**
* @param keyOverride
* the keyOverride to set
*/
public void setKeyOverride(Predicate<KeyEvent> keyOverride) {
this.keyOverride = keyOverride;
}
/**
* @param keyHandler
* the keyHandler to set
*/
public void setKeyPressedHandler(Predicate<KeyEvent> keyHandler) {
this.keyPressedHandler = keyHandler;
}
/**
* @param keyReleasedHandler
* the keyReleasedHandler to set
*/
public void setKeyReleasedHandler(Predicate<KeyEvent> keyReleasedHandler) {
this.keyReleasedHandler = keyReleasedHandler;
}
/**
* @param keyTypedHandler
* the keyTypedHandler to set
*/
public void setKeyTypedHandler(Predicate<KeyEvent> keyTypedHandler) {
this.keyTypedHandler = keyTypedHandler;
}
public void setMouseCursor(Cursor cursor) {
subScene.getScene().setCursor(cursor);
}
public void showMouseCursor() {
subScene.getScene().setCursor(Cursor.DEFAULT);
}
public void zoomCycle() {
scaling++;
if (scaling > maxScale)
scaling = ((int) scaling) % maxScale;
recomputeLayout(true);
}
public void zoomFit() {
scaling = 0;
recomputeLayout(false);
}
public void zoomIn() {
scaling = Math.min(10, currentScale + 0.2);
recomputeLayout(false);
}
public void zoomOne() {
scaling = 1;
recomputeLayout(false);
}
public void zoomOut() {
scaling = Math.max(0.1, currentScale - 0.2);
recomputeLayout(false);
}
}

View File

@@ -0,0 +1,39 @@
# ZX Spectrum 7 Font
By Sizenko Alexander, [Style-7](http://www.styleseven.com), December 2012. From http://www.styleseven.com/php/get_product.php?product=ZX-Spectrum-7
Minor metrics adjustments by Anya Helene Bagge, October 2017.
* ZXSpectrum-7.otf monospaced regular
# True Type Font: ZX Spectrum-7 version 1.0
## EULA
The font ZX Spectrum-7 is freeware.
## DESCRIPTION
This font has been created to mark the 30th anniversary of the great computer ZX-Spectrum. Font based on native ZX-Spectrum symbols. Latin and Cyrillic code pages are supported.
Files in zx_spectrum-7.zip:
* readme.txt this file;
* zx_spectrum-7.ttf regular style;
* zx_spectrum-7_bold.ttf bold style;
* zx_spectrum-7_screen.png preview image.
Please visit http://www.styleseven.com/ for download our other products as freeware as shareware.
We will welcome any useful suggestions and comments; please send them to ms-7@styleseven.com
## WHAT'S NEW?
* Version 1.01 (December 27 2012):
* Fixed bug for Cyrillic code page.
## AUTHOR
Sizenko Alexander
Style-7
http://www.styleseven.com
Created: December 24 2012

View File

@@ -0,0 +1,171 @@
This package was debianized by Florent Rougon <f.rougon@free.fr> on
Tue, 27 Jan 2004 20:12:21 +0100.
The following TeX Live packages were downloaded from
http://www.ctan.org/tex-archive/systems/texlive/tlnet/archive/
and merged into one orig.tar.gz file:
lm.tar.xz
lm.doc.tar.xz
lm-math.tar.xz
lm-math.doc.tar.xz
Upstream work
-------------
The upstream README-Latin-Modern.txt file says:
Font: The Latin Modern Family of Fonts
Designer (Computer Modern Family of Fonts): Donald E. Knuth
Author: Bogus\l{}aw Jackowski and Janusz M. Nowacki
Version: 2.003
Date: 16 IX 2009
Downloads: http://www.gust.org.pl/projects/e-foundry/latin-modern/
License:
% Copyright 2003--2009 by B. Jackowski and J.M. Nowacki
% (on behalf of TeX Users Groups).
% This work is released under the GUST Font License
% -- see GUST-FONT-LICENSE.txt.
% This work has the LPPL maintenance status "maintained".
% The Current Maintainer of this work is Bogus\l{}aw Jackowski
% and Janusz M. Nowacki.
% This work consists of the files listed in the MANIFEST.txt file.
[...]
The current LM package contains the most recent version
of the Latin Modern family of fonts in the PostScript Type 1 and
OpenType format. The fonts are based on Donald E. Knuth's Computer Modern
fonts in the PostScript Type 1 format, released into public domain by the
American Mathematical Society (for the history of the outline version of
the CM fonts see, e.g., http://www.math.utah.edu/~beebe/fonts/bluesky.html ).
The project is supported by TeX users groups: CSTUG, DANTE eV, GUST,
GUTenberg, NTG, and TUG.
The current README-Latin-Modern-Math.txt says
License:
% Copyright 2012--2014 for the Latin Modern math extensions by B. Jackowski,
% P. Strzelczyk and P. Pianowski (on behalf of TeX Users Groups).
%
% This work can be freely used and distributed under
% the GUST Font License (GFL -- see GUST-FONT-LICENSE.txt)
% which is actually an instance of the LaTeX Project Public License
% (LPPL -- see http://www.latex-project.org/lppl.txt).
%
% This work has the maintenance status "maintained". The Current Maintainer
% of this work is Bogus\l{}aw Jackowski, Piotr Strzelczyk and Piotr Pianowski.
%
% This work consists of the files listed
% in the MANIFEST-Latin-Modern-Math.txt file.
See the appendix B for the GUST Font License.
Please read the appendix A below if you want to examine the licensing terms
for the Computer Modern fonts in Type 1 format on which the Latin Modern fonts
are based.
Debian packaging
----------------
Copyright (c) 2004-2007 Florent Rougon
Copyright (c) 2005-2015 Norbert Preining
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 dated June, 1991.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
Boston, MA 02110-1301 USA.
On Debian systems, the complete text of the GNU General Public License version
2 can be found in `/usr/share/common-licenses/GPL-2'.
Appendix A -- Licensing terms for the Computer Modern fonts in Type 1 format
on which the Latin Modern fonts are based.
-----------------------------------------------------------------------------
Running t1disasm (from the t1utils package) on
/usr/share/texmf/fonts/type1/bluesky/cm/*.pfb and
/usr/share/texmf/fonts/type1/bluesky/cmextra/*.pfb yields:
Copyright (C) 1997 American Mathematical Society. All Rights Reserved
[ Florent Rougon's note: well, for
/usr/share/texmf/fonts/type1/bluesky/cm/cmb{,sy}10.pfb, you will only get
one space between "Society." and "All" (with tetex-extra 2.0.2-5.1). ;-) ]
The precise distribution conditions for these fonts can be found in
/usr/share/doc/texmf/fonts/bluesky/README from the tetex-doc package. I will
duplicate here the relevant excerpt for your convenience:
The PostScript Type 1 implementation of the Computer Modern fonts produced
by and previously distributed by Blue Sky Research and Y&Y, Inc. are now
freely available for general use. This has been accomplished through the
cooperation of a consortium of scientific publishers with Blue Sky Research
and Y&Y. Members of this consortium include:
Elsevier Science
IBM Corporation
Society for Industrial and Applied Mathematics (SIAM)
Springer-Verlag
American Mathematical Society (AMS)
In order to assure the authenticity of these fonts, copyright will be held
by the American Mathematical Society. This is not meant to restrict in any
way the legitimate use of the fonts, such as (but not limited to) electronic
distribution of documents containing these fonts, inclusion of these fonts
into other public domain or commercial font collections or computer
applications, use of the outline data to create derivative fonts and/or
faces, etc. However, the AMS does require that the AMS copyright notice be
removed from any derivative versions of the fonts which have been altered in
any way. In addition, to ensure the fidelity of TeX documents using Computer
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
has requested that any alterations which yield different font metrics be
given a different name.
Appendix B -- GUST Font License
-------------------------------
What follows is the exact contents of GUST-FONT-LICENSE.txt from the
upstream distribution of the Latin Modern fonts.
% This is version 1.0, dated 22 June 2009, of the GUST Font License.
% (GUST is the Polish TeX Users Group, http://www.gust.org.pl)
%
% For the most recent version of this license see
% http://www.gust.org.pl/fonts/licenses/GUST-FONT-LICENSE.txt
% or
% http://tug.org/fonts/licenses/GUST-FONT-LICENSE.txt
%
% This work may be distributed and/or modified under the conditions
% of the LaTeX Project Public License, either version 1.3c of this
% license or (at your option) any later version.
%
% Please also observe the following clause:
% 1) it is requested, but not legally required, that derived works be
% distributed only after changing the names of the fonts comprising this
% work and given in an accompanying "manifest", and that the
% files comprising the Work, as listed in the manifest, also be given
% new names. Any exceptions to this request are also given in the
% manifest.
%
% We recommend the manifest be given in a separate file named
% MANIFEST-<fontid>.txt, where <fontid> is some unique identification
% of the font family. If a separate "readme" file accompanies the Work,
% we recommend a name of the form README-<fontid>.txt.
%
% The latest version of the LaTeX Project Public License is in
% http://www.latex-project.org/lppl.txt and version 1.3c or later
% is part of all distributions of LaTeX version 2006/05/20 or later.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,205 @@
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);
}
private double xDir;
private double yDir;
/**
* 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();
}
/**
* 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();
}
/**
* Multiply direction by distance
*
* @param distance
* @return Position delta
*/
public Point getMovement(double distance) {
return new Point(xDir * distance, -yDir * distance);
}
/**
* @return X-component of direction vector
*
* Same as the Math.cos(toRadians())
*/
public double getX() {
return xDir;
}
/**
* @return Y-component of direction vector
*
* 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, -2π .. 2π
*/
public double toRadians() {
return Math.atan2(yDir, xDir);
}
@Override
public String toString() {
return String.format("%.2f", toDegrees());
}
/**
* Turn (relative)
*
* @param deltaDir
*/
public Direction turn(Direction deltaDir) {
return new Direction(xDir + deltaDir.xDir, yDir + deltaDir.yDir);
}
/**
* Turn angle degrees
*
* @param angle
*/
public Direction turn(double angle) {
return turnTo(toDegrees() + angle);
}
/**
* Turn around 180 degrees
*/
public Direction turnBack() {
return turn(180.0);
}
/**
* Turn left 90 degrees
*/
public Direction turnLeft() {
return turn(90.0);
}
/**
* 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));
}
}

View File

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

View File

@@ -0,0 +1,49 @@
package inf101.v18.gfx.gfxmode;
import inf101.v18.gfx.IPaintLayer;
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();
/**
* 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);
/**
* 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();
}

View File

@@ -0,0 +1,239 @@
package inf101.v18.gfx.gfxmode;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Paint;
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 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);
/**
* 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);
/**
* Close the line path, turning it into a polygon.
*
* @return
*/
IShape close();
void draw();
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();
/**
* 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 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 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);
/**
* 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();
/**
* 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();
/**
* 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();
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 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);
}

View File

@@ -0,0 +1,270 @@
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);
/**
* 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();
/**
* 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 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 direction of the turtle. Same as calling
* <code>new Direction(getAngle())</code>
*/
Direction getDirection();
/**
* @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 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);
/**
* 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);
/**
* 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);
/**
* 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.
*
* <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 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 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);
/**
* 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

@@ -0,0 +1,116 @@
package inf101.v18.gfx.gfxmode;
public class Point {
private final double x;
private final double 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 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 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 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);
}
/**
* 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);
}
/**
* 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);
}
}

View File

@@ -0,0 +1,329 @@
package inf101.v18.gfx.gfxmode;
import java.util.List;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Shape;
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;
}
}
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;
}
}
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);
// 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();
}
protected abstract void strokeIt(GraphicsContext ctx, ShapePainter p);
}
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 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 {
@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);
}
}
}
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 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 Gravity gravity = Gravity.CENTER;
private DrawCommand cmd = null;
private boolean closed = false;
private final GraphicsContext 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(Point xy) {
lineSegments.add(xy.getX());
lineSegments.add(xy.getY());
return this;
}
@Override
public ShapePainter angle(double a) {
return this;
}
@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 IShape close() {
closed = true;
return this;
}
@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 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 fillPaint(Paint p) {
fill = p;
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 length(double l) {
w = l;
h = l;
return this;
}
@Override
public IShape line() {
cmd = new DrawLine();
return this;
}
@Override
public IShape rectangle() {
cmd = new DrawRectangle();
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 strokePaint(Paint p) {
stroke = p;
return this;
}
@Override
public Shape toFXShape() {
throw new UnsupportedOperationException();
}
@Override
public String toSvg() {
throw new UnsupportedOperationException();
}
@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 y(double y) {
this.y = y;
return this;
}
}

View File

@@ -0,0 +1,373 @@
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;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeLineJoin;
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;
public TurtleState() {
}
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 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(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
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);
if (!path && context != null) {
context.stroke();
// context.restore();
}
return this;
}
@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(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(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 Direction getDirection() {
return state.dir;
}
@Override
public double getHeight() {
return height;
}
@Override
public Point getPos() {
return state.pos;
}
public Screen getScreen() {
return screen;
}
@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(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;
}
@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 void layerToBack() {
if (screen != null)
screen.moveToBack(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 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 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 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 turnAround() {
return turn(180);
}
@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 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 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 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 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 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;
}
}

View File

@@ -0,0 +1,201 @@
package inf101.v18.gfx.textmode;
import java.util.Arrays;
import java.util.Iterator;
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);
private List<Integer> order;
PixelOrder(int a, int b, int c, int d) {
order = Arrays.asList(a, b, c, d);
}
@Override
public Iterator<Integer> iterator() {
return order.iterator();
}
}
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 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;
}
/**
* 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 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 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

@@ -0,0 +1,276 @@
package inf101.v18.gfx.textmode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.BiConsumer;
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;
}
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 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 String patStr;
private Pattern pattern;
private int defaultArg = 0;
private String desc;
private Consumer<Printer> handler0;
private BiConsumer<Printer, Integer> handler1;
private BiConsumer<Printer, List<Integer>> handlerN;
private int numArgs;
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 getCommandLetter() {
return patStr.substring(patStr.length() - 1);
}
public String getDescription() {
return desc;
}
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 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 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 };
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 boolean applyCsi(Printer printer, String csi) {
CsiPattern csiPattern = patterns.get(csi.substring(csi.length() - 1));
// System.out.println("Applying CSI: " + csi.replaceAll("\u001b", "ESC"));
if (csiPattern != null) {
if (csiPattern.match(printer, csi))
return true;
else
System.err.println("Handler failed for escape sequence: " + csi.replaceAll("\u001b", "ESC"));
} 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

@@ -0,0 +1,153 @@
package inf101.v18.gfx.textmode;
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();
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 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();
}
}
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);
}
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);
}
}

View File

@@ -0,0 +1,844 @@
package inf101.v18.gfx.textmode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import inf101.v18.gfx.IPaintLayer;
import inf101.v18.gfx.Screen;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.effect.BlendMode;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
public class Printer implements IPaintLayer {
private static class Char {
public int mode;
public String s;
public Color fill;
public Color stroke;
public Paint bg;
public Char(String s, Color fill, Color stroke, Paint bg, int mode) {
this.s = s;
this.fill = fill;
this.stroke = stroke;
this.bg = bg;
this.mode = mode;
}
}
public static final TextFont FONT_MONOSPACED = new TextFont("Monospaced", 27.00, TextMode.CHAR_BOX_SIZE, 3.4000,
-6.7000, 1.5000, 1.0000, true);
public static final TextFont FONT_LMMONO = new TextFont("lmmono10-regular.otf", 30.00, TextMode.CHAR_BOX_SIZE,
4.0000, -8.5000, 1.5000, 1.0000, true);
public static final TextFont FONT_ZXSPECTRUM7 = new TextFont("ZXSpectrum-7.otf", 22.00, TextMode.CHAR_BOX_SIZE,
3.1000, -3.8000, 1.0000, 1.0000, true);
/**
* TTF file can be found here: http://users.teilar.gr/~g1951d/ in this ZIP file:
* http://users.teilar.gr/~g1951d/Symbola.zip
* <p>
* (Put the extracted Symbola.ttf in src/inf101/v18/gfx/fonts/)
*/
public static final TextFont FONT_SYMBOLA = new TextFont("Symbola.ttf", 26.70, TextMode.CHAR_BOX_SIZE, -0.4000,
-7.6000, 1.35000, 1.0000, true);
/**
* TTF file can be found here:
* http://www.kreativekorp.com/software/fonts/c64.shtml
*/
public static final TextFont FONT_GIANA = new TextFont("Giana.ttf", 25.00, TextMode.CHAR_BOX_SIZE, 4.6000, -5.0000,
1.0000, 1.0000, true);
/**
* TTF file can be found here:
* http://www.kreativekorp.com/software/fonts/c64.shtml
*/
public static final TextFont FONT_C64 = new TextFont("PetMe64.ttf", 31.50, TextMode.CHAR_BOX_SIZE, 0.0000, -4.000,
1.0000, 1.0000, true);
private static final Paint DEFAULT_BACKGROUND = Color.TRANSPARENT;
private static final TextMode DEFAULT_MODE = TextMode.MODE_40X22;
private static final boolean DEBUG_REDRAW = false;
public static String center(String s, int width) {
for (; s.length() < width; s = " " + s + " ")
;
return s;
}
public static String repeat(String s, int width) {
String r = s;
for (; r.length() < width; r += s)
;
return r;
}
Color DEFAULT_FILL = Color.WHITE;
Color DEFAULT_STROKE = Color.TRANSPARENT;
private TextMode textMode;
private Color fill;
private Color stroke;
private Paint background;
private Screen screen;
private List<Char[]> lineBuffer = new ArrayList<>();
private boolean autoscroll = true;
private final Canvas textPage;
private int x = 1, y = 1, savedX = 1, savedY = 1;
// private int pageWidth = LINE_WIDTHS[resMode], pageHeight =
// PAGE_HEIGHTS[resMode];
private int leftMargin = 1, topMargin = 1;
private TextFont font = FONT_SYMBOLA;
private int videoAttrs = 0;
private String csiSeq = null;
private boolean csiEnabled = true;
private int csiMode = 0;
private final double width;
private final double height;
private int dirtyX0 = Integer.MAX_VALUE;
private int dirtyX1 = Integer.MIN_VALUE;
private int dirtyY0 = Integer.MAX_VALUE;
private int dirtyY1 = Integer.MIN_VALUE;
private boolean useBuffer = true;
public Printer(double width, double height) {
this.screen = null;
this.textPage = null;
this.width = width;
this.height = height;
for (int i = 0; i < TextMode.PAGE_HEIGHT_MAX; i++) {
lineBuffer.add(new Char[TextMode.LINE_WIDTH_MAX]);
}
resetFull();
}
public Printer(Screen screen, Canvas page) {
this.screen = screen;
this.textPage = page;
this.width = page.getWidth();
this.height = page.getHeight();
for (int i = 0; i < TextMode.PAGE_HEIGHT_MAX; i++) {
lineBuffer.add(new Char[TextMode.LINE_WIDTH_MAX]);
}
resetFull();
}
public void addToCharBuffer(String string) {
string.codePoints().mapToObj((int i) -> String.valueOf(Character.toChars(i))).forEach((String s) -> {
if (csiMode != 0) {
s = addToCsiBuffer(s);
}
switch (s) {
case "\r":
moveTo(leftMargin, y);
break;
case "\n":
moveTo(leftMargin, y + 1);
break;
case "\f":
moveTo(leftMargin, topMargin);
for (Char[] line : lineBuffer)
Arrays.fill(line, null);
if(textPage != null) {
GraphicsContext context = textPage.getGraphicsContext2D();
if (background != null && background != Color.TRANSPARENT) {
context.setFill(background);
context.fillRect(0.0, 0.0, textPage.getWidth(), textPage.getHeight());
} else
context.clearRect(0.0, 0.0, textPage.getWidth(), textPage.getHeight());
}
break;
case "\b":
moveHoriz(-1);
break;
case "\t":
moveTo((x + 8) % 8, y);
break;
case "\u001b":
if (csiEnabled) {
csiSeq = s;
csiMode = 1;
}
break;
default:
if (s.length() > 0 && s.codePointAt(0) >= 0x20) {
drawChar(x, y, setChar(x, y, s));
moveHoriz(1);
}
break;
}
});
}
private String addToCsiBuffer(String s) {
if (csiMode == 1) {
switch (s) {
case "[":
csiMode = 2;
csiSeq += s;
break;
case "c":
csiMode = 0;
resetFull();
break;
default:
csiReset();
return s;
}
} else if (csiMode == 2) {
int c = s.codePointAt(0);
if (c >= 0x30 && c <= 0x3f) {
csiSeq += s;
} else if (c >= 0x20 && c <= 0x2f) {
csiMode = 3;
csiSeq += s;
} else if (c >= 0x40 && c <= 0x7e) {
csiSeq += s;
csiFinish();
} else {
csiReset();
return s;
}
} else if (csiMode == 3) {
int c = s.codePointAt(0);
if (c >= 0x20 && c <= 0x2f) {
csiSeq += s;
} else if (c >= 0x40 && c <= 0x7e) {
csiSeq += s;
csiFinish();
} else {
csiReset();
return s;
}
}
return "";
}
public void beginningOfLine() {
x = leftMargin;
}
public void beginningOfPage() {
x = leftMargin;
y = topMargin;
}
@Override
public void clear() {
print("\f");
}
public void clearAt(int x, int y) {
printAt(x, y, " ");
}
public void clearLine(int y) {
y = constrainY(y);
if (y > 0 && y <= TextMode.PAGE_HEIGHT_MAX) {
Arrays.fill(lineBuffer.get(y - 1), null);
dirty(1, y);
dirty(getLineWidth(), y);
if (!useBuffer)
redrawDirty();
}
}
public void clearRegion(int x, int y, int width, int height) {
if (x > getLineWidth() || y > getPageHeight())
return;
int x2 = Math.min(x + width - 1, getLineWidth());
int y2 = Math.min(y + height - 1, getPageHeight());
if (x2 < 1 || y2 < 1)
return;
int x1 = Math.max(1, x);
int y1 = Math.max(1, y);
// Char fillWith = new Char("*", Color.BLACK, Color.GREEN, Color.TRANSPARENT,
// 0);
for (int i = y1; i <= y2; i++) {
Arrays.fill(lineBuffer.get(i - 1), x1 - 1, x2, null);
}
dirty(x1, y1);
dirty(x2, y2);
if (!useBuffer)
redrawDirty();
}
private int constrainX(int x) {
return x; // Math.min(LINE_WIDTH_HIRES, Math.max(1, x));
}
public int constrainY(int y) {
return y; // Math.min(pageHeight, Math.max(1, y));
}
public int constrainYOrScroll(int y) {
if (autoscroll) {
if (y < 1) {
scroll(y - 1);
return 1;
} else if (y > getPageHeight()) {
scroll(y - getPageHeight());
return getPageHeight();
}
}
return y;// Math.min(pageHeight, Math.max(1, y));
}
private void csiFinish() {
ControlSequences.applyCsi(this, csiSeq);
csiReset();
}
private void csiReset() {
csiMode = 0;
csiSeq = null;
}
public void cycleMode(boolean adjustDisplayAspect) {
textMode = textMode.nextMode();
if (adjustDisplayAspect && screen != null)
screen.setAspect(textMode.getAspect());
dirty(1, 1);
dirty(getLineWidth(), getPageHeight());
if (!useBuffer)
redrawDirty();
}
private void drawChar(int x, int y, Char c) {
if (useBuffer) {
dirty(x, y);
} else if (c != null && textPage != null) {
GraphicsContext context = textPage.getGraphicsContext2D();
context.setFill(c.fill);
context.setStroke(c.stroke);
font.drawTextAt(context, (x - 1) * getCharWidth(), y * getCharHeight(), c.s,
textMode.getCharWidth() / textMode.getCharBoxSize(), c.mode, c.bg);
}
}
public void drawCharCells() {
if (screen != null) {
GraphicsContext context = screen.getBackgroundContext();
screen.clearBackground();
double w = getCharWidth();
double h = getCharHeight();
context.save();
context.setGlobalBlendMode(BlendMode.EXCLUSION);
context.setFill(Color.WHITE.deriveColor(0.0, 1.0, 1.0, 0.1));
for (int x = 0; x < getLineWidth(); x++) {
for (int y = 0; y < getPageHeight(); y++) {
if ((x + y) % 2 == 0)
context.fillRect(x * w, y * h, w, h);
}
}
context.restore();
}
}
public Color getBackground(int x, int y) {
Char c = null;
if (x > 0 && x <= TextMode.LINE_WIDTH_MAX && y > 0 && y <= TextMode.PAGE_HEIGHT_MAX) {
c = lineBuffer.get(y - 1)[x - 1];
}
Color bg = Color.TRANSPARENT;
if (c != null && c.bg instanceof Color)
bg = (Color) c.bg;
else if (background instanceof Color)
bg = (Color) background;
return bg;
}
public boolean getBold() {
return (videoAttrs & TextFont.ATTR_BRIGHT) != 0;
}
public String getChar(int x, int y) {
Char c = null;
if (x > 0 && x <= TextMode.LINE_WIDTH_MAX && y > 0 && y <= TextMode.PAGE_HEIGHT_MAX) {
c = lineBuffer.get(y - 1)[x - 1];
}
if (c != null)
return c.s;
else
return " ";
}
public double getCharHeight() {
return textMode.getCharHeight();
}
public double getCharWidth() {
return textMode.getCharWidth();
}
public Color getColor(int x, int y) {
Char c = null;
if (x > 0 && x <= TextMode.LINE_WIDTH_MAX && y > 0 && y <= TextMode.PAGE_HEIGHT_MAX) {
c = lineBuffer.get(y - 1)[x - 1];
}
if (c != null)
return c.fill;
else
return fill;
}
public TextFont getFont() {
return font;
}
public boolean getItalics() {
return (videoAttrs & TextFont.ATTR_ITALIC) != 0;
}
/**
* @return the leftMargin
*/
public int getLeftMargin() {
return leftMargin;
}
public int getLineWidth() {
return textMode.getLineWidth();
}
public int getPageHeight() {
return textMode.getPageHeight();
}
public boolean getReverseVideo() {
return (videoAttrs & TextFont.ATTR_INVERSE) != 0;
}
public TextMode getTextMode() {
return textMode;
}
/**
* @return the topMargin
*/
public int getTopMargin() {
return topMargin;
}
public int getVideoMode() {
return videoAttrs;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isFilled(int x, int y) {
return !getChar(x, y).equals(" ");
}
@Override
public void layerToBack() {
if (screen != null) {
screen.moveToBack(this);
}
}
@Override
public void layerToFront() {
if (screen != null) {
screen.moveToFront(this);
}
}
public void move(int deltaX, int deltaY) {
x = constrainX(x + deltaX);
y = constrainYOrScroll(y + deltaY);
}
public void moveHoriz(int dist) {
x = constrainX(x + dist);
}
public void moveTo(int newX, int newY) {
x = constrainX(newX);
y = constrainYOrScroll(newY);
}
public void moveVert(int dist) {
y = constrainYOrScroll(y + dist);
}
public void plot(int x, int y) {
plot(x, y, (a, b) -> a | b);
}
public void plot(int x, int y, BiFunction<Integer, Integer, Integer> op) {
int textX = (x) / 2 + 1;
int textY = (y) / 2 + 1;
int bitPos = (x + 1) % 2 + ((y + 1) % 2) * 2;
String blockChar = BlocksAndBoxes.unicodeBlocks[1 << bitPos];
// System.out.println(blockChar + ", " + bitPos + ", ("+ (x) + ", " + (y) + ")"+
// ", (" + (textX) + ", " + (textY) + ")");
String s = BlocksAndBoxes.blockComposeOrOverwrite(getChar(textX, textY), blockChar, op);
// System.out.println("Merge '" + getChar(textX, textY) + "' + '" + blockChar +
// "' = '" + s + "'");
printAt(textX, textY, s);
}
public void print(String s) {
addToCharBuffer(s);
}
public void print(String s, Color paint) {
Color tmp = fill;
fill = paint;
addToCharBuffer(s);
fill = tmp;
}
public void printAt(int atX, int atY, String s) {
moveTo(atX, atY);
print(s);
}
public void printAt(int atX, int atY, String s, Color ink) {
moveTo(atX, atY);
print(s, ink);
}
public void println() {
print("\n");
}
public void println(String s) {
print(s);
print("\n");
}
public void redrawTextPage() {
redrawTextPage(1, 1, getLineWidth(), getPageHeight());
clean();
}
private void redrawTextPage(int x0, int y0, int x1, int y1) {
/*
* System.out.printf("redrawTextPage benchmark");
* System.out.printf(" %5s %5s %7s %4s %5s %5s %5s%n", "ms", "chars",
* "ms/char", "mode", "indir", "inv", "fake"); for (int m = -1; m < 8; m++) {
* long t0 = System.currentTimeMillis(); int n = 0;
*/
if(textPage == null)
return;
GraphicsContext context = textPage.getGraphicsContext2D();
double px0 = (x0 - 1) * getCharWidth(), py0 = (y0 - 1) * getCharHeight();
double px1 = x1 * getCharWidth(), py1 = y1 * getCharHeight();
if (DEBUG_REDRAW)
System.out.printf("redrawTextPage(): Area to clear: (%2f,%2f)(%2f,%2f)%n", px0, py0, px1, py1);
if (background != null && background != Color.TRANSPARENT) {
context.setFill(background);
context.fillRect(px0, py0, px1 - px0, py1 - py0);
} else {
context.clearRect(px0, py0, px1 - px0, py1 - py0);
}
for (int tmpY = y0; tmpY <= y1; tmpY++) {
Char[] line = lineBuffer.get(tmpY - 1);
for (int tmpX = x0; tmpX <= x1; tmpX++) {
Char c = line[tmpX - 1];
if (c != null) {
context.save();
context.setFill(c.fill);
context.setStroke(c.stroke);
Paint bg = c.bg == background ? null : c.bg;
font.drawTextNoClearAt(context, (tmpX - 1) * getCharWidth(), tmpY * getCharHeight(), c.s,
textMode.getCharWidth() / textMode.getCharBoxSize(), c.mode/* m */, bg);
context.restore();
// n++;
}
}
}
/*
* long t = System.currentTimeMillis() - t0; if (m >= 0)
* System.out.printf(" %5d %5d %7.4f %4d %5b %5b %5b%n", t, n, ((double) t) /
* n, m, (m & 3) != 0, (m & 1) != 0, (m & 4) != 0); } System.out.println();
*/
}
public void resetAttrs() {
this.fill = DEFAULT_FILL;
this.stroke = DEFAULT_STROKE;
this.background = DEFAULT_BACKGROUND;
this.videoAttrs = 0;
this.csiSeq = null;
this.csiMode = 0;
}
public void resetFull() {
resetAttrs();
beginningOfPage();
this.autoscroll = true;
this.textMode = DEFAULT_MODE;
redrawTextPage();
}
public void restoreCursor() {
x = savedX;
y = savedY;
}
public void saveCursor() {
savedX = x;
savedY = y;
}
void scroll(int i) {
while (i < 0) {
scrollDown();
i++;
}
while (i > 0) {
scrollUp();
i--;
}
}
public void scrollDown() {
Char[] remove = lineBuffer.remove(lineBuffer.size() - 1);
Arrays.fill(remove, null);
lineBuffer.add(0, remove);
dirty(1, 1);
dirty(getLineWidth(), getPageHeight());
if (!useBuffer)
redrawDirty();
}
public void scrollUp() {
Char[] remove = lineBuffer.remove(0);
Arrays.fill(remove, null);
lineBuffer.add(remove);
dirty(1, 1);
dirty(getLineWidth(), getPageHeight());
if (!useBuffer)
redrawDirty();
}
public boolean setAutoScroll(boolean autoScroll) {
boolean old = autoscroll;
autoscroll = autoScroll;
return old;
}
public void setBackground(int x, int y, Paint bg) {
Char c = null;
if (x > 0 && x <= TextMode.LINE_WIDTH_MAX && y > 0 && y <= TextMode.PAGE_HEIGHT_MAX) {
c = lineBuffer.get(y - 1)[x - 1];
}
if (c != null) {
c.bg = bg;
drawChar(x, y, c);
}
}
public void setBackground(Paint bgColor) {
this.background = bgColor != null ? bgColor : DEFAULT_BACKGROUND;
}
public void setBold(boolean enabled) {
if (enabled)
videoAttrs |= TextFont.ATTR_BRIGHT;
else
videoAttrs &= ~TextFont.ATTR_BRIGHT;
}
public Char setChar(int x, int y, String s) {
if (x > 0 && x <= TextMode.LINE_WIDTH_MAX && y > 0 && y <= TextMode.PAGE_HEIGHT_MAX) {
Char c = new Char(s, fill, stroke, background, videoAttrs);
lineBuffer.get(y - 1)[x - 1] = c;
return c;
}
return null;
}
public void setColor(int x, int y, Color fill) {
Char c = null;
if (x > 0 && x <= TextMode.LINE_WIDTH_MAX && y > 0 && y <= TextMode.PAGE_HEIGHT_MAX) {
c = lineBuffer.get(y - 1)[x - 1];
}
if (c != null) {
c.fill = fill;
drawChar(x, y, c);
}
}
public void setFill(Color fill) {
this.fill = fill != null ? fill : DEFAULT_FILL;
}
public void setFont(TextFont font) {
this.font = font;
}
public void setInk(Color ink) {
fill = ink != null ? ink : DEFAULT_FILL;
stroke = ink != null ? ink : DEFAULT_STROKE;
}
public void setItalics(boolean enabled) {
if (enabled)
videoAttrs |= TextFont.ATTR_ITALIC;
else
videoAttrs &= ~TextFont.ATTR_ITALIC;
}
/**
*/
public void setLeftMargin() {
this.leftMargin = x;
}
/**
* @param leftMargin
* the leftMargin to set
*/
public void setLeftMargin(int leftMargin) {
this.leftMargin = constrainX(leftMargin);
}
public void setReverseVideo(boolean enabled) {
if (enabled)
videoAttrs |= TextFont.ATTR_INVERSE;
else
videoAttrs &= ~TextFont.ATTR_INVERSE;
}
public void setStroke(Color stroke) {
this.stroke = stroke != null ? stroke : DEFAULT_STROKE;
}
public void setTextMode(TextMode mode) {
setTextMode(mode, false);
}
public void setTextMode(TextMode mode, boolean adjustDisplayAspect) {
if (mode == null)
throw new IllegalArgumentException();
textMode = mode;
if (adjustDisplayAspect && screen != null)
screen.setAspect(textMode.getAspect());
dirty(1, 1);
dirty(getLineWidth(), getPageHeight());
if (!useBuffer)
redrawDirty();
}
public void setTopMargin() {
this.topMargin = y;
}
/**
* @param topMargin
* the topMargin to set
*/
public void setTopMargin(int topMargin) {
this.topMargin = constrainY(topMargin);
}
public void setVideoAttrDisabled(int attr) {
videoAttrs &= ~attr;
}
public void setVideoAttrEnabled(int attr) {
videoAttrs |= attr;
}
public void setVideoAttrs(int attr) {
videoAttrs = attr;
}
public void unplot(int x, int y) {
plot(x, y, (a, b) -> a & ~b);
}
@Override
public double getWidth() {
return width;
}
@Override
public double getHeight() {
return height;
}
private boolean isDirty() {
return dirtyX0 <= dirtyX1 || dirtyY0 <= dirtyY1;
}
/**
* Expand the dirty region (area that should be redrawn) to include the given
* position
*
* @param x
* @param y
*/
private void dirty(int x, int y) {
dirtyX0 = Math.max(Math.min(x, dirtyX0), 1);
dirtyX1 = Math.min(Math.max(x, dirtyX1), getLineWidth());
dirtyY0 = Math.max(Math.min(y, dirtyY0), 1);
dirtyY1 = Math.min(Math.max(y, dirtyY1), getPageHeight());
}
/**
* Redraw the part of the page that has changed since last redraw.
*/
public void redrawDirty() {
if (isDirty()) {
if (DEBUG_REDRAW)
System.out.printf("redrawDirty(): Dirty region is (%d,%d)(%d,%d)%n", dirtyX0, dirtyY0, dirtyX1,
dirtyY1);
redrawTextPage(dirtyX0, dirtyY0, dirtyX1, dirtyY1);
clean();
}
}
/**
* Mark the entire page as clean
*/
private void clean() {
dirtyX0 = Integer.MAX_VALUE;
dirtyX1 = Integer.MIN_VALUE;
dirtyY0 = Integer.MAX_VALUE;
dirtyY1 = Integer.MIN_VALUE;
}
/**
* With buffered printing, nothing is actually drawn until
* {@link #redrawDirty()} or {@link #redrawTextPage()} is called.
*
* @param buffering
* Whether to use buffering
*/
public void setBuffering(boolean buffering) {
useBuffer = buffering;
}
/**
* @return True if buffering is enabled
* @see #setBuffering(boolean)
*/
public boolean getBuffering() {
return useBuffer;
}
}

View File

@@ -0,0 +1,995 @@
package inf101.v18.gfx.textmode;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javafx.geometry.Point2D;
import javafx.scene.SnapshotParameters;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.text.Font;
import javafx.scene.transform.Affine;
import javafx.scene.transform.Transform;
/**
* TextFont for grid-based text / character graphics
* <p>
* TextFonts are used for drawing text and character graphics. Each character is
* assumed to be uniform in size, fitting within a square with sides of length
* {@link #getSquareSize()}. The given font file should contain a monospaced
* font of a type suitable for JavaFX, such as OpenType or TrueType.
*
* <p>
* Additional horizontal and vertical positioning and scaling can be used to
* make the font fit with the square-shaped concept.
*
* <p>
* See {@link #setGraphicsContext(GraphicsContext)} for setting up the graphics
* context for writing with the font, or
* {@link #setGraphicsContext(GraphicsContext, double)} for extra on-the-fly
* horizontal scaling, e.g. to make half-width letters ("hires" mode).
*
*/
public class TextFont {
public static final int ATTR_INVERSE = 0x01;
public static final int ATTR_ITALIC = 0x02;
public static final int ATTR_BOLD = 0x04;
public static final int ATTR_OUTLINE = 0x08;
public static final int ATTR_UNDERLINE = 0x10;
public static final int ATTR_OVERLINE = 0x20;
public static final int ATTR_LINE_THROUGH = 0x40;
public static final int ATTR_OVERSTRIKE = 0x80;
public static final int ATTR_CLIP = 0x80;
public static final int ATTR_NO_FAKE_CHARS = 0x100;
public static final int ATTR_BLINK = 0x200; // NOT IMPLEMENTED
public static final int ATTR_FAINT = 0x400; // NOT IMPLEMENTED
public static final int ATTR_BRIGHT = 0x800;
private static final String[] searchPath = { "", "../", "../fonts/" };
private static final Map<String, String> loadedFonts = new HashMap<>();
private static final double thin = 2.0, thick = 4.0;
private static final String[] boxDrawingShapes = { // lines
"--..", "**..", "..--", "..**",
// dashed lines
"3--..", "3**..", "3..--", "3..**", "4--..", "4**..", "4..--", "4..**",
// corners
".-.-", ".*.-", ".-.*", ".*.*", "-..-", "*..-", "-..*", "*..*", ".--.", ".*-.", ".-*.", ".**.", "-.-.",
"*.-.", "-.*.", "*.*.",
// |-
".---", ".*--", ".-*- ", ".--* ", ".-**", ".**-", ".*-*", ".***", "-.--", "*.--", "-.*-", "-.-*", "-.**",
"*.*-", "*.-*", "*.**",
// T
"--.-", "*-.-", "-*.-", "**.-", "--.*", "*-.*", "-*.*", "**.*", "---.", "*--. ", "-*-.", "**-.", "--*.",
"*-*.", "-**.", "***.",
// +
"----", "*---", "-*--", "**--", "--*-", "---*", "--**", "*-*-", "-**-", "*--*", "-*-*", "***-", "**-*",
"*-**", "-***", "****",
// dashes
"2--..", "2**..", "2..--", "2..**",
// double lines
"==..", "..==", ".=.-", ".-.=", ".N.N", "=..-", "-..=", "M..M", ".=-.", ".-=.", ".MM.", "=.-.", "-.=.",
"N.N.", ".=--", ".s==", ".zMN", "=.--", "s.==", "z.NM", "==.s", "--.=", "MN.z", "==s.", "--=.", "NMz.",
"==--", "--==", "zzzz",
// round corners
"0.-.-", "0-..-", "0-.-.", "0.--.",
// diagonals
"////", "\\\\\\\\", "//\\\\\\",
// short lines
"-...", "..-.", ".-..", "...-", "*...", "..*.", ".*..", "...*",
// thin/thick lines
"-*..", "..-*", "*-..", "..*-" };
public static void drawMasked(GraphicsContext ctx, Image src, Image mask, double x, double y, boolean invert,
boolean blend) {
int w = (int) src.getWidth();
int h = (int) src.getHeight();
PixelReader pixelSrc = src.getPixelReader();
PixelReader pixelMask = mask.getPixelReader();
PixelWriter pixelWriter = ctx.getPixelWriter();
Affine transform = ctx.getTransform();
Point2D point = transform.transform(x, y);
int dx = (int) point.getX(), dy = (int) point.getY();
for (int px = 0; px < w; px++) {
for (int py = 0; py < h; py++) {
int a = pixelMask.getArgb(px, py) >>> 24;
int rgb = pixelSrc.getArgb(px, py);
if (invert)
a = ~a & 0xff;
if (blend)
a = ((rgb >>> 24) * a) >>> 8;
pixelWriter.setArgb(px + dx, py + dy, (a << 24) | rgb);
}
}
}
public static void fillInverse(GraphicsContext ctx, Image img, double x, double y) {
int w = (int) img.getWidth();
int h = (int) img.getHeight();
PixelReader pixelReader = img.getPixelReader();
PixelWriter pixelWriter = ctx.getPixelWriter();
Affine transform = ctx.getTransform();
Point2D point = transform.transform(x, y);
int dx = (int) point.getX(), dy = (int) point.getY();
Color c = ctx.getFill() instanceof Color ? (Color) ctx.getFill() : Color.BLACK;
int rgb = ((int) (c.getRed() * 255)) << 16 | ((int) (c.getGreen() * 255)) << 8 | ((int) (c.getBlue() * 255));
for (int px = 0; px < w; px++) {
for (int py = 0; py < h; py++) {
int a = (~pixelReader.getArgb(px, py) & 0xff000000);
// if(a != 0)
pixelWriter.setArgb(px + dx, py + dy, a | rgb);
}
}
}
/**
* Load a font.
*
* Will first try to use the provided string as a file name, and load the font
* from a font file (should be in a format supported by JavaFX). If loading from
* file fails, we assume we have been given the name of a font which is passed
* directly to JavaFX for loading. A fallback font is used if this fails.
*
* When looking for files, his method will search for the file in a search path
* starting with the folder containing the {@link TextFont} class file (using
* Java's standard {@link Class#getResourceAsStream(String)} system). The search
* path also includes ".." (parent directory) and "../fonts".
*
* The loaded font will be cached, so that additional calls with the same file
* name will not cause the file to be loaded again.
*
* If the font cannot be loaded, a default font will be substituted. You may
* check which font you got using {@link Font#getName()} or
* {@link Font#getFamily()}.
*
* @param name
* Font name, or relative path to the file
* @param size
* Desired point size of the font
* @return A JavaFX font
*/
public static final Font findFont(String name, double size) {
return findFont(name, size, TextFont.class);
}
/**
* Load a font.
*
* Will first try to use the provided string as a file name, and load the font
* from a font file (should be in a format supported by JavaFX). If loading from
* file fails, we assume we have been given the name of a font which is passed
* directly to JavaFX for loading. A fallback font is used if this fails.
*
* When looking for files, this method will search for the file in a search path
* starting with the folder containing the provided Java class (using Java's
* standard {@link Class#getResourceAsStream(String)} system). The search path
* also includes ".." (parent directory) and "../fonts".
*
* The loaded font will be cached, so that additional calls with the same file
* name will not cause the file to be loaded again.
*
* If the font cannot be loaded, a default font will be substituted. You may
* check which font you got using {@link Font#getName()} or
* {@link Font#getFamily()}.
*
* @param name
* Name of a font, or relative path to the font file
* @param size
* Desired point size of the font
* @param clazz
* A class for finding files relative to
* @return A JavaFX font
*/
public static final Font findFont(String name, double size, Class<?> clazz) {
if (name == null || size < 0)
throw new IllegalArgumentException();
if (loadedFonts.containsKey(name))
return Font.font(loadedFonts.get(name), size);
for (String path : searchPath) {
try (InputStream stream = clazz.getResourceAsStream(path + name)) {
Font font = Font.loadFont(stream, size);
if (font != null) {
loadedFonts.put(name, font.getName());
// System.err.println("Found: " + font.getName());
return font;
}
} catch (FileNotFoundException e) {
// we'll just try the next alternative in the search path
} catch (IOException e) {
e.printStackTrace();
}
}
Font font = Font.font(name, size);
if (font == null)
font = Font.font(size);
if (font == null)
throw new RuntimeException("Even the default font seems to be unavailable this shouldn't happen! :(");
if (font.getName().equals(Font.getDefault().getName())) {
System.err.println("TextFont: Default font '" + font.getName() + "' substituted for '" + name + "'");
}
// System.err.println("Found: " + name + "=" + font.getName());
loadedFonts.put(name, name);
return font;
}
private Canvas tmpCanvas;
private final WritableImage img;
/**
* The JavaFX font
*/
private Font font;
/** Font size */
private final double size;
/**
* Horizontal positioning of letters.
*
* Each letter should be approximately centered within its available
* square-shaped space.
*/
private final double xTranslate;
/**
* Vertical positioning of letters.
*
* Each letter should be positioned on the baseline so that ascenders and
* descenders fall within its available square-shaped space.
*/
private final double yTranslate;
/**
* Horizontal scaling factor (1.0 means no scaling)
*
* Most fonts are relatively tall and narrow, and need horizontal scaling to fit
* a square shape.
*/
private final double xScale;
/**
* Vertical scaling factor (1.0 means no scaling)
*/
private final double yScale;
/**
* Width and height of the square-shaped space each letter should fit within
*/
private double squareSize;
private String fileName;
SnapshotParameters snapshotParameters = new SnapshotParameters();
{
snapshotParameters.setFill(Color.TRANSPARENT);
}
/**
* Create a new TextFont.
*
* <p>
* TextFonts are used for drawing text and character graphics. Each character is
* assumed to be uniform in size, fitting within a square with sides of length
* {@link #getSquareSize()}. The given font file should contain a monospaced
* font of a type suitable for JavaFX, such as OpenType or TrueType.
*
* <p>
* Additional horizontal and vertical positioning and scaling can be used to
* make the font fit with the square-shaped concept.
*
* <p>
* See {@link #setGraphicsContext(GraphicsContext)} for setting up the graphics
* context for writing with the font, or
* {@link #setGraphicsContext(GraphicsContext, double)} for extra on-the-fly
* horizontal scaling, e.g. to make half-width letters ("hires" mode).
*
*
* @param font
* Name of the font file. Will search for the file in the same folder
* as the TextFont class, as well as ".." and "../fonts".
* @param squareSize
* The width and height of a square defining the bounds of letters
* @param xTranslate
* Horizontal positioning of letters
* @param yTranslate
* Vertical positioning of letters
* @param xScale
* Horizontal scaling factor
* @param yScale
* Vertical scaling factor
*/
public TextFont(Font font, double squareSize, double xTranslate, double yTranslate, double xScale, double yScale) {
super();
this.fileName = font.getName();
this.font = font;
this.size = font.getSize();
this.squareSize = squareSize;
this.xTranslate = xTranslate;
this.yTranslate = yTranslate;
this.xScale = xScale;
this.yScale = yScale;
this.img = new WritableImage((int) squareSize, (int) squareSize);
}
/**
* Create a new TextFont.
*
* <p>
* TextFonts are used for drawing text and character graphics. Each character is
* assumed to be uniform in size, fitting within a square with sides of length
* {@link #getSquareSize()}. The given font file should contain a monospaced
* font of a type suitable for JavaFX, such as OpenType or TrueType.
*
* <p>
* Additional horizontal and vertical positioning and scaling can be used to
* make the font fit with the square-shaped concept.
*
* <p>
* See {@link #setGraphicsContext(GraphicsContext)} for setting up the graphics
* context for writing with the font, or
* {@link #setGraphicsContext(GraphicsContext, double)} for extra on-the-fly
* horizontal scaling, e.g. to make half-width letters ("hires" mode).
*
*
* @param size
* Point size of the font.
* @param squareSize
* The width and height of a square defining the bounds of letters
* @param xTranslate
* Horizontal positioning of letters
* @param yTranslate
* Vertical positioning of letters
* @param xScale
* Horizontal scaling factor
* @param yScale
* Vertical scaling factor
*/
public TextFont(String fileName, double size, double squareSize, double xTranslate, double yTranslate,
double xScale, double yScale) {
super();
this.fileName = fileName;
this.font = findFont(fileName, size);
this.size = size;
this.squareSize = squareSize;
this.xTranslate = xTranslate;
this.yTranslate = yTranslate;
this.xScale = xScale;
this.yScale = yScale;
this.img = new WritableImage((int) squareSize, (int) squareSize);
}
/**
* Create a new TextFont.
*
* <p>
* TextFonts are used for drawing text and character graphics. Each character is
* assumed to be uniform in size, fitting within a square with sides of length
* {@link #getSquareSize()}. The given font file should contain a monospaced
* font of a type suitable for JavaFX, such as OpenType or TrueType.
*
* <p>
* Additional horizontal and vertical positioning and scaling can be used to
* make the font fit with the square-shaped concept.
*
* <p>
* See {@link #setGraphicsContext(GraphicsContext)} for setting up the graphics
* context for writing with the font, or
* {@link #setGraphicsContext(GraphicsContext, double)} for extra on-the-fly
* horizontal scaling, e.g. to make half-width letters ("hires" mode).
*
*
* @param size
* Point size of the font.
* @param squareSize
* The width and height of a square defining the bounds of letters
* @param xTranslate
* Horizontal positioning of letters
* @param yTranslate
* Vertical positioning of letters
* @param xScale
* Horizontal scaling factor
* @param yScale
* Vertical scaling factor
* @param deferLoading
* True if the font file shouldn't be loaded before the font is
* actually used
*/
public TextFont(String fileName, double size, double squareSize, double xTranslate, double yTranslate,
double xScale, double yScale, boolean deferLoading) {
super();
this.fileName = fileName;
this.font = deferLoading ? null : findFont(fileName, size);
this.size = size;
this.squareSize = squareSize;
this.xTranslate = xTranslate;
this.yTranslate = yTranslate;
this.xScale = xScale;
this.yScale = yScale;
this.img = new WritableImage((int) squareSize, (int) squareSize);
}
/**
* Create a copy of this font, with the given adjustments to the translation and
* scaling.
*
* @param deltaXTranslate
* @param deltaYTranslate
* @param deltaXScale
* @param deltaYScale
* @return
*/
public TextFont adjust(double size, double deltaXTranslate, double deltaYTranslate, double deltaXScale,
double deltaYScale) {
if (size == 0.0) {
return new TextFont(fileName, this.size, squareSize, xTranslate + deltaXTranslate,
yTranslate + deltaYTranslate, xScale + deltaXScale, yScale + deltaYScale);
} else {
return new TextFont(fileName, this.size + size, squareSize, xTranslate + deltaXTranslate,
yTranslate + deltaYTranslate, xScale + deltaXScale, yScale + deltaYScale);
}
}
/**
* Draw the given text at position (0,0).
*
* The <code>ctx</code> should normally be translated to the appropriate text
* position before calling this method.
*
* Text will be clipped so each character fits its expected square-shaped area,
* and the area will be cleared to transparency before drwaing.
*
* The graphics context's current path will be overwritten.
*
* @param ctx
* a grapics context
* @param text
* string to be printed
*/
public void drawText(GraphicsContext ctx, String text) {
textAt(ctx, 0.0, 0.0, text, 1.0, true, true, ctx.getFill(), null, 0, null);
}
/**
* Draw the given text at position (0,0), with horizontal scaling.
*
* The <code>ctx</code> should normally be translated to the appropriate text
* position before calling this method.
*
* Text will be clipped so each character fits its expected square-shaped area,
* and the area will be cleared to transparency before drwaing.
*
* The graphics context's current path will be overwritten.
*
* @param ctx
* a grapics context
* @param text
* string to be printed
* @param xScaleFactor
* a horizontal scaling factor
*/
public void drawText(GraphicsContext ctx, String text, double xScaleFactor) {
textAt(ctx, 0.0, 0.0, text, xScaleFactor, true, false, ctx.getFill(), null, 0, null);
}
/**
* Draw the given text at position (x,y).
*
* Text will be clipped so each character fits its expected square-shaped area,
* and the area will be cleared to transparency before drwaing.
*
* The graphics context's current path will be overwritten.
*
* @param ctx
* a grapics context
* @param x
* X-position of the lower left corner of the text
* @param y
* Y-position of the lower left corner of the text
* @param text
* string to be printed
*/
public void drawTextAt(GraphicsContext ctx, double x, double y, String text) {
textAt(ctx, x, y, text, 1.0, true, false, ctx.getFill(), null, 0, null);
}
/**
* Draw the given text at position (x, y), with horizontal scaling.
*
* The area will be cleared to transparency before drawing.
*
* The graphics context's current path will be overwritten.
*
* @param ctx
* a graphics context
* @param x
* X-position of the lower left corner of the text
* @param y
* Y-position of the lower left corner of the text
* @param text
* string to be printed
* @param xScaleFactor
* a horizontal scaling factor
*/
public void drawTextAt(GraphicsContext ctx, double x, double y, String text, double xScaleFactor, int mode,
Paint bg) {
textAt(ctx, x, y, text, xScaleFactor, true, false, ctx.getFill(), null, mode, bg);
}
/**
* Draw the given text at position (x, y), with horizontal scaling.
*
* The area will not be cleared to transparency before drawing.
*
* The graphics context's current path will be overwritten.
*
* @param ctx
* a graphics context
* @param x
* X-position of the lower left corner of the text
* @param y
* Y-position of the lower left corner of the text
* @param text
* string to be printed
* @param xScaleFactor
* a horizontal scaling factor
*/
public void drawTextNoClearAt(GraphicsContext ctx, double x, double y, String text, double xScaleFactor, int mode,
Paint bg) {
textAt(ctx, x, y, text, xScaleFactor, false, false, ctx.getFill(), null, mode, bg);
}
private void fakeBlockElement(GraphicsContext ctx, String text, double xScaleFactor) {
text.codePoints().forEach((int c) -> {
// System.out.printf("%s %x%n", text, c);
if (c >= 0x2596 && c <= 0x259f) { // quadrants
int bits = BlocksAndBoxes.unicodeBlocksString.indexOf(c);
if ((bits & 1) > 0) { // lower right
ctx.fillRect(squareSize * xScaleFactor / 2, -squareSize / 2, (squareSize / 2) * xScaleFactor,
squareSize / 2);
}
if ((bits & 2) > 0) { // lower left
ctx.fillRect(0, -squareSize / 2, (squareSize / 2) * xScaleFactor, squareSize / 2);
}
if ((bits & 4) > 0) { // upper right
ctx.fillRect(squareSize * xScaleFactor / 2, -squareSize, (squareSize / 2) * xScaleFactor,
squareSize / 2);
}
if ((bits & 8) > 0) { // upper left
ctx.fillRect(0, -squareSize, (squareSize / 2) * xScaleFactor, squareSize / 2);
}
} else if (c == 0x2580) { // upper half
ctx.fillRect(0, -squareSize, (squareSize) * xScaleFactor, squareSize / 2);
} else if (c > 0x2580 && c <= 0x2588) { // x/8 block
int height = c - 0x2580;
ctx.fillRect(0, -(height * squareSize) / 8, (squareSize) * xScaleFactor, (height * squareSize) / 8);
} else if (c >= 0x2589 && c <= 0x258f) { // x/8 block
int width = 8 - (c - 0x2588);
ctx.fillRect(0, -squareSize, ((width * squareSize) / 8) * xScaleFactor, squareSize);
} else if (c == 0x2590) { // right half
ctx.fillRect(squareSize * xScaleFactor / 2, -squareSize, (squareSize / 2) * xScaleFactor, squareSize);
} else if (c == 0x2591) { // light shade
ctx.save();
ctx.setGlobalAlpha(0.25);
ctx.fillRect(0, -squareSize, (squareSize) * xScaleFactor, squareSize);
ctx.restore();
} else if (c == 0x2592) { // medium shade
ctx.save();
ctx.setGlobalAlpha(0.5);
ctx.fillRect(0, -squareSize, (squareSize) * xScaleFactor, squareSize);
ctx.restore();
} else if (c == 0x2593) { // dark shade
ctx.save();
ctx.setGlobalAlpha(0.75);
ctx.fillRect(0, -squareSize, (squareSize) * xScaleFactor, squareSize);
ctx.restore();
} else if (c == 0x2594) { // upper eighth
ctx.fillRect(0, -squareSize, (squareSize) * xScaleFactor, squareSize / 8);
} else if (c == 0x2595) { // right eighth
ctx.fillRect(((7 * squareSize) / 8) * xScaleFactor, -squareSize, (squareSize / 8) * xScaleFactor,
squareSize);
} else if (c == 0x2571) {
ctx.save();
ctx.setLineWidth(2.0);
ctx.strokeLine(0, 0, squareSize * xScaleFactor, -squareSize);
ctx.restore();
} else if (c == 0x2572) {
ctx.save();
ctx.setLineWidth(2.0);
ctx.strokeLine(0, -squareSize, squareSize * xScaleFactor, 0);
ctx.restore();
} else if (c == 0x2573) {
ctx.save();
ctx.setLineWidth(2.0);
ctx.strokeLine(0, 0, squareSize * xScaleFactor, -squareSize);
ctx.strokeLine(0, -squareSize, squareSize * xScaleFactor, 0);
ctx.restore();
} else if (c >= 0x2500 && c <= 0x257f) {
ctx.save();
ctx.setLineCap(StrokeLineCap.BUTT);
String spec = boxDrawingShapes[c - 0x2500];
int i = 0;
double extraThickness = 0.0;
if (Character.isDigit(spec.charAt(i))) {
extraThickness = setContextFromChar(ctx, spec.charAt(i++));
}
char s;
double hThickness = Math.max(setContextFromChar(ctx, spec.charAt(i)),
setContextFromChar(ctx, spec.charAt(i + 1))) + extraThickness;
double vThickness = Math.max(setContextFromChar(ctx, spec.charAt(i + 2)),
setContextFromChar(ctx, spec.charAt(i + 3))) + extraThickness;
if (c >= 0x2550 || spec.charAt(i) != spec.charAt(i + 1)) {
s = spec.charAt(i++);
setContextFromChar(ctx, s);
strokeHalfLine(ctx, xScaleFactor, -1, 0, s, vThickness);
s = spec.charAt(i++);
setContextFromChar(ctx, s);
strokeHalfLine(ctx, xScaleFactor, 1, 0, s, vThickness);
} else {
s = spec.charAt(i++);
s = spec.charAt(i++);
setContextFromChar(ctx, s);
strokeFullLine(ctx, xScaleFactor, 1, 0, s);
}
if (c >= 0x2550 || spec.charAt(i) != spec.charAt(i + 1)) {
s = spec.charAt(i++);
setContextFromChar(ctx, s);
strokeHalfLine(ctx, xScaleFactor, 0, -1, s, hThickness);
s = spec.charAt(i++);
setContextFromChar(ctx, s);
strokeHalfLine(ctx, xScaleFactor, 0, 1, s, hThickness);
} else {
s = spec.charAt(i++);
s = spec.charAt(i++);
setContextFromChar(ctx, s);
strokeFullLine(ctx, xScaleFactor, 0, 1, s);
}
ctx.restore();
}
});
}
/**
* @return the font
*/
public Font getFont() {
if (font == null)
font = findFont(fileName, size);
return font;
}
/**
* @return the size
*/
public double getSize() {
return size;
}
/**
* Width and height of the square-shaped space each letter should fit within
*
* @return the squareSize
*/
public double getSquareSize() {
return squareSize;
}
private Canvas getTmpCanvas() {
if (tmpCanvas == null) {
tmpCanvas = new Canvas(squareSize, squareSize);
} else {
tmpCanvas.getGraphicsContext2D().clearRect(0, 0, squareSize, squareSize);
}
return tmpCanvas;
}
/**
* Horizontal scaling factor (1.0 means no scaling)
*
* Most fonts are relatively tall and narrow, and need horizontal scaling to fit
* a square shape.
*
* @return the xScale
*/
public double getxScale() {
return xScale;
}
/**
* Horizontal positioning of letters.
*
* Each letter should be approximately centered within its available
* square-shaped space.
*
* @return the xTranslate
*/
public double getxTranslate() {
return xTranslate;
}
/**
* Vertical scaling factor (1.0 means no scaling)
*
* @return the yScale
*/
public double getyScale() {
return yScale;
}
/**
* /** Vertical positioning of letters.
*
* Each letter should be positioned on the baseline so that ascenders and
* descenders fall within its available square-shaped space.
*
* @return the yTranslate
*/
public double getyTranslate() {
return yTranslate;
}
private double setContextFromChar(GraphicsContext ctx, char c) {
switch (c) {
case '0':
return -2 * thin;
case '2':
ctx.setLineDashes(14.75, 2.5);
break;
case '3':
ctx.setLineDashes(9, 2.5);
break;
case '4':
ctx.setLineDashes(6.125, 2.5);
break;
case '.':
return 0.0;
case '-':
case 's':
ctx.setLineWidth(thin);
return thin;
case '*':
ctx.setLineWidth(thick);
return thick;
case '=':
case 'N':
case 'M':
case 'z':
ctx.setLineWidth(thin);
return thin;
}
return 0.0;
}
/**
* Set up a graphics context for drawing with this font.
*
* Caller should call {@link GraphicsContext#save()} first, and then
* {@link GraphicsContext#restore()} afterwards, to clean up adjustments to the
* transformation matrix (i.e., translation, scaling).
*
* The GraphicsContext should be translated to the coordinates where the text
* should appear <em>before</em> calling this method, since this method will
* modify the coordinate system.
*
* @param ctx
* A GraphicsContext
*/
public void setGraphicsContext(GraphicsContext ctx) {
ctx.setFont(getFont());
ctx.translate(xTranslate, yTranslate);
ctx.scale(xScale, yScale);
}
/**
* Set up a graphics context for drawing with this font.
*
* Caller should call {@link GraphicsContext#save()} first, and then
* {@link GraphicsContext#restore()} afterwards, to clean up adjustments to the
* transformation matrix (i.e., translation, scaling).
*
* The GraphicsContext should be translated to the coordinates where the text
* should appear <em>before</em> calling this method, since this method will
* modify the coordinate system.
*
* @param ctx
* A GraphicsContext
* @param xScaleFactor
* Additional horizontal scaling, normally 0.5 (for half-width
* characters)
*/
public void setGraphicsContext(GraphicsContext ctx, double xScaleFactor) {
ctx.setFont(getFont());
ctx.translate(xTranslate * xScaleFactor, yTranslate);
ctx.scale(xScale * xScaleFactor, yScale);
}
private void strokeFullLine(GraphicsContext ctx, double xScaleFactor, double xDir, double yDir, char c) {
double x = squareSize * xScaleFactor / 2, y = -squareSize / 2;
if (c != '.') {
// System.out.printf("(%4.1f %4.1f %4.1f %4.1f) w=%1.4f%n", x * yDir, y * xDir,
// x * yDir + xDir * squareSize,
// y * xDir + yDir * squareSize, ctx.getLineWidth());
if (c == '=') {
ctx.setLineWidth(2.0);
ctx.strokeLine((x - 2) * yDir, (y - 2) * xDir, (x - 2) * yDir + xDir * squareSize * xScaleFactor,
(y - 2) * xDir + yDir * -squareSize);
ctx.strokeLine((x + 2) * yDir, (y + 2) * xDir, (x + 2) * yDir + xDir * squareSize * xScaleFactor,
(y + 2) * xDir + yDir * -squareSize);
} else {
ctx.strokeLine(x * yDir, y * xDir, x * yDir + xDir * squareSize * xScaleFactor,
y * xDir + yDir * -squareSize);
}
}
}
private void strokeHalfLine(GraphicsContext ctx, double xScaleFactor, double xDir, double yDir, char c,
double otherWidth) {
if (c != '.') {
double factor = 1.0, dblFactor = 0.0;
if (c == 's' || c == 'z')
factor = -1;
if (c == 'N')
dblFactor = -2;
if (c == 'M')
dblFactor = 2;
double x = squareSize * xScaleFactor / 2, y = -squareSize / 2;
x -= xDir * factor * (otherWidth / 2);
y -= yDir * factor * (otherWidth / 2);
if (c == '=' || c == 'z' || c == 'N' || c == 'M') {
ctx.setLineWidth(2.0);
double x0 = x - 2 * yDir;
double y0 = y - 2 * xDir;
x0 += dblFactor * xDir * (otherWidth / 2);
y0 += dblFactor * yDir * (otherWidth / 2);
ctx.strokeLine(x0, y0, x0 + xDir * squareSize * xScaleFactor, y0 + yDir * squareSize);
double x1 = x + 2 * yDir;
double y1 = y + 2 * xDir;
x1 -= dblFactor * xDir * (otherWidth / 2);
y1 -= dblFactor * yDir * (otherWidth / 2);
ctx.strokeLine(x1, y1, x1 + xDir * squareSize * xScaleFactor, y1 + yDir * squareSize);
} else {
ctx.strokeLine(x, y, x + xDir * squareSize * xScaleFactor, y + yDir * squareSize);
}
}
}
/**
* Draw text at the given position.
*
* For most cases, the simpler {@link #drawText(GraphicsContext, String)} or
* {@link #drawText(GraphicsContext, String, double)} will be easier to use.
*
* If <code>clip</code> is true, the graphics context's current path will be
* overwritten.
*
* @param ctx
* A GraphicsContext
* @param x
* X-position of the lower left corner of the text
* @param y
* Y-position of the lower left corner of the text
* @param text
* The text to be printed
* @param xScaleFactor
* Horizontal scaling factor, normally 1.0 (full width) or 0.5 (half
* width)
* @param clear
* True if the area should be cleared (to transparency) before
* drawing; normally true.
* @param clip
* True if the text drawing should be clipped to fit the expected
* printing area; normally true.
* @param fill
* True if the letter shapes should be filled; normally true.
* @param stroke
* True if the letter shapes should be stroked (outlined); normally
* false.
*/
public void textAt(GraphicsContext ctx, double x, double y, String text, double xScaleFactor, boolean clear,
boolean clip, Paint fill, Paint stroke, int mode, Paint bg) {
if ((mode & ATTR_BRIGHT) != 0) {
fill = fill instanceof Color ? ((Color) fill).deriveColor(0.0, 1.0, 3.0, 1.0) : fill;
stroke = stroke instanceof Color ? ((Color) stroke).deriveColor(0.0, 1.0, 3.0, 1.0) : stroke;
}
if ((mode & ATTR_FAINT) != 0) {
fill = fill instanceof Color ? ((Color) fill).deriveColor(0.0, 1.0, 1.0, .5) : fill;
stroke = stroke instanceof Color ? ((Color) stroke).deriveColor(0.0, 1.0, 1.0, .5) : stroke;
}
GraphicsContext target = ctx;
int width = text.codePointCount(0, text.length());
ctx.save(); // save 1
ctx.setFill(fill);
ctx.setStroke(stroke);
ctx.translate(x, y);
if (clear && (mode & ATTR_INVERSE) == 0 && (mode & ATTR_OVERSTRIKE) == 0) {
ctx.clearRect(0 + 0.5, -squareSize + 0.5, squareSize * width * xScaleFactor - 1, squareSize - 1);
}
if (bg != null && bg != Color.TRANSPARENT) {
ctx.save(); // save 2
ctx.setFill(bg);
ctx.fillRect(0, -squareSize, squareSize * width * xScaleFactor, squareSize);
ctx.restore(); // restore 2
}
boolean drawIndirect = clip || (mode & (ATTR_INVERSE | ATTR_CLIP)) != 0;
Canvas tmpCanvas = getTmpCanvas();
if (drawIndirect) {
target = tmpCanvas.getGraphicsContext2D();
target.save(); // save 2 if drawIndirect
target.translate(0, squareSize);
target.setFill((mode & ATTR_INVERSE) != 0 ? Color.BLACK : fill);
target.setStroke((mode & ATTR_INVERSE) != 0 ? Color.BLACK : stroke);
}
if (text.length() > 0 && text.charAt(0) >= 0x2500 && text.charAt(0) <= 0x259f
&& (mode & ATTR_NO_FAKE_CHARS) == 0) {
target.save(); // save 3
target.setStroke(target.getFill());
fakeBlockElement(target, text, xScaleFactor);
target.restore(); // restore 3
} else {
target.save(); // save 3
if ((mode & ATTR_ITALIC) != 0) {
target.translate(-0.2, 0);
target.transform(new Affine(Transform.shear(-0.2, 0)));
}
setGraphicsContext(target, xScaleFactor);
if (fill != null)
target.fillText(text, 0.0, 0.0);
if ((mode & ATTR_BOLD) != 0) {
// System.err.println("stroke2");
target.save(); // save 4
target.setLineWidth(thin);
target.setStroke(target.getFill());
target.strokeText(text, 0.0, 0.0);
target.restore(); // restore 4
}
if (stroke != null || (mode & ATTR_OUTLINE) != 0) {
// System.err.println("stroke2");
target.setLineWidth(((mode & ATTR_BOLD) != 0) ? thin : thin / 2);
target.strokeText(text, 0.0, 0.0);
}
target.restore(); // restore 3
}
if ((mode & ATTR_UNDERLINE) != 0) {
target.fillRect(0, yTranslate - 2, width * squareSize * xScaleFactor, thin);
}
if ((mode & ATTR_OVERLINE) != 0) {
target.fillRect(0, -squareSize + 2, width * squareSize * xScaleFactor, thin);
}
if ((mode & ATTR_LINE_THROUGH) != 0) {
target.fillRect(0, -squareSize / 2 + 2, width * squareSize * xScaleFactor, thin);
}
if (drawIndirect) {
target.restore(); // restore 2 if drawIndirect
tmpCanvas.snapshot(snapshotParameters, img);
if ((mode & ATTR_INVERSE) != 0) {
fillInverse(ctx, img, 0, -squareSize);
} else
ctx.drawImage(img, 0, -squareSize);
}
ctx.restore(); // restore 1
}
}

View File

@@ -0,0 +1,236 @@
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;
import javafx.scene.paint.Color;
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;
public static TextFontAdjuster getInstance() {
return demo;
}
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 boolean paused;
private Printer printer;
private boolean grid = true;
private 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 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 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);
}
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);
}
private void setup() {
drawBackgroundGrid();
printHelp();
printInfo();
}
@Override
public void start(Stage stage) {
demo = this;
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.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();
}
}

View File

@@ -0,0 +1,158 @@
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);
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];
}
}
/**
* 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;
private int h;
private int hIndex;
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];
}
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;
}
public double getCharBoxSize() {
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 int getLineWidth() {
return w;
}
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 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 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 vertical modes
*
* @return Previous available vertical mode (horizontal resolution unchanged)
*/
public TextMode prevVertMode() {
return findMode((hIndex - 1) % Constants.HREZ.length, vIndex);
}
}

View File

@@ -0,0 +1,95 @@
      leahciM  
  ▓████ ▄▀   ▓█
███ ▄▄ ▀▀▀▀██▐
 ████▀ ▀▀▀    
       :yb neercS  
 ▓████     ▓██
██▄  ▀ ████ ░ ▓
███▐▄ ▓███▀▄▄█▀
▀▀                 
   ▓███▄ ▄▀█ 
 ▓████▄ ▀▀ ███
▄ ░ ▓███▀▄ ▓███
▀ ▄▄██▀▀▀       
         ▓███  
▄   ▓███▄▄▀▀▀▀
▄▄  ░░█▌ ▓███
▀▄ ▓▓██▀  ▄█▀
██▀▀ █     ▀▀▀ ▀▀▀
▓███     ▓███▄
 ▀▀▄▄▄   ▄ ░  
██▄▀▄█ ▄▄ ▓
██▀  ▄▄▄███▀   
  ▄▀▀▀▀▀███ ▐ 
 ▐▄ ▓██▄  █▄
 ▀▀▀▀░░▀█▀▀▀██
█   ▄ ▓██     ▄▄
▄▄▄      ▄▄▄▄▄▄
▄▌▌ ▒▓ ▐ ▄▄▄
▄   ▄▄▄  ▄█████▀▀███
███▄▀▀▀▀▀▄▄█   
                     
  ▐▌ ▒▓▓▐ ▐██▀
▀▀▀ ▀▀▀▀▀▀▄███████
▓▓▓▀██████████▀▀▀  
                     
 ▌ ▐ ▒▒▓▄ █████
█▀▀▀███▓▓██▀▀▄██▓
▓▓▀▀▓▓▓▓▓██████▄▄▀
▀                   
  ▌ ▌  ▓▓▌ ██▀█
██████████▓▓▓▓▓▄▄▀▀
▓▓▓▓████▄▄▄▄▄██
 ▀                 
     ▐  ▄▓▌ ▓█▄▄
▄██████████▄▀█▄▄▄███▄▄▄
▀▀█▀▀ ▄██ ▀▀    
               ▌    ▄
▄▄░▓█▀██▀▀▀▄▄▄▄▄▀▀
▓▓████▀▀▀▀▓▓▓▓▓███
▀ ▄▄█▀▀▀▀▀▀▀   
                 ▀▄▄▄
▀▀████████▓▓▓▓▓█▓▓▓▓
▓▓███▀████▓▓▓▓███
▀▀ ▄▄▄▄▄▄▄▄█   
                 ▄███
███████▓▓▓▓▓███▀█▓▓▓
▓▓▓███▀▄▄▄▄███████
█▀                   
          ▄ ▀▀▄███
█████████▄▄▐▌▀█▄▀▀▀
▀▀▀▄▄█▀▐  ▄▀▀▄▄▄███
▀▀                
            ██▄▄▄
▄▄▄▄▄▄▄▄▀▀▀▀▀▀█▄
 ▀▀▀▄██▀▀▀▀▀  ██
▄▄▄█           
               ▀ ██
           ▀▀▄▄▄▀▀
▀█▓▐▐█▓▀▀▀▀▄▄▄▀▀ 
█▀  ▄▄▄          
                 ██
▄          ▀▄▀█▄
███▓▓█▌▌▐█▓█████
█▀▄█  █           
                    
 ███           ▄▀
▄▄██████▐█▒█▐████
███▄▀▄  █▀      
                     
  ▄██▄           
 ▄▄█▀▄▄▄██████████
▄▄▄▀▄  ▄ █▀   
                     
    ▌█▄           
    ▄▄▄▄█▀▄▄▄██▄▄
▄▀█▄▄▄    ▄▄█  
                      
    ▌▄            
        ▄▄▄▄▄▄▄▄▄
▄▄▄         ▄▄▄     
                      
 ▄▄▄                
                     
                     

View File

@@ -0,0 +1,69 @@
package inf101.v18.grid;
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);
private final double degrees;
private final int dx;
private final int dy;
private final int mask;
GridDirection(double degrees, int dx, int dy, int mask) {
this.degrees = degrees;
this.dx = dx;
this.dy = dy;
this.mask = mask;
}
/**
* @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 X-coordinate if you were to move one step in this
* direction
*/
public int getDx() {
return dx;
}
/**
* @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

@@ -0,0 +1,161 @@
package inf101.v18.grid;
import java.util.List;
import java.util.stream.Stream;
/**
* Representation of a two-dimensional area.
* <p>
* This describes the coordinate system of the area and defines the set of valid
* locations within the area.
* <p>
* See {@link #location(int, int)} to covert (x,y)-coordinates to
* {@link ILocation}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);
/**
* 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);
/**
* 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);
/** @return Height of the area */
int getHeight();
/**
* Returns the number of legal positions in the area
*
* @return Same as getWidth()*getHeight()
*/
int getSize();
/** @return Width of the area */
int getWidth();
@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 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();
/**
* 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 A (possibly) parallel {@link Stream} of all locations in the area */
Stream<ILocation> parallelStream();
/** @return A {@link Stream} of all locations in the area */
Stream<ILocation> 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);
@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 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

@@ -0,0 +1,213 @@
package inf101.v18.grid;
import java.util.function.Function;
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();
/**
* 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();
/**
* 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);
/**
* 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);
/**
* 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.
*
* 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();
/** @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.
*
* 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();
/**
* 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.
*
* 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();
/**
* 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();
/**
* 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();
/**
* 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.
*
* 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

@@ -0,0 +1,107 @@
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

@@ -0,0 +1,214 @@
package inf101.v18.grid;
import java.util.List;
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 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);
}
/**
* 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 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.
*
* 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);
}
/**
* 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());
}
/**
* 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);
}
/**
* 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 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 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.
*
* 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

@@ -0,0 +1,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);
/**
* 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);
/**
* Gets the x-coordinate
*
* @return
*/
int getX();
/**
* 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);
@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);
/** @return Position as a string, "(x,y)" */
@Override
String toString();
}

View File

@@ -0,0 +1,16 @@
package inf101.v18.grid;
import java.util.ArrayList;
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(int width, int height) {
super(width, height, (l) -> new ArrayList<T>());
}
}

View File

@@ -0,0 +1,221 @@
package inf101.v18.grid;
import java.util.ArrayList;
import java.util.Iterator;
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. */
public class MyGrid<T> implements IGrid<T> {
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();
}
this.area = area;
this.cells = new ArrayList<T>(area.getSize());
for (ILocation 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();
}
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.
*
* @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 Stream<T> elementParallelStream() {
return cells.parallelStream();
}
@Override
public Stream<T> elementStream() {
return cells.stream();
}
@Override
public void fill(Function<ILocation, T> initialiser) {
if (initialiser == null)
throw new NullPointerException();
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 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(int x, int y) {
return cells.get(area.toIndex(x, y));
}
@Override
public IArea getArea() {
return area;
}
@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(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 boolean isValid(ILocation 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 Iterator<T> iterator() {
return cells.iterator();
}
@Override
public Stream<ILocation> locationParallelStream() {
return area.parallelStream();
}
@Override
public Iterable<ILocation> locations() {
return area;
}
@Override
public Stream<ILocation> 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(int x, int y, T elem) {
cells.set(area.toIndex(x, y), elem);
}
}

View File

@@ -0,0 +1,10 @@
# A new (improved?) version of the grid ADT
## 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”.

View File

@@ -0,0 +1,341 @@
package inf101.v18.grid;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
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 {
/** 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;
}
@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 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 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 IArea getArea() {
return RectArea.this;
}
@Override
public int getIndex() {
return idx;
}
@Override
public int getX() {
return x;
}
@Override
public int getY() {
return y;
}
@Override
public ILocation 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 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 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 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 boolean hWrap, vWrap;
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);
}
/**
* @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;
}
/**
* @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(IPosition pos) {
return (pos instanceof ILocation && ((ILocation) 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 int getHeight() {
return height;
}
@Override
public int getSize() {
return size;
}
@Override
public int getWidth() {
return width;
}
@Override
public Iterator<ILocation> 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 List<ILocation> locations() {
return locs; // (OK since locs has been through Collections.unmodifiableList())
}
@Override
public Iterable<ILocation> neighboursOf(ILocation pos) {
return pos.allNeighbours();
}
@Override
public Stream<ILocation> parallelStream() {
return locs.parallelStream();
}
@Override
public Stream<ILocation> stream() {
return locs.stream();
}
@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 boolean wrapsHorizontally() {
return hWrap;
}
@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 wrapY(int y) {
if (hWrap) {
if (y < 0) {
return getHeight() + y % getHeight();
} else {
return y % getHeight();
}
} else {
return y;
}
}
}

View File

@@ -0,0 +1,32 @@
package inf101.v18.rogue101;
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 = "";
}

View File

@@ -0,0 +1,211 @@
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 javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javafx.util.Duration;
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;
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 void main(String[] args) {
launch(args);
}
private Screen screen;
private ITurtle painter;
private Printer printer;
private Game game;
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();
//
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);
// 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);
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();
} catch (Exception e) {
printer.printAt(1, 25, "Exception: " + e.getMessage(), Color.RED);
e.printStackTrace();
}
return true;*/ // This interferes with other code
} else {
try {
if (game.keyPressed(code)) {
game.draw();
} else {
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();
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 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

@@ -0,0 +1,107 @@
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;
public class Boss implements INonPlayer {
private int hp = getMaxHealth();
private final Backpack backpack = new Backpack();
private ILocation loc;
public Boss() {
backpack.add(new Sword());
}
@Override
public void doTurn(IGame game) {
loc = game.getLocation();
NPC.tryAttack(game, 1, Attack.MELEE);
}
@Override
public int getAttack() {
return 50;
}
@Override
public int getDamage() {
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() {
return 40;
}
@Override
public int getMaxHealth() {
return 550;
}
@Override
public String getName() {
return "Lucifer";
}
@Override
public int getSize() {
return 50;
}
@Override
public String getPrintSymbol() {
return "\u001b[91m" + "\uD83D\uDE08" + "\u001b[0m";
}
@Override
public String getSymbol() {
return "B";
}
@Override
public int getVision() {
return 3;
}
@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();
}
game.getPrinter().printAt(Main.COLUMN_RIGHTSIDE_START, 19, "Boss HP: " + NPC.hpBar(this));
return amount;
}
}

View File

@@ -0,0 +1,280 @@
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 java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Girl implements INonPlayer {
private final String name = randomName();
private final Age age = Age.getRandom();
private final Personality personality = Personality.getRandom();
private final Occupation occupation = Occupation.getRandom();
private int maxhp;
private int hp;
private int attack;
private int defence;
private int visibility;
private int damage;
private final Backpack backpack = new Backpack();
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"};
public Girl() {
setStats();
setValidItems();
}
private void setStats() {
switch (age) {
case TODDLER:
maxhp = 30;
attack = 10;
defence = 50;
damage = 1 + random.nextInt(5);
visibility = 1;
break;
case CHILD:
maxhp = 50;
attack = 20;
defence = 40;
damage = 2 + random.nextInt(5);
visibility = 2;
break;
case TEEN:
maxhp = 70;
attack = 25;
defence = 30;
damage = 3 + random.nextInt(5);
visibility = 3;
break;
case ADULT:
maxhp = 100;
attack = 30;
defence = 20;
damage = 4 + random.nextInt(5);
visibility = 4;
break;
case ELDER:
maxhp = 70;
attack = 15;
defence = 35;
damage = 3 + random.nextInt(5);
visibility = 2;
break;
}
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.
}
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
*/
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());
}
}
}
/**
* Specified which items the current Girl should be able to pick up.
*/
private void setValidItems() {
validItems = new ArrayList<>();
switch (occupation) {
case BOWSMAN:
validItems.add(IRangedWeapon.class);
break;
case MAGE:
validItems.add(IMagicWeapon.class);
break;
case KNIGHT:
validItems.add(IMeleeWeapon.class);
}
validItems.add(IBuffItem.class);
}
/**
* Picks a "random" name
*
* @return A random name
*/
private String randomName() {
return namelist[random.nextInt(namelist.length)] + "-chan";
}
@Override
public void doTurn(IGame game) {
if (backpack.hasSpace()) {
IItem item = NPC.pickUp(game, validItems);
if (item != null) {
backpack.add(item);
return;
}
if (NPC.trackItem(game, validItems)) {
return;
}
}
if (personality == Personality.AFRAID && NPC.flee(game)) {
return;
}
if (willAttack(game) && attack(game)) {
return;
}
List<GridDirection> possibleMoves = game.getPossibleMoves();
if (!possibleMoves.isEmpty()) {
Collections.shuffle(possibleMoves);
game.move(possibleMoves.get(0));
}
}
/**
* 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
*/
private boolean attack(IGame game) {
switch (occupation) {
case KNIGHT:
if (NPC.tryAttack(game, 1, Attack.MELEE)) {
return true;
}
break;
case MAGE:
if (NPC.tryAttack(game, getVision() / 2 + getVision() % 2 == 0 ? 0 : 1, Attack.MAGIC)) {
return true;
}
case BOWSMAN:
if (NPC.tryAttack(game, getVision(), Attack.RANGED)) {
return true;
}
}
return false;
}
/**
* Checks if the current girl will try to attack.
*
* @param game An IGame object
* @return True if the girl will attack. False otherwise
*/
private boolean willAttack(IGame game) {
boolean attack = false;
switch (personality) {
case CALM:
if (hp < maxhp) {
attack = true;
}
break;
case AFRAID:
if (game.getPossibleMoves().isEmpty()) {
attack = true;
}
break;
case AGRESSIVE:
attack = true;
break;
}
return attack;
}
@Override
public int getAttack() {
return attack;
}
@Override
public int getDamage() {
return damage;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
return defence;
}
@Override
public int getMaxHealth() {
return maxhp;
}
@Override
public String getName() {
return name;
}
@Override
public int getSize() {
return 30;
}
@Override
public String getPrintSymbol() {
return "\u001b[95m" + "\uD83D\uDEB6" + "\u001b[0m";
}
@Override
public String getSymbol() {
return "G";
}
@Override
public int getVision() {
return visibility;
}
@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;
return amount;
}
}

View File

@@ -0,0 +1,145 @@
package inf101.v18.rogue101.events;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
/**
* 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
*/
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 IItem source;
private final IItem target;
private T value;
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, 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, 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, IItem source, T value) {
this(name, null, source, null, value);
}
@Override
public T getData() {
return value;
}
@Override
public String getEventName() {
return name;
}
@Override
public IGame getGame() {
return game;
}
@Override
public IItem getSource() {
return source;
}
@Override
public IItem getTarget() {
return target;
}
@Override
public void setData(T value) {
this.value = value;
}
}

View File

@@ -0,0 +1,72 @@
package inf101.v18.rogue101.events;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
/**
* An “event” is something that happens in the game, typically due to an actor
* taking some action (nut could also be used to transmit user input)
* <p>
* Storing the particular action and it's associated data in an object means
* that we can extend our system with many different kinds of actions and have
* many different reactions to those actions without having to all of the
* "game rule specific" stuff to all our interfaces and classes.
* <p>
* Our event objects let you store an extra (arbitrary) piece of data, giving
* more information about what happened. An event handler can also update this
* information, which is a possible way to report back to whomever caused the
* event in the first place. The event objects also contain an event name, and
* 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
*/
public interface IEvent<T> {
/**
* @return Extra data stored in this event
*/
T getData();
/**
* @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();
/**
* 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 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();
/**
* @param value
* Extra data to store in this event
*/
void setData(T value);
}

View File

@@ -0,0 +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 javafx.scene.paint.Color;
public class Carrot implements IItem {
private int hp = 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 int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
return 0;
}
@Override
public double getHealthStatus() {
return getCurrentHealth() / getMaxHealth();
}
@Override
public int getMaxHealth() {
return 23;
}
@Override
public String getName() {
return "carrot";
}
@Override
public int getSize() {
return 2;
}
@Override
public String getSymbol() {
return "C";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
if (hp < 0) {
// we're all eaten!
hp = 0;
}
return amount;
}
}

View File

@@ -0,0 +1,51 @@
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

@@ -0,0 +1,122 @@
package inf101.v18.rogue101.examples;
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 INonPlayer {
private int food = 0;
private int hp = getMaxHealth();
private static final List<Class<?>> validItems = new ArrayList<>();
static {
validItems.add(Carrot.class);
}
@Override
public void doTurn(IGame game) {
if (food == 0) {
hp--;
} else {
food--;
}
if (hp < 1) {
return;
}
if (NPC.tryAttack(game, 1, Attack.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;
}
}
}
if (NPC.trackItem(game, validItems)) {
return;
}
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 int getAttack() {
return 10;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDamage() {
return 5;
}
@Override
public int getDefence() {
return 10;
}
@Override
public int getMaxHealth() {
return 30;
}
@Override
public String getName() {
return "Rabbit";
}
@Override
public int getSize() {
return 4;
}
@Override
public int getVision() {
return 4;
}
@Override
public IItem getItem(Class<?> type) {
return null;
}
@Override
public String getSymbol() {
return hp > 0 ? "R" : "¤";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
return amount;
}
}

View File

@@ -0,0 +1,819 @@
package inf101.v18.rogue101.game;
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;
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.ILocation;
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.items.Manga;
import inf101.v18.rogue101.items.*;
import inf101.v18.rogue101.examples.Rabbit;
import inf101.v18.rogue101.map.GameMap;
import inf101.v18.rogue101.map.IGameMap;
import inf101.v18.rogue101.map.IMapView;
import inf101.v18.rogue101.map.MapReader;
import inf101.v18.rogue101.objects.*;
import inf101.v18.rogue101.shared.NPC;
import inf101.v18.rogue101.states.Attack;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
public class Game implements IGame {
/**
* All the IActors that have things left to do this turn
*/
private List<IActor> actors = Collections.synchronizedList(new ArrayList<>());
/**
* For fancy solution to factory problem
*/
private Map<String, Supplier<IItem>> itemFactories = new HashMap<>();
/**
* Useful random generator
*/
private Random random = new Random();
/**
* Saves the last three messages
*/
private List<String> lastMessages = new ArrayList<>();
/**
* The game map. {@link IGameMap} gives us a few more details than
* {@link IMapView} (write access to item lists); the game needs this but
* individual items don't.
*/
private IGameMap map;
private List<IGameMap> maps = new ArrayList<>();
private int currentLVL = 0;
private IActor currentActor;
private ILocation currentLocation;
private int movePoints = 0;
private final ITurtle painter;
private final Printer printer;
private int numPlayers = 0;
private boolean won = false;
public Game(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_RIGHTSIDE_START, 1 + i, info[i]);
}
}
public Game(String mapString) {
printer = new Printer(1280, 720);
painter = new TurtlePainter(1280, 720);
addFactory();
IGrid<String> inputGrid = MapReader.readString(mapString);
this.map = new GameMap(inputGrid.getArea());
for (ILocation loc : inputGrid.locations()) {
IItem item = createItem(inputGrid.get(loc));
if (item != null) {
map.add(loc, item);
}
}
}
@Override
public void addItem(IItem item) {
map.add(currentLocation, item);
}
@Override
public void addItem(String sym) {
IItem 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(Attack type) {
int attack = currentActor.getAttack() + random.nextInt(20) + 1;
IWeapon weapon = NPC.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(IItem target) {
int defence = target.getDefence() + 10;
IActor actor = (IActor) target;
IBuffItem item = (IBuffItem) actor.getItem(IBuffItem.class);
if (item != null) {
defence += item.getBuffDefence();
}
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(IItem target, Attack type) {
int damage = currentActor.getDamage();
IWeapon weapon = NPC.getWeapon(type, currentActor);
if (weapon != null) {
damage += weapon.getWeaponDamage();
}
IBuffItem buff = (IBuffItem)currentActor.getItem(IBuffItem.class);
if (buff != null) {
damage += buff.getBuffDamage();
}
IBuffItem item = (IBuffItem)((IActor)target).getItem(IBuffItem.class);
if (item != null) {
damage -= item.getBuffDamageReduction();
}
return damage;
}
@Override
public ILocation attack(GridDirection dir, IItem target) {
ILocation loc = currentLocation.go(dir);
if (!map.has(loc, target)) {
throw new IllegalMoveException("Target isn't there!");
}
IWeapon weapon = (IWeapon) currentActor.getItem(IMeleeWeapon.class);
if (weapon != null) {
NPC.playSound(weapon.getSound());
} else {
NPC.playSound("audio/Realistic_Punch-Mark_DiAngelo-1609462330.wav");
}
if (getAttack(Attack.MELEE) >= getDefence(target)) {
int actualDamage = target.handleDamage(this, target, getDamage(target, Attack.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 ILocation rangedAttack(GridDirection dir, IItem target, Attack type) {
ILocation loc = currentLocation;
IWeapon weapon = null;
switch (type) {
case MAGIC:
weapon = (IWeapon) currentActor.getItem(IMagicWeapon.class);
break;
case RANGED:
weapon = (IWeapon) currentActor.getItem(IRangedWeapon.class);
}
if (weapon != null) {
NPC.playSound(weapon.getSound());
} else {
NPC.playSound("audio/Snow Ball Throw And Splat-SoundBible.com-992042947.wav");
}
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 (numPlayers == 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)
}
if (currentActor.isDestroyed()) // skip if it's dead
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
if (currentActor instanceof INonPlayer) {
// computer-controlled players do their stuff right away
((INonPlayer) currentActor).doTurn(this);
// remove any dead items from current location
map.clean(currentLocation);
return false;
} else if (currentActor instanceof IPlayer) {
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 (numPlayers > 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");
NPC.playSound("audio/Dying-SoundBible.com-1255481835.wav");
}
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);
NPC.playSound("audio/1_person_cheering-Jett_Rifkin-1851518140.wav");
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);
}
IGameMap map = new GameMap(inputGrid.getArea());
for (ILocation loc : inputGrid.locations()) {
IItem 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);
}
IGameMap map = new GameMap(inputGrid.getArea());
for (ILocation loc : inputGrid.locations()) {
IItem 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() {
numPlayers = 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<IItem> list = map.getAllModifiable(loc); // all items at loc
Iterator<IItem> li = list.iterator(); // manual iterator lets us remove() items
while (li.hasNext()) { // this is what "for(IItem item : list)" looks like on the inside
IItem 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 IPlayer) {
actors.add(0, (IActor) item); // we let the human player go first
synchronized (this) {
numPlayers++;
}
} else if (item instanceof IActor) {
actors.add((IActor) 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", Sword::new);
itemFactories.put("c", Chest::new);
itemFactories.put("B", Boss::new);
itemFactories.put("s", Staff::new);
itemFactories.put("b", Bow::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 IItem createItem(String sym) {
switch (sym) {
case " ":
return null;
default:
// alternative/advanced method
Supplier<IItem> factory = itemFactories.get(sym);
if (factory != null) {
return factory.get();
} else {
System.err.println("createItem: Don't know how to create a '" + sym + "'");
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 (numPlayers == 0) {
map.draw(painter, printer);
} else {
((GameMap) map).drawVisible(painter, printer);
}
}
@Override
public boolean drop(IItem item) {
if (item != null) {
map.add(currentLocation, item);
return true;
} else
return false;
}
@Override
public boolean dropAt(ILocation loc, IItem 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<IItem> getLocalItems() {
return map.getItems(currentLocation);
}
@Override
public ILocation getLocation() {
return currentLocation;
}
@Override
public ILocation getLocation(GridDirection dir) {
if (currentLocation.canGo(dir))
return currentLocation.go(dir);
else
return null;
}
/**
* Return the game map. {@link IGameMap} gives us a few more details than
* {@link IMapView} (write access to item lists); the game needs this but
* individual items don't.
*/
@Override
public IMapView 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<ILocation> getVisible() {
List<ILocation> neighbours = map.getNeighbourhood(currentLocation, currentActor.getVision());
List<ILocation> invalid = new ArrayList<>();
for (ILocation neighbour : neighbours) {
for (ILocation tile : currentLocation.gridLineTo(neighbour)) {
if (map.hasWall(tile)) {
invalid.add(neighbour);
break;
}
}
}
neighbours.removeAll(invalid);
return neighbours;
}
@Override
public int getWidth() {
return 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 IPlayer) || !((IPlayer) currentActor).keyPressed(this, code);
}
@Override
public ILocation move(GridDirection dir) {
if (movePoints < 1)
throw new IllegalMoveException("You're out of moves!");
ILocation newLoc = map.go(currentLocation, dir);
map.remove(currentLocation, currentActor);
map.add(newLoc, currentActor);
currentLocation = newLoc;
movePoints--;
return currentLocation;
}
@Override
public IItem pickUp(IItem item) {
if (item != null && map.has(currentLocation, item) && !(item instanceof IStatic)) {
if (item instanceof IActor) {
if (item.getCurrentHealth() / item.getMaxHealth() < 3) {
map.remove(currentLocation, item);
return item;
} else {
return null;
}
} else if (currentActor.getAttack() > item.getDefence()) {
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 IActor getActor() {
return currentActor;
}
public ILocation setCurrent(IActor actor) {
currentLocation = map.getLocation(actor);
if (currentLocation != null) {
currentActor = actor;
movePoints = 1;
}
return currentLocation;
}
public IActor setCurrent(ILocation loc) {
List<IActor> list = map.getActors(loc);
if (!list.isEmpty()) {
currentActor = list.get(0);
currentLocation = loc;
movePoints = 1;
}
return currentActor;
}
public IActor setCurrent(int x, int y) {
return setCurrent(map.getLocation(x, y));
}
@Override
public Random getRandom() {
return random;
}
@Override
public List<GridDirection> locationDirection(ILocation start, ILocation target) {
int targetX = target.getX(), targetY = target.getY();
int startX = start.getX(), startY = start.getY();
List<GridDirection> dirs = new ArrayList<>();
if (targetX > startX && targetY > startY) {
if (Math.abs(targetX - startX) < Math.abs(targetY - startY)) {
dirs.add(GridDirection.SOUTH);
dirs.add(GridDirection.EAST);
} else {
dirs.add(GridDirection.EAST);
dirs.add(GridDirection.SOUTH);
}
} else if (targetX > startX && targetY < startY) {
if (Math.abs(targetX - startX) < Math.abs(targetY - startY)) {
dirs.add(GridDirection.NORTH);
dirs.add(GridDirection.EAST);
} else {
dirs.add(GridDirection.EAST);
dirs.add(GridDirection.NORTH);
}
} else if (targetX < startX && targetY > startY) {
if (Math.abs(targetX - startX) < Math.abs(targetY - startY)) {
dirs.add(GridDirection.SOUTH);
dirs.add(GridDirection.WEST);
} else {
dirs.add(GridDirection.WEST);
dirs.add(GridDirection.SOUTH);
}
} else if (targetX < startX && targetY < startY) {
if (Math.abs(targetX - startX) < Math.abs(targetY - startY)) {
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

@@ -0,0 +1,340 @@
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

@@ -0,0 +1,20 @@
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
*
*/
public class IllegalMoveException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 7641529271996915740L;
public IllegalMoveException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,145 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Backpack implements IContainer {
/**
* A list containing everything in the backpack.
*/
private final List<IItem> content = new ArrayList<>();
/**
* The maximum amount of items allowed in a single backpack.
*/
private final int MAX_SIZE = 5;
@Override
public int getCurrentHealth() {
return 0;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 0;
}
@Override
public String getName() {
return "Backpack";
}
@Override
public int getSize() {
return 20;
}
@Override
public String getSymbol() {
return "B";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
return 0;
}
/**
* Retrieves the current size of the Backpack.
*
* @return The size
*/
public int size() {
return content.size();
}
/**
* Checks if the Backpack is empty
*
* @return True if empty. False otherwise
*/
public boolean isEmpty() {
return content.isEmpty();
}
/**
* 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
*/
public boolean add(IItem item) {
if (size() < MAX_SIZE) {
content.add(item);
return true;
} else {
return false;
}
}
@Override
public void remove(int i) {
content.remove(i);
}
/**
* Removes item from the backpack.
*
* @param item The item to remove
*/
public void remove(IItem item) {
content.remove(item);
}
/**
* Gets a T at index i,
*
* @param i The index of an element
* @return An object of type T
*/
public IItem get(int i) {
return content.get(i);
}
@Override
public boolean addItem(IItem item) {
if (content.size() < MAX_SIZE) {
content.add(item);
return true;
} else {
return false;
}
}
/**
* Gets the content List for direct manipulation.
*
* @return A list of T
*/
public List<IItem> getContent() {
return Collections.unmodifiableList(content);
}
@Override
public boolean hasSpace() {
return size() < MAX_SIZE;
}
@Override
public IItem getFirst(Class<?> clazz) {
for (IItem item : content) {
if (clazz.isInstance(item)) {
return item;
}
}
return null;
}
}

View File

@@ -0,0 +1,52 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
public class Binoculars implements IBuffItem {
@Override
public int getBuffVisibility() {
return 2;
}
@Override
public int getCurrentHealth() {
return 0;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 0;
}
@Override
public String getName() {
return "Binoculars";
}
@Override
public int getSize() {
return 0;
}
@Override
public String getPrintSymbol() {
return "\uD83D\uDD0E";
}
@Override
public String getSymbol() {
return "b";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
return 0;
}
}

View File

@@ -0,0 +1,62 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import java.util.Random;
public class Bow implements IRangedWeapon {
private static final Random random = new Random();
private final int damage = 3 + random.nextInt(20);
private final int hp = getMaxHealth();
@Override
public int getWeaponDamage() {
return damage;
}
@Override
public int getWeaponAttack() {
return 15;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 110;
}
@Override
public String getName() {
return "Unknown bow";
}
@Override
public int getSize() {
return 2;
}
@Override
public String getPrintSymbol() {
return "\uD83C\uDFF9";
}
@Override
public String getSymbol() {
return "b";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
return 0;
}
}

View File

@@ -0,0 +1,124 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
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;
private final int MAX_SIZE = 10;
public Chest() {
this.container = new ArrayList<>();
}
/**
* Randomly fills chest with random items based on dungeon level.
*
* @param lvl The current dungeon level
*/
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());
items.add(new Binoculars());
items.add(new Shield());
items.add(new Manga());
for (int i = 0; i < MAX_SIZE; i++) {
int num = random.nextInt(100);
boolean added = false;
for (int j = 0; j < items.size(); j++) {
if (num < (itemChance * (j + 1)) + ((j + 1) * lvl)) {
addItem(items.get(j));
items.remove(j); //We don't want duplicates
added = true;
break;
}
}
if (!added && num > 70) {
addItem(new HealthPotion());
}
}
}
@Override
public IItem get(int i) {
return container.get(i);
}
@Override
public List<IItem> getContent() {
return Collections.unmodifiableList(container);
}
@Override
public boolean hasSpace() {
return container.size() < MAX_SIZE;
}
@Override
public IItem getFirst(Class<?> clazz) {
for (IItem item : container) {
if (clazz.isInstance(item)) {
return item;
}
}
return null;
}
@Override
public int getCurrentHealth() {
return 0;
}
@Override
public int getMaxHealth() {
return 0;
}
@Override
public String getName() {
return "Chest";
}
@Override
public int getSize() {
return 10000;
}
public String getPrintSymbol() {
return "\u001b[94m" + "\uD83D\uDDC3" + "\u001b[0m";
}
@Override
public String getSymbol() {
return "C";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
return 0;
}
@Override
public boolean addItem(IItem item) {
if (container.size() < MAX_SIZE) {
container.add(item);
return true;
} else {
return false;
}
}
@Override
public void remove(int i) {
container.remove(i);
}
}

View File

@@ -0,0 +1,56 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
public class HealthPotion implements IConsumable {
@Override
public int hpIncrease() {
return 100;
}
@Override
public int attackIncrease() {
return 0;
}
@Override
public int defenceIncrease() {
return 0;
}
@Override
public int getCurrentHealth() {
return 0;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 0;
}
@Override
public String getName() {
return "Healing potion";
}
@Override
public int getSize() {
return 0;
}
@Override
public String getSymbol() {
return "H";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
return 0;
}
}

View File

@@ -0,0 +1,41 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.objects.IItem;
public interface IBuffItem extends IItem {
/**
* Retrieve damage increase done by the buff item.
*
* @return An int, May be 0
*/
default int getBuffDamage() {
return 0;
}
/**
* Retrieve defence increase done by the buff item.
*
* @return An int, May be 0
*/
default int getBuffDefence() {
return 0;
}
/**
* Retrieve defence increase done by the buff item.
*
* @return An int, May be 0
*/
default int getBuffDamageReduction() {
return 0;
}
/**
* Retrieve visibility increase done by the buff item.
*
* @return An int, May be 0
*/
default int getBuffVisibility() {
return 0;
}
}

View File

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

View File

@@ -0,0 +1,62 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.objects.IItem;
import java.util.List;
public interface IContainer extends IItem {
/**
* Retrieves an item from a container in index i
*
* @param i The index of an element
* @return An IItem
* @throws IndexOutOfBoundsException If the index is out of range.
*/
IItem 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
*/
boolean addItem(IItem item);
/**
* Gets a list with everything inside a container.
*
* @return A list of Objects extending IItem
*/
List<IItem> getContent();
/**
* Checks if we can add anything at all to the container.
*
* @return True if it has no space left
*/
boolean hasSpace();
/**
* Returns the message to show the user upon interacting with the container.
*
* @return A message
*/
default String getInteractMessage() {
return "Items in " + getName() + ": ";
}
/**
* Gets the first item from the container of a specified type.
*
* @param clazz The class type to accept
* @return An IItem or null
*/
IItem getFirst(Class<?> clazz);
/**
* Removes an element at index i from the container.
*
* @param i The index of an element
*/
void remove(int i);
}

View File

@@ -0,0 +1,12 @@
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

@@ -0,0 +1,12 @@
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

@@ -0,0 +1,12 @@
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

@@ -0,0 +1,15 @@
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

@@ -0,0 +1,26 @@
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

@@ -0,0 +1,64 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
public class Manga implements IConsumable {
private int hp = getMaxHealth();
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 1;
}
@Override
public String getName() {
return "Manga";
}
@Override
public int getSize() {
return 5;
}
@Override
public String getPrintSymbol() {
return "🕮";
}
@Override
public String getSymbol() {
return "M";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
return amount;
}
@Override
public int hpIncrease() {
return 0;
}
@Override
public int attackIncrease() {
return 5;
}
@Override
public int defenceIncrease() {
return 5;
}
}

View File

@@ -0,0 +1,58 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
public class Shield implements IBuffItem {
private final int hp = getMaxHealth();
@Override
public int getBuffDefence() {
return 10;
}
@Override
public int getBuffDamageReduction() {
return 1;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 150;
}
@Override
public String getName() {
return "Unknown shield";
}
@Override
public int getSize() {
return 2;
}
@Override
public String getPrintSymbol() {
return "\uD83D\uDEE1";
}
@Override
public String getSymbol() {
return "f";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
return 0;
}
}

View File

@@ -0,0 +1,63 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import java.util.Random;
public class Staff implements IMagicWeapon {
private static final Random random = new Random();
private final int damage = 5 + random.nextInt(25);
private int hp = getMaxHealth();
@Override
public int getWeaponDamage() {
return damage;
}
@Override
public int getWeaponAttack() {
return 10;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 90;
}
@Override
public String getName() {
return "Unknown staff";
}
@Override
public int getSize() {
return 0;
}
@Override
public String getPrintSymbol() {
return "";
}
@Override
public String getSymbol() {
return "s";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
return amount;
}
}

View File

@@ -0,0 +1,63 @@
package inf101.v18.rogue101.items;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.objects.IItem;
import java.util.Random;
public class Sword implements IMeleeWeapon {
private static final Random random = new Random();
private final int damage = 5 + random.nextInt(25);
private int hp = getMaxHealth();
@Override
public int getWeaponDamage() {
return damage;
}
@Override
public int getWeaponAttack() {
return 5;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 100;
}
@Override
public String getName() {
return "Unknown sword";
}
@Override
public int getSize() {
return 2;
}
@Override
public String getPrintSymbol() {
return "";
}
@Override
public String getSymbol() {
return "S";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
return amount;
}
}

View File

@@ -0,0 +1,393 @@
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;
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<>();
public GameMap(IArea area) {
grid = new MultiGrid<>(area);
}
public GameMap(int width, int height) {
grid = new MultiGrid<>(width, height);
}
@Override
public void add(ILocation loc, IItem 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<IItem> 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(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

@@ -0,0 +1,48 @@
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

@@ -0,0 +1,190 @@
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

@@ -0,0 +1,100 @@
package inf101.v18.rogue101.map;
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}.
*
* 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
* *## p
* * rr#
* *####
* * *
* * d
* 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]++;
}
}
/**
* 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;
}
}

View File

@@ -0,0 +1,49 @@
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

@@ -0,0 +1,50 @@
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 FakeWall 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 1;
}
@Override
public String getName() {
return "fake wall";
}
@Override
public int getSize() {
return Integer.MAX_VALUE;
}
@Override
public String getSymbol() {
return "\u001b[47m" + BlocksAndBoxes.BLOCK_FULL + "\u001b[0m";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
return amount;
}
}

View File

@@ -0,0 +1,40 @@
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

@@ -0,0 +1,181 @@
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

@@ -0,0 +1,22 @@
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

@@ -0,0 +1,26 @@
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

@@ -0,0 +1,540 @@
package inf101.v18.rogue101.objects;
import inf101.v18.gfx.textmode.Printer;
import inf101.v18.grid.GridDirection;
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.*;
import inf101.v18.rogue101.shared.NPC;
import inf101.v18.rogue101.states.Attack;
import javafx.scene.input.KeyCode;
import java.util.List;
public class Player implements IPlayer {
private int hp = 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 String text = "";
private String name = "Player";
@Override
public boolean keyPressed(IGame game, KeyCode key) {
boolean turnConsumed = false;
if (writing) {
write(game, key);
return false;
}
if (key == KeyCode.LEFT || key == KeyCode.A) {
tryToMove(game, GridDirection.WEST);
turnConsumed = true;
} else if (key == KeyCode.RIGHT || key == KeyCode.D) {
tryToMove(game, GridDirection.EAST);
turnConsumed = true;
} else if (key == KeyCode.UP || key == KeyCode.W) {
tryToMove(game, GridDirection.NORTH);
turnConsumed = true;
} else if (key == KeyCode.DOWN || key == KeyCode.S) {
tryToMove(game, GridDirection.SOUTH);
turnConsumed = true;
} else if (key == KeyCode.E) {
turnConsumed = interactInit(game);
} else if (key == KeyCode.Q) {
turnConsumed = dropInit(game);
} else if (key == KeyCode.C) {
turnConsumed = useConsumable(game);
} else if (key.isDigitKey()) {
//Takes care of all digit keys.
int keyValue = Integer.parseInt(key.getName());
if (keyValue == 0) {
keyValue = 10;
}
if (dropping) {
drop(game, keyValue - 1);
dropping = false;
turnConsumed = true;
} else if (picking) {
pickUp(game, keyValue - 1);
picking = false;
turnConsumed = true;
} else if (exploringChest) {
loot(game, keyValue - 1);
exploringChest = false;
turnConsumed = true;
}
} else if (key == KeyCode.N) {
game.displayMessage("Please enter your name: ");
writing = true;
} else if (key == KeyCode.R) {
turnConsumed = nonMeleeAttack(game, getVision(), Attack.RANGED, "ranged");
} else if (key == KeyCode.F) {
turnConsumed = nonMeleeAttack(game, getVision() / 2 + getVision() % 2 == 0 ? 0 : 1, Attack.MAGIC, "magic");
}
showStatus(game);
return turnConsumed;
}
/**
* 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
*/
private boolean nonMeleeAttack(IGame game, int range, Attack type, String weapon) {
boolean turnConsumed = false;
IItem item = null;
switch (type) {
case RANGED:
item = getItem(IRangedWeapon.class);
break;
case MAGIC:
item = getItem(IMagicWeapon.class);
}
if (item == null) {
game.displayMessage("You do not have a " + weapon + " weapon.");
} else {
turnConsumed = rangedAttack(game, range, type);
if (!turnConsumed) {
game.displayMessage("No enemies within range.");
}
}
return turnConsumed;
}
/**
* Lets the user write his/her name.
*
* @param game An IGame object
* @param key The key pressed
*/
private void write(IGame game, KeyCode key) {
if (key == KeyCode.BACK_SPACE) {
if (text.length() > 0) {
text = text.substring(0, text.length() - 1);
game.displayMessage("Please enter your name: " + text);
}
} else if (key != KeyCode.ENTER) {
if (key == KeyCode.SPACE) {
text += " ";
} else {
text += key.getName();
}
game.displayMessage("Please enter your name: " + text);
} else {
name = text.toLowerCase();
text = "";
game.displayMessage("Name set.");
writing = false;
}
}
/**
* 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
*/
private boolean interactInit(IGame game) {
List<IItem> 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.
openChest(game, items);
} else if (item instanceof IStatic && item instanceof StairsUp) {
((Game)game).goUp();
return true;
} else if (item instanceof IStatic && item instanceof StairsDown) {
((Game)game).goDown();
return true;
} else {
if (items.size() == 1) {
pickUp(game, 0);
return true;
} else {
game.displayMessage("Items on this tile:" + niceList(items, 5));
picking = true;
}
}
}
return false;
}
/**
* Uses the first consumable from the player's inventory
*
* @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);
if (consumable != null) {
hp += consumable.hpIncrease();
if (hp > getMaxHealth()) {
hp = getMaxHealth();
}
attack += consumable.attackIncrease();
defence += consumable.defenceIncrease();
equipped.remove(consumable);
game.displayMessage("Used " + consumable.getName());
return true;
} else {
game.displayMessage("You don't have any consumables.");
return false;
}
}
/**
* Lists the contents of a chest, an makes the player ready to loot.
*
* @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);
items = container.getContent();
game.displayMessage(container.getInteractMessage() + niceList(items, 10));
exploringChest = true;
}
/**
* 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
*/
private String niceList(List<IItem> 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()));
}
return msg.toString();
}
/**
* 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
*/
private boolean dropInit(IGame game) {
if (equipped.size() == 1) {
drop(game, 0);
return true;
} else if (equipped.size() < 1) {
game.displayMessage("You have nothing to drop");
} else {
game.displayMessage("Items to drop:" + niceList(equipped.getContent(), equipped.getContent().size()));
dropping = true;
}
return false;
}
/**
* Picks up an item at index i.
*
* @param game An IGame object
* @param i The wanted index
*/
private void pickUp(IGame game, int i) {
if (equipped.hasSpace()) {
List<IItem> items = game.getLocalItems();
if (items.size() >= i) {
IItem pickedUp = game.pickUp(items.get(i));
if (pickedUp != null) {
equipped.add(pickedUp);
game.displayMessage("Picked up " + pickedUp.getName());
} else {
game.displayMessage("The item could not be picked up.");
}
} else {
game.displayMessage("That item does not exist.");
}
} else {
game.displayMessage("Your inventory is full.");
}
}
/**
* Takes an item from a chest, and gives it to the player.
*/
private void loot(IGame game, int i) {
if (equipped.hasSpace()) {
IContainer container = getStaticContainer(game);
if (container != null && i < container.getContent().size()) {
IItem loot = container.getContent().get(i);
equipped.add(loot);
container.remove(i);
game.displayMessage("Looted " + loot.getName());
}
} else {
game.displayMessage("Your inventory is full.");
}
}
/**
* Gets any static containers on the current tile.
*
* @param game An IGame object
* @return A static container
*/
private IContainer getStaticContainer(IGame game) {
List<IItem> items = game.getLocalItems();
if (items.size() < 1) {
return null;
}
IItem item = items.get(0);
if (item instanceof IStatic && item instanceof IContainer) {
return (IContainer) item;
} else {
return null;
}
}
/**
* Drops an item at index i.
*
* @param game An IGame object
* @param i The wanted index
*/
private void drop(IGame game, int i) {
if (!equipped.isEmpty() && equipped.size() > i) {
IContainer container = getStaticContainer(game);
if (container != null) {
if (container.addItem(equipped.get(i))) {
game.displayMessage(equipped.get(i).getName() + " stored in " + container.getName());
equipped.remove(i);
return;
} else {
game.displayMessage(container.getName() + " is full.");
return;
}
}
if (game.drop(equipped.get(i))) {
equipped.remove(i);
game.displayMessage("Item dropped.");
} else {
game.displayMessage("The ground rejected the item.");
}
} else {
game.displayMessage("You have nothing to drop.");
}
}
/**
* Updates the status bar with the Player's current stats.
*
* @param game An IGame object
*/
private void showStatus(IGame 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)
);
printInventory(game);
}
/**
* Prints all items in the player's inventory.
*
* @param game An IGame object
*/
private void printInventory(IGame 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:");
for (int i = 0; i < items.size(); i++) {
printer.printAt(Main.COLUMN_RIGHTSIDE_START, 13 + i, items.get(i).getName());
}
}
/**
* Changes the first character in a string to uppercase.
*
* @param input The input string
* @return The input string with the first character uppercased
*/
private String firstCharToUpper(String input) {
if (input.length() < 1) {
return input;
} else {
return Character.toUpperCase(input.charAt(0)) + input.substring(1);
}
}
/**
* Lets the user move or attack if possible.
*
* @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();
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.");
}
}
@Override
public int getAttack() {
IBuffItem buff = (IBuffItem)getItem(IBuffItem.class);
if (buff != null) {
return attack + buff.getBuffDamage();
} else {
return attack;
}
}
/**
* Gets the attack with added weapon attack
*
* @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);
if (weapon != null) {
return getAttack() + weapon.getWeaponAttack();
} else {
return getAttack();
}
}
@Override
public int getDamage() {
return 10;
}
/**
* Gets the damage with added weapon damage
*
* @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);
if (weapon != null) {
return getDamage() + weapon.getWeaponDamage();
} else {
return getDamage();
}
}
@Override
public IItem getItem(Class<?> type) {
for (IItem item : equipped.getContent()) {
if (type.isInstance(item)) {
return item;
}
}
return null;
}
@Override
public int getCurrentHealth() {
return hp;
}
@Override
public int getDefence() {
IBuffItem buff = (IBuffItem)getItem(IBuffItem.class);
if (buff != null) {
return defence + buff.getBuffDamage();
} else {
return defence;
}
}
@Override
public int getMaxHealth() {
return 1000;
}
@Override
public String getName() {
return firstCharToUpper(name);
}
@Override
public int getSize() {
return 10;
}
@Override
public String getPrintSymbol() {
return "\u001b[96m" + "@" + "\u001b[0m";
}
@Override
public String getSymbol() {
return "@";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
hp -= amount;
showStatus(game);
if (hp < 1) {
game.displayStatus("Game Over");
}
return amount;
}
@Override
public int getVision() {
IBuffItem item = (IBuffItem) getItem(IBuffItem.class);
if (item != null) {
return 3 + item.getBuffVisibility();
} else {
return 3;
}
}
/**
* 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
*/
private boolean rangedAttack(IGame game, int range, Attack type) {
List<ILocation> neighbours = game.getVisible();
for (ILocation neighbour : neighbours) {
if (game.getMap().hasActors(neighbour)) {
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.
if (actor instanceof INonPlayer && current.gridDistanceTo(neighbour) <= range) {
GridDirection dir = dirs.get(0); //Only ever has one item
game.rangedAttack(dir, actor, type);
return true;
}
}
}
return false;
}
}

View File

@@ -0,0 +1,41 @@
package inf101.v18.rogue101.objects;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.items.IStatic;
public class StairsDown implements IItem, IStatic {
@Override
public int getCurrentHealth() {
return 0;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 0;
}
@Override
public String getName() {
return "Stairs going downward";
}
@Override
public int getSize() {
return 100;
}
@Override
public String getSymbol() {
return ">";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
return 0;
}
}

View File

@@ -0,0 +1,41 @@
package inf101.v18.rogue101.objects;
import inf101.v18.rogue101.game.IGame;
import inf101.v18.rogue101.items.IStatic;
public class StairsUp implements IItem, IStatic {
@Override
public int getCurrentHealth() {
return 0;
}
@Override
public int getDefence() {
return 0;
}
@Override
public int getMaxHealth() {
return 0;
}
@Override
public String getName() {
return "Stairs going upward";
}
@Override
public int getSize() {
return 100;
}
@Override
public String getSymbol() {
return "<";
}
@Override
public int handleDamage(IGame game, IItem source, int amount) {
return 0;
}
}

View File

@@ -0,0 +1,50 @@
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

@@ -0,0 +1,226 @@
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.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) {
Media sound = new Media(url.toString());
MediaPlayer mediaPlayer = new MediaPlayer(sound);
mediaPlayer.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,16 @@
package inf101.v18.rogue101.states;
import java.util.Random;
/**
* An enum to distinguish different enemies of the same type.
*/
public enum Age {
TODDLER, CHILD, TEEN, ADULT, ELDER;
private static final Random random = new Random();
public static Age getRandom() {
return values()[random.nextInt(values().length)];
}
}

View File

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

View File

@@ -0,0 +1,16 @@
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

@@ -0,0 +1,16 @@
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,53 @@
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);
}

View File

@@ -0,0 +1,35 @@
package inf101.v18.util.generators;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import inf101.v18.util.IGenerator;
public abstract class AbstractGenerator<T> implements IGenerator<T> {
private static final Random commonRandom = new Random();
@Override
public T generate() {
return generate(commonRandom);
}
@Override
public List<T> generateEquals(int n) {
return generateEquals(commonRandom, n);
}
@Override
public List<T> generateEquals(Random r, int n) {
long seed = r.nextLong();
List<T> list = new ArrayList<T>();
for (int i = 0; i < n; i++) {
list.add(generate(new Random(seed)));
}
return list;
}
}

View File

@@ -0,0 +1,46 @@
package inf101.v18.util.generators;
import inf101.v18.grid.IArea;
import inf101.v18.grid.RectArea;
import inf101.v18.util.IGenerator;
import java.util.Random;
public class AreaGenerator extends AbstractGenerator<IArea> {
/**
* Generator for the x-coordinate
*/
private final IGenerator<Integer> xGenerator;
/**
* Generator for the y-coordinate
*/
private final IGenerator<Integer> yGenerator;
/**
* Generate random Areas between (1,1) and (100,100)
*/
public AreaGenerator() {
this.xGenerator = new IntGenerator(1, 100);
this.yGenerator = new IntGenerator(1, 100);
}
/**
* Generate random Areas between (0,0) and (maxWidth,maxHeight)
*
* @param maxWidth
* @param maxHeight
*/
public AreaGenerator(int maxWidth, int maxHeight) {
if (maxWidth < 1 || maxHeight < 1) {
throw new IllegalArgumentException("Width and height must be 0 or greater");
}
this.xGenerator = new IntGenerator(1, maxWidth);
this.yGenerator = new IntGenerator(1, maxHeight);
}
@Override
public IArea generate(Random r) {
return new RectArea(xGenerator.generate(r), yGenerator.generate(r));
}
}

View File

@@ -0,0 +1,87 @@
package inf101.v18.util.generators;
import java.util.Random;
/**
* Generator for doubles, with uniform distribution.
*
* Will never generate positive or negative infinity or NaN.
*
* @author anya
*
*/
public class DoubleGenerator extends AbstractGenerator<Double> {
private final double minValue;
private final double diff;
/**
* Make a generator for doubles between 0.0 (inclusive) and 1.0 (exclusive).
*/
public DoubleGenerator() {
this.minValue = 0;
diff = 1.0;
}
/**
* Make a generator for positive doubles from 0 (inclusive) to maxValue
* (exclusive).
*
* @param maxValue
* The max value, or 0 for the full range of positive doubles
*/
public DoubleGenerator(double maxValue) {
if (maxValue < 0.0) {
throw new IllegalArgumentException("maxValue must be positive or 0.0");
}
this.minValue = 0.0;
double mv = Double.MAX_VALUE;
if (maxValue != 0.0) {
mv = maxValue;
}
diff = mv - minValue;
}
/**
* Make a generator for numbers from minValue (inclusive) to maxValue
* (exclusive).
*
* Due to the way the numbers are constructed, the range from minValue to
* maxValue can only span half the total range of available double values. If
* the range is too large the bounds will be divided by two (you can check
* whether they range is too large by checking
* <code>Double.isInfinite(maxValue-minValue)</code>).
*
* @param minValue
* The minimum value
* @param maxValue
* The maximum value, minValue < maxValue
*/
public DoubleGenerator(double minValue, double maxValue) {
if (minValue >= maxValue) {
throw new IllegalArgumentException("minValue must be less than maxValue");
}
if (Double.isInfinite(minValue)) {
minValue = -Double.MAX_VALUE / 2.0;
}
if (Double.isInfinite(maxValue)) {
maxValue = Double.MAX_VALUE / 2.0;
}
if (Double.isInfinite(maxValue - minValue)) {
maxValue /= 2.0;
minValue /= 2.0;
}
this.minValue = minValue;
diff = maxValue - minValue;
assert !Double.isInfinite(diff);
}
@Override
public Double generate(Random rng) {
double d = rng.nextDouble();
return minValue + (d * diff);
}
}

View File

@@ -0,0 +1,38 @@
package inf101.v18.util.generators;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
public class ElementGenerator<T> extends AbstractGenerator<T> {
private List<T> elts;
/**
* New ElementGenerator, will pick a random element from a collection.
*
* @requires collection must not be empty
*/
public ElementGenerator(Collection<T> elts) {
if (elts.size() == 0)
throw new IllegalArgumentException();
this.elts = new ArrayList<>(elts);
}
/**
* New ElementGenerator, will pick a random element from a list.
*
* @requires list must not be empty
*/
public ElementGenerator(List<T> elts) {
if (elts.size() == 0)
throw new IllegalArgumentException();
this.elts = elts;
}
@Override
public T generate(Random r) {
return elts.get(r.nextInt(elts.size()));
}
}

View File

@@ -0,0 +1,21 @@
package inf101.v18.util.generators;
import java.util.List;
import inf101.v18.grid.GridDirection;
public class GridDirectionGenerator extends ElementGenerator<GridDirection> {
/**
* New DirectionGenerator, will generate directions between 0° and 360°
*/
public GridDirectionGenerator() {
super(GridDirection.EIGHT_DIRECTIONS);
}
/**
* New DirectionGenerator, will generate directions between minValue and maxVaue
*/
public GridDirectionGenerator(List<GridDirection> dirs) {
super(dirs);
}
}

View File

@@ -0,0 +1,78 @@
package inf101.v18.util.generators;
import inf101.v18.grid.IGrid;
import inf101.v18.grid.MyGrid;
import inf101.v18.util.IGenerator;
import java.util.Random;
public class GridGenerator<T> extends AbstractGenerator<IGrid<T>> {
/**
* Generator for the width of a random grid
*/
private final IGenerator<Integer> widthGenerator;
/**
* Generator for the height of a random grid
*/
private final IGenerator<Integer> heightGenerator;
/**
* Generator for one element of a random grid
*/
private final IGenerator<T> elementGenerator;
/**
* Generator for random 2D grids. Each dimension will be from 1 to 100.
*
* @param elementGenerator
* Generator for the elements
*/
public GridGenerator(IGenerator<T> elementGenerator) {
this.elementGenerator = elementGenerator;
this.widthGenerator = new IntGenerator(1, 100);
this.heightGenerator = new IntGenerator(1, 100);
}
/**
* Generator for random 2D grids using the supplied generators to generate width
* and height.
*
* @param elementGenerator
* Generator for the elements
* @param widthGenerator
* Should only generate positive numbers
* @param heightGenerator
* Should only generate positive numbers
*/
public GridGenerator(IGenerator<T> elementGenerator, IGenerator<Integer> widthGenerator,
IGenerator<Integer> heightGenerator) {
this.elementGenerator = elementGenerator;
this.widthGenerator = widthGenerator;
this.heightGenerator = heightGenerator;
}
/**
* Generator for random 2D grids with the given max dimensions.
*
* @param elementGenerator
* Generator for the elements
* @param maxWidth
* @param maxHeight
*/
public GridGenerator(IGenerator<T> elementGenerator, int maxWidth, int maxHeight) {
if (maxWidth < 1 || maxHeight < 1) {
throw new IllegalArgumentException("Width and height must be 1 or greater");
}
this.elementGenerator = elementGenerator;
this.widthGenerator = new IntGenerator(1, maxWidth);
this.heightGenerator = new IntGenerator(1, maxHeight);
}
@Override
public IGrid<T> generate(Random r) {
int w = widthGenerator.generate(r);
int h = heightGenerator.generate(r);
return new MyGrid<>(w, h, (l) -> elementGenerator.generate(r));
}
}

View File

@@ -0,0 +1,88 @@
package inf101.v18.util.generators;
import java.util.Random;
public class IntGenerator extends AbstractGenerator<Integer> {
/**
* Generate a random long in the interval [0,n)
*
* @param rng
* A random generator
* @param n
* The maximum value (exclusive)
* @return A uniformly distributed random integer in the range 0 (inclusive) to
* n (exclusive)
*
* @author Adapted from JDK implementation for nextInt(n)
*/
public static long nextLong(Random rng, long n) {
if (n <= 0) {
throw new IllegalArgumentException("n must be positive");
}
long bits, val;
do {
bits = rng.nextLong() & ~Long.MIN_VALUE; // force to positive
val = bits % n;
} while (bits - val + (n - 1L) < 0L);
return val;
}
private final long minValue;
private final long diff;
/**
* Make a generator for the full range of integers.
*/
public IntGenerator() {
this.minValue = Integer.MIN_VALUE;
long maxValue = Integer.MAX_VALUE + 1L; // generate up to and including
// Integer.MAX_VALUE
diff = maxValue - minValue;
}
/**
* Make a generator for positive numbers from 0 (inclusive) to maxValue
* (exclusive).
*
* @param maxValue
* The max value, or 0 for the full range of positive integers
*/
public IntGenerator(int maxValue) {
if (maxValue < 0) {
throw new IllegalArgumentException("maxValue must be positive or 0");
}
this.minValue = 0;
long mv = Integer.MAX_VALUE + 1L; // generate up to and including
// Integer.MAX_VALUE
if (maxValue != 0) {
mv = maxValue;
}
diff = mv - minValue;
}
/**
* Make a generator for numbers from minValue (inclusive) to maxValue
* (exclusive).
*
* @param minValue
* The minimum value
* @param maxValue
* The maximum value, minValue < maxValue
*/
public IntGenerator(int minValue, int maxValue) {
if (minValue >= maxValue) {
throw new IllegalArgumentException("minValue must be less than maxValue");
}
this.minValue = minValue;
diff = ((long) maxValue) - ((long) minValue);
}
@Override
public Integer generate(Random rng) {
long r = minValue + nextLong(rng, diff);
return (int) r;
}
}

View File

@@ -0,0 +1,44 @@
package inf101.v18.util.generators;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import inf101.v18.util.IGenerator;
public class ListGenerator<T> extends AbstractGenerator<List<T>> {
/**
* Generator for the length of the list
*/
private final IGenerator<Integer> lengthGenerator;
/**
* Generator for one element of a random grid
*/
private final IGenerator<T> elementGenerator;
public ListGenerator(IGenerator<T> elementGenerator) {
this.elementGenerator = elementGenerator;
this.lengthGenerator = new IntGenerator(1, 100);
}
public ListGenerator(IGenerator<T> elementGenerator, int maxLength) {
if (maxLength < 1) {
throw new IllegalArgumentException("Length must be 1 or greater");
}
this.elementGenerator = elementGenerator;
this.lengthGenerator = new IntGenerator(1, maxLength);
}
@Override
public List<T> generate(Random r) {
int l = lengthGenerator.generate(r);
List<T> result = new ArrayList<>(l);
for (int i = 0; i < l; i++) {
result.add(elementGenerator.generate(r));
}
return result;
}
}

View File

@@ -0,0 +1,23 @@
package inf101.v18.util.generators;
import java.util.Random;
import inf101.v18.grid.IArea;
import inf101.v18.grid.ILocation;
public class LocationGenerator extends AbstractGenerator<ILocation> {
private final IArea area;
/**
* New LocationGenerator, will generate locations within the area
*/
public LocationGenerator(IArea area) {
this.area = area;
}
@Override
public ILocation generate(Random r) {
return area.location(r.nextInt(area.getWidth()), r.nextInt(area.getHeight()));
}
}

View File

@@ -0,0 +1,59 @@
package inf101.v18.util.generators;
import java.util.Random;
public class StringGenerator extends AbstractGenerator<String> {
private final int minLength;
private final int maxLength;
public StringGenerator() {
this.minLength = 0;
this.maxLength = 15;
}
public StringGenerator(int maxLength) {
if (maxLength < 0) {
throw new IllegalArgumentException("maxLength must be positive or 0");
}
this.minLength = 0;
this.maxLength = maxLength;
}
public StringGenerator(int minLength, int maxLength) {
if (minLength >= maxLength) {
throw new IllegalArgumentException("minLength must be less than maxLength");
}
this.minLength = minLength;
this.maxLength = maxLength;
}
@Override
public String generate(Random r) {
int len = r.nextInt(maxLength - minLength) + minLength;
StringBuilder b = new StringBuilder();
for (int i = 0; i < len; i++) {
b.append(generateChar(r));
}
return b.toString();
}
public char generateChar(Random r) {
int kind = r.nextInt(7);
switch (kind) {
case 0:
case 1:
case 2:
return (char) ('a' + r.nextInt(26));
case 3:
case 4:
return (char) ('A' + r.nextInt(26));
case 5:
return (char) ('0' + r.nextInt(10));
case 6:
return (char) (' ' + r.nextInt(16));
}
return ' ';
}
}