diff --git a/app/src/main/java/fr/iutfbleau/sae/Line.java b/app/src/main/java/fr/iutfbleau/sae/Line.java new file mode 100644 index 0000000..7bde293 --- /dev/null +++ b/app/src/main/java/fr/iutfbleau/sae/Line.java @@ -0,0 +1,105 @@ +package fr.iutfbleau.sae; + +import android.graphics.Point; + +import androidx.annotation.NonNull; + +import java.io.Serializable; +import java.util.Iterator; + + +public class Line implements Iterable, Serializable { + + private final Cell start; + + private final Cell end; + + + public Line(Cell start, Cell end) { + if (!isValid(start, end)) + throw new IllegalArgumentException("Invalid line."); + + this.start = new Cell(start); + this.end = new Cell(end); + } + + + public Line(Line line) { + this.start = line.getStart(); + this.end = line.getEnd(); + } + + + public static boolean isValid(Cell start, Cell end) { + int dx = end.x - start.x; + int dy = end.y - start.y; + + if (dx == 0 && dy == 0) + return false; + + boolean horizontal = Math.abs(dx) == 4 || dx == 0; + boolean vertical = Math.abs(dy) == 4 || dy == 0; + + return horizontal && vertical; + } + + + public Cell getStart() { + return new Cell(this.start); + } + + + public Cell getEnd() { + return new Cell(this.end); + } + + + public boolean extendsLine(Line line) { + int dx = this.end.x - this.start.x; + int dy = this.end.y - this.start.y; + + int ldx = line.end.x - line.start.x; + int ldy = line.end.y - line.start.y; + + if (line.start.equals(this.start) || line.end.equals(this.end)) + return dx == -ldx && dy == -ldy; + else if (line.end.equals(this.start) || line.start.equals(this.end)) + return dx == ldx && dy == ldy; + else + return false; + } + + + @Override + public int hashCode() { + return this.start.hashCode() + this.end.hashCode(); + } + + + @Override + public boolean equals(Object object) { + if (object == this) + return true; + if (object == null || this.getClass() != object.getClass()) + return false; + + Line line = (Line) object; + + return (line.start.equals(this.start) && line.end.equals(this.end)) + || (line.end.equals(this.start) && line.start.equals(this.end)); + } + + + @NonNull + @Override + public Iterator iterator() { + return new LineIterator(this); + } + + + @NonNull + @Override + public String toString() { + return this.start + " -> " + this.end; + } +}