Squashed 'solution/H00/' content from commit 38bca6b

git-subtree-dir: solution/H00
git-subtree-split: 38bca6b3b94b8413dd3377f62b730a6fd4fb892d
This commit is contained in:
Oshgnacknak 2025-01-11 16:41:04 +01:00
commit ed3f0fe4d0
26 changed files with 1140 additions and 0 deletions

12
.editorconfig Normal file
View file

@ -0,0 +1,12 @@
# Editor configuration, see https://editorconfig.org
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
[{*.yml,*.json}]
indent_size = 2

88
.gitignore vendored Normal file
View file

@ -0,0 +1,88 @@
### Intellij ###
.idea/
*.iws
/out/
*.iml
.idea_modules/
atlassian-ide-plugin.xml
### VS-Code ###
.vscode/
.VSCodeCounter/
### Eclipse ###
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
.externalToolBuilders/
*.launch
.factorypath
.recommenders/
.apt_generated/
.project
.classpath
### Linux ###
*~
.fuse_hidden*
.directory
.Trash-*
.nfs*
### macOS ###
.DS_Store
.AppleDouble
.LSOverride
Icon
._*
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
*.stackdump
[Dd]esktop.ini
$RECYCLE.BIN/
*.lnk
### Gradle ###
.gradle
/build/
out/
gradle-app.setting
!gradle-wrapper.jar
.gradletasknamecache
*.hprof
screenshots/
jagr.conf

4
README.md Normal file
View file

@ -0,0 +1,4 @@
# Musterlösung zu Hausübung 00
Beachten Sie die Hinweise zum Herunterladen, Importieren, Bearbeitern, Exportieren und Hochladen in unserem
[Studierenden-Guide](https://wiki.tudalgo.org/)

41
build.gradle.kts Normal file
View file

@ -0,0 +1,41 @@
plugins {
alias(libs.plugins.algomate)
alias(libs.plugins.style)
}
version = file("version").readLines().first()
exercise {
assignmentId.set("h00")
}
submission {
// ACHTUNG!
// Setzen Sie im folgenden Bereich Ihre TU-ID (NICHT Ihre Matrikelnummer!), Ihren Nachnamen und Ihren Vornamen
// in Anführungszeichen (z.B. "ab12cdef" für Ihre TU-ID) ein!
// BEISPIEL:
// studentId = "ab12cdef"
// firstName = "sol_first"
// lastName = "sol_last"
studentId = "ab12cdef"
firstName = "sol_first"
lastName = "sol_last"
// Optionally require own tests for mainBuildSubmission task. Default is false
requireTests = false
}
dependencies {
implementation(libs.fopbot)
}
jagr {
graders {
val graderPublic by getting
val graderPrivate by creating {
parent(graderPublic)
graderName.set("FOP-2425-H00-Private")
rubricProviderName.set("h00.H00_RubricProvider")
}
}
}

View file

@ -0,0 +1,6 @@
[plugins]
algomate = { id = "org.tudalgo.algomate", version = "0.7.1" }
style = { id = "org.sourcegrade.style", version = "3.0.0" }
[libraries]
fopbot = {module = "org.tudalgo:fopbot", version = "0.8.1"}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

245
gradlew vendored Executable file
View file

@ -0,0 +1,245 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored Normal file
View file

@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

11
settings.gradle.kts Normal file
View file

@ -0,0 +1,11 @@
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
// mavenLocal()
maven("https://s01.oss.sonatype.org/content/repositories/snapshots")
maven("https://jitpack.io")
mavenCentral()
}
}
rootProject.name = "H00-Root"

View file

@ -0,0 +1,90 @@
package h00;
import org.sourcegrade.jagr.api.rubric.Criterion;
import org.sourcegrade.jagr.api.rubric.JUnitTestRef;
import org.sourcegrade.jagr.api.rubric.Rubric;
import org.sourcegrade.jagr.api.rubric.RubricProvider;
import org.tudalgo.algoutils.tutor.general.json.JsonParameterSet;
import static org.tudalgo.algoutils.tutor.general.jagr.RubricUtils.criterion;
public class H00_RubricProvider implements RubricProvider {
public static final Rubric RUBRIC = Rubric.builder()
.title("H00 | Hands on mit Java & FopBot").addChildCriteria(
Criterion.builder()
.shortDescription("H0.1 | Matrikelnummer in Moodle")
.build(),
Criterion.builder()
.shortDescription("H0.4 | Initializing FOPBot")
.addChildCriteria(
criterion(
"Der Konstruktor von Robot wurde für Alfred und Kaspar mit korrekten Parametern aufgerufen.",
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testRobotInit", JsonParameterSet.class))
)
)
.build(),
Criterion.builder()
.shortDescription("H0.5 | Lets start with turning")
.addChildCriteria(
criterion(
"Beide Roboter haben die korrekte Anzahl an Drehungen durch geführt.",
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_5_1", JsonParameterSet.class)),
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_5_2", JsonParameterSet.class)),
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_5_3", JsonParameterSet.class))
),
criterion(
"Es wurden bis hierhin genau eine for- und eine while-Schleife benutzt.",
-1,
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_5VA"))
)
)
.minPoints(0)
.build(),
Criterion.builder()
.shortDescription("H0.6 | Now we move, put, and pick")
.addChildCriteria(
criterion(
"Beide Roboter haben die korrekten Bewegungen durchgeführt (move, turnLeft, pick, put).",
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_6_1", JsonParameterSet.class)),
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_6_2", JsonParameterSet.class)),
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_6_3", JsonParameterSet.class))
),
criterion(
"Es wurde genau eine zusätzliche for-Schleife benutzt.",
-1,
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_6VA"))
)
)
.minPoints(0)
.build(),
Criterion.builder()
.shortDescription("H0.7 | Lets repeat that")
.addChildCriteria(
criterion(
"Beide Roboter haben die korrekten Bewegungen durchgeführt (move, turnLeft, pick, put).",
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_7_1", JsonParameterSet.class)),
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_7_2", JsonParameterSet.class)),
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_7_3", JsonParameterSet.class))
),
criterion(
"Es wurden genau eine zusätzliche for-Schleife und zwei zusätzliche while-Schleifen benutzt.",
-1,
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_7VA"))
),
criterion(
"Die Läufervariable der for-Schleife verringert sich.",
-1,
JUnitTestRef.ofMethod(() -> MainTest.class.getDeclaredMethod("testH0_7VA_ForLoop"))
)
)
.minPoints(0)
.build()
).build();
@Override
public Rubric getRubric() {
return RUBRIC;
}
}

View file

@ -0,0 +1,264 @@
package h00;
import fopbot.Robot;
import fopbot.Transition;
import fopbot.World;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.sourcegrade.jagr.api.rubric.TestForSubmission;
import org.tudalgo.algoutils.tutor.general.SpoonUtils;
import org.tudalgo.algoutils.tutor.general.assertions.Context;
import org.tudalgo.algoutils.tutor.general.json.JsonParameterSet;
import org.tudalgo.algoutils.tutor.general.json.JsonParameterSetTest;
import spoon.reflect.code.CtFor;
import spoon.reflect.code.CtIf;
import spoon.reflect.code.CtLoop;
import spoon.reflect.code.CtStatement;
import spoon.reflect.code.CtUnaryOperator;
import spoon.reflect.code.CtWhile;
import spoon.reflect.code.UnaryOperatorKind;
import spoon.reflect.declaration.CtElement;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static h00.Utils.RobotSpec.ALFRED;
import static h00.Utils.RobotSpec.KASPAR;
import static h00.Utils.deserializeRobotActions;
import static h00.Utils.getRobot;
import static h00.Utils.subtaskToIndex;
import static h00.Utils.toRobotActions;
import static org.tudalgo.algoutils.tutor.general.assertions.Assertions2.*;
@TestForSubmission
public class MainTest {
private static final List<Map<Utils.RobotSpec, List<Transition>>> SUBTASK_ROBOT_TRANSITIONS = new ArrayList<>();
private static final List<List<CtElement>> CT_ELEMENTS = new ArrayList<>();
@BeforeAll
public static void setup() {
Main.delay = 0;
for (int i = 0; i < 10; i++) {
setup(i);
}
CtType<?> ctType = SpoonUtils.getType(Main.class.getName());
CtMethod<?> ctMethod = ctType.getMethodsByName("main").getFirst();
List<CtElement> ctElements = ctMethod.getBody().getDirectChildren();
int previousSplit = 0;
for (int i = 0; i < ctElements.size(); i++) {
CtElement ctElement = ctElements.get(i);
if (ctElement instanceof CtIf ctIf && ctIf.getCondition().toStringDebug().strip().matches(Main.class.getName() + "\\.runToSubtask == \\d+")) {
CT_ELEMENTS.add(ctElements.subList(previousSplit, i));
previousSplit = i + 1;
}
if (i == ctElements.size() - 1) {
CT_ELEMENTS.add(ctElements.subList(previousSplit, ctElements.size()));
}
}
}
private static void setup(int subtask) {
Main.runToSubtask = subtask;
try {
Main.main(new String[0]);
} catch (Exception e) {
System.err.println("Exception occurred while invoking main method, trying to continue...");
e.printStackTrace(System.err);
}
List<Transition> kasperTransitions = World.getGlobalWorld()
.getTrace(getRobot(KASPAR))
.getTransitions();
List<Transition> alfredTransitions = World.getGlobalWorld()
.getTrace(getRobot(ALFRED))
.getTransitions();
int kasperPreviousTransitions = 0;
int alfredPreviousTransitions = 0;
if (subtask > 0) {
kasperPreviousTransitions = SUBTASK_ROBOT_TRANSITIONS.stream()
.mapToInt(map -> map.get(KASPAR).size())
.sum() - subtask; // ignore NONE actions
alfredPreviousTransitions = SUBTASK_ROBOT_TRANSITIONS.stream()
.mapToInt(map -> map.get(ALFRED).size())
.sum() - subtask; // ignore NONE actions
}
Map<Utils.RobotSpec, List<Transition>> currentRobotActions = Map.of(
KASPAR, kasperTransitions.subList(kasperPreviousTransitions, kasperTransitions.size()),
ALFRED, alfredTransitions.subList(alfredPreviousTransitions, alfredTransitions.size())
);
SUBTASK_ROBOT_TRANSITIONS.add(currentRobotActions);
}
@ParameterizedTest
@JsonParameterSetTest("H0_4.json")
public void testRobotInit(JsonParameterSet params) {
for (Utils.RobotSpec robotSpec : Utils.RobotSpec.values()) {
List<Transition> transitions = SUBTASK_ROBOT_TRANSITIONS.getFirst().get(robotSpec);
Robot robot = transitions.getFirst().robot; // getRobot(RobotSpec) won't work because it already moved
Context context = contextBuilder()
.add("reference robot", robotSpec)
.add("actual robot", robot)
.build();
assertEquals(robotSpec.initialX, robot.getX(), context, result -> robotSpec.name + "'s x-coordinate is incorrect");
assertEquals(robotSpec.initialY, robot.getY(), context, result -> robotSpec.name + "'s y-coordinate is incorrect");
assertEquals(robotSpec.initialDirection, robot.getDirection(), context, result -> robotSpec.name + "'s direction is incorrect");
assertEquals(robotSpec.initialCoins, robot.getNumberOfCoins(), context, result -> robotSpec.name + " has an incorrect number of coins");
assertEquals(robotSpec.robotFamily, robot.getRobotFamily(), context, result -> robotSpec.name + "'s RobotFamily is incorrect");
}
testMovements(params, "H0.4");
}
@ParameterizedTest
@JsonParameterSetTest("H0_5_1.json")
public void testH0_5_1(JsonParameterSet params) {
testMovements(params, "H0.5.1");
}
@ParameterizedTest
@JsonParameterSetTest("H0_5_2.json")
public void testH0_5_2(JsonParameterSet params) {
testMovements(params, "H0.5.2");
}
@ParameterizedTest
@JsonParameterSetTest("H0_5_3.json")
public void testH0_5_3(JsonParameterSet params) {
testMovements(params, "H0.5.3");
}
@Test
public void testH0_5VA() {
assertFalse(CT_ELEMENTS.get(subtaskToIndex("H0.5.1"))
.stream()
.anyMatch(CtLoop.class::isInstance),
emptyContext(),
result -> "H0.5.1 uses a loop");
assertTrue(CT_ELEMENTS.get(subtaskToIndex("H0.5.2"))
.stream()
.anyMatch(CtFor.class::isInstance),
emptyContext(),
result -> "H0.5.2 does not use a for-loop");
assertTrue(CT_ELEMENTS.get(subtaskToIndex("H0.5.3"))
.stream()
.anyMatch(CtWhile.class::isInstance),
emptyContext(),
result -> "H0.5.3 does not use a while-loop");
}
@ParameterizedTest
@JsonParameterSetTest("H0_6_1.json")
public void testH0_6_1(JsonParameterSet params) {
testMovements(params, "H0.6.1");
}
@ParameterizedTest
@JsonParameterSetTest("H0_6_2.json")
public void testH0_6_2(JsonParameterSet params) {
testMovements(params, "H0.6.2");
}
@ParameterizedTest
@JsonParameterSetTest("H0_6_3.json")
public void testH0_6_3(JsonParameterSet params) {
testMovements(params, "H0.6.3");
}
@Test
public void testH0_6VA() {
assertFalse(CT_ELEMENTS.get(subtaskToIndex("H0.6.1"))
.stream()
.anyMatch(CtLoop.class::isInstance),
emptyContext(),
result -> "H0.6.1 uses a loop");
assertFalse(CT_ELEMENTS.get(subtaskToIndex("H0.6.2"))
.stream()
.anyMatch(CtLoop.class::isInstance),
emptyContext(),
result -> "H0.6.2 uses a loop");
assertTrue(CT_ELEMENTS.get(subtaskToIndex("H0.6.3"))
.stream()
.anyMatch(CtFor.class::isInstance),
emptyContext(),
result -> "H0.6.3 does not use a for-loop");
}
@ParameterizedTest
@JsonParameterSetTest("H0_7_1.json")
public void testH0_7_1(JsonParameterSet params) {
testMovements(params, "H0.7.1");
}
@ParameterizedTest
@JsonParameterSetTest("H0_7_2.json")
public void testH0_7_2(JsonParameterSet params) {
testMovements(params, "H0.7.2");
}
@ParameterizedTest
@JsonParameterSetTest("H0_7_3.json")
public void testH0_7_3(JsonParameterSet params) {
testMovements(params, "H0.7.3");
}
@Test
public void testH0_7VA() {
assertTrue(CT_ELEMENTS.get(subtaskToIndex("H0.7.1"))
.stream()
.anyMatch(CtWhile.class::isInstance),
emptyContext(),
result -> "H0.7.1 does not use a while-loop");
assertTrue(CT_ELEMENTS.get(subtaskToIndex("H0.7.2"))
.stream()
.anyMatch(CtWhile.class::isInstance),
emptyContext(),
result -> "H0.7.2 does not use a while-loop");
assertTrue(CT_ELEMENTS.get(subtaskToIndex("H0.7.3"))
.stream()
.anyMatch(CtFor.class::isInstance),
emptyContext(),
result -> "H0.7.3 does not use a for-loop");
}
@Test
public void testH0_7VA_ForLoop() {
CT_ELEMENTS.get(subtaskToIndex("H0.7.3"))
.stream()
.filter(CtFor.class::isInstance)
.map(CtFor.class::cast)
.findAny()
.ifPresentOrElse(ctFor -> {
List<CtStatement> updateStatements = ctFor.getForUpdate();
assertEquals(1, updateStatements.size(), emptyContext(),
result -> "Found more than one update statement in for-loop");
assertTrue(updateStatements.getFirst() instanceof CtUnaryOperator<?> op && op.getKind() == UnaryOperatorKind.POSTDEC,
emptyContext(),
result -> "Update statement does not use a postdecrement operator (i.e., i--)");
}, () -> fail(emptyContext(), result -> "No for loop found for task H0.7.3"));
}
/**
* Tests Kaspar's and Alfred's movements.
*
* @param params the expected movements (serialized)
* @param subtask the subtask (see markers in main method)
*/
private void testMovements(JsonParameterSet params, String subtask) {
for (Utils.RobotSpec robotSpec : Utils.RobotSpec.values()) {
List<Transition.RobotAction> expectedMovements = deserializeRobotActions(params.get(robotSpec.name));
List<Transition.RobotAction> actualMovements = toRobotActions(SUBTASK_ROBOT_TRANSITIONS.get(subtaskToIndex(subtask)).get(robotSpec));
assertEquals(expectedMovements, actualMovements, emptyContext(), result ->
robotSpec.name + "'s movements are incorrect for task " + subtask);
}
}
}

View file

@ -0,0 +1,103 @@
package h00;
import fopbot.Direction;
import fopbot.Robot;
import fopbot.RobotFamily;
import fopbot.Transition;
import fopbot.World;
import java.util.List;
public class Utils {
/**
* Information on {@link Robot}s needed for the exercise (id, name and expected initial values).
*/
public enum RobotSpec {
KASPAR(0, "Kaspar", 0, 0, Direction.DOWN, 4, RobotFamily.SQUARE_BLUE),
ALFRED(1, "Alfred", 0, 3, Direction.DOWN, 0, RobotFamily.SQUARE_GREEN);
public final int id;
public final String name;
public final int initialX;
public final int initialY;
public final Direction initialDirection;
public final int initialCoins;
public final RobotFamily robotFamily;
RobotSpec(int id, String name, int initialX, int initialY, Direction initialDirection, int initialCoins, RobotFamily rf) {
this.id = id;
this.name = name;
this.initialX = initialX;
this.initialY = initialY;
this.initialDirection = initialDirection;
this.initialCoins = initialCoins;
this.robotFamily = rf;
}
}
/**
* Get a specific robot from the world.
*
* @param robotSpec the {@link RobotSpec} describing the robot to get
* @return the robot
*/
public static Robot getRobot(RobotSpec robotSpec) {
return World.getGlobalWorld()
.getAllFieldEntities()
.stream()
.filter(Robot.class::isInstance)
.map(Robot.class::cast)
.filter(robot -> robot.getId().equals(Integer.toString(robotSpec.id)))
.findAny()
.orElseThrow();
}
/**
* Deserialize {@link fopbot.Transition.RobotAction} from their string representation.
*
* @param serializedRobotActions the serialized RobotActions
* @return a list of {@link fopbot.Transition.RobotAction}s
*/
public static List<Transition.RobotAction> deserializeRobotActions(List<String> serializedRobotActions) {
return serializedRobotActions.stream()
.map(Transition.RobotAction::valueOf)
.toList();
}
/**
* Maps {@link Transition}s to their respective {@link fopbot.Transition.RobotAction}s.
*
* @param transitions a list of Transitions
* @return a list of RobotActions
*/
public static List<Transition.RobotAction> toRobotActions(List<Transition> transitions) {
return transitions.stream()
.map(transition -> transition.action)
.toList();
}
/**
* Maps the subtask string to the corresponding index.
*
* @param subtask the subtask name
* @return the index
* @see MainTest#SUBTASK_ROBOT_TRANSITIONS
*/
public static int subtaskToIndex(String subtask) {
return switch (subtask) {
case "H0.4" -> 0;
case "H0.5.1" -> 1;
case "H0.5.2" -> 2;
case "H0.5.3" -> 3;
case "H0.6.1" -> 4;
case "H0.6.2" -> 5;
case "H0.6.3" -> 6;
case "H0.7.1" -> 7;
case "H0.7.2" -> 8;
case "H0.7.3" -> 9;
default -> -1;
};
}
}

View file

@ -0,0 +1,4 @@
[ {
"Kaspar" : [ "NONE" ],
"Alfred" : [ "NONE" ]
} ]

View file

@ -0,0 +1,4 @@
[ {
"Kaspar" : [ "NONE" ],
"Alfred" : [ "TURN_LEFT", "TURN_LEFT", "NONE" ]
} ]

View file

@ -0,0 +1,4 @@
[ {
"Kaspar" : [ "NONE" ],
"Alfred" : [ "TURN_LEFT", "TURN_LEFT", "NONE" ]
} ]

View file

@ -0,0 +1,4 @@
[ {
"Kaspar" : [ "TURN_LEFT", "NONE" ],
"Alfred" : [ "NONE" ]
} ]

View file

@ -0,0 +1,4 @@
[ {
"Kaspar" : [ "PUT_COIN", "MOVE", "MOVE", "MOVE", "TURN_LEFT", "NONE" ],
"Alfred" : [ "NONE" ]
} ]

View file

@ -0,0 +1,4 @@
[ {
"Kaspar" : [ "NONE" ],
"Alfred" : [ "MOVE", "MOVE", "MOVE", "PICK_COIN", "TURN_LEFT", "NONE" ]
} ]

View file

@ -0,0 +1,4 @@
[ {
"Kaspar" : [ "PUT_COIN", "MOVE", "MOVE", "MOVE", "TURN_LEFT", "NONE" ],
"Alfred" : [ "NONE" ]
} ]

View file

@ -0,0 +1,4 @@
[ {
"Kaspar" : [ "NONE" ],
"Alfred" : [ "MOVE", "MOVE", "MOVE", "PICK_COIN", "TURN_LEFT", "NONE" ]
} ]

View file

@ -0,0 +1,4 @@
[ {
"Kaspar" : [ "PUT_COIN", "MOVE", "MOVE", "MOVE", "TURN_LEFT", "NONE" ],
"Alfred" : [ "MOVE", "MOVE", "MOVE", "PICK_COIN", "TURN_LEFT", "NONE" ]
} ]

View file

@ -0,0 +1,4 @@
[ {
"Alfred" : [ "PUT_COIN", "MOVE", "PUT_COIN", "MOVE", "PUT_COIN", "MOVE", "TURN_LEFT", "NONE" ],
"Kaspar" : [ "NONE" ]
} ]

121
src/main/java/h00/Main.java Normal file
View file

@ -0,0 +1,121 @@
package h00;
import fopbot.Direction;
import fopbot.Robot;
import fopbot.RobotFamily;
import fopbot.World;
/**
* Main entry point in executing the program.
*/
public class Main {
/**
* The subtask to run.
*/
public static int runToSubtask = -1;
/**
* The world speed in milliseconds.
*/
public static int delay = 300;
/**
* Main entry point in executing the program.
*
* @param args program arguments, currently ignored
*/
public static void main(String[] args) {
// This sets up the FOPBot World with a 4x4 grid. (DO NOT TOUCH)
setupWorld();
// TODO: H0.4 - Initializing FOPBot
Robot kasper = new Robot(0, 0, Direction.DOWN, 4, RobotFamily.SQUARE_BLUE);
Robot alfred = new Robot(0, 3, Direction.DOWN, 0, RobotFamily.SQUARE_GREEN);
if (runToSubtask == 0) return; // DO NOT TOUCH!
// TODO: H0.5.1 - Turning with repeated instructions
alfred.turnLeft();
alfred.turnLeft();
if (runToSubtask == 1) return; // DO NOT TOUCH!
// TODO: H0.5.2 - Turning with for-loop
int numberOfTurns = 2;
for (int i = 0; i < numberOfTurns; i++) {
alfred.turnLeft();
}
if (runToSubtask == 2) return; // DO NOT TOUCH!
// TODO: H0.5.3 - Turning with while-loop
while (!kasper.isFacingRight()) {
kasper.turnLeft();
}
if (runToSubtask == 3) return; // DO NOT TOUCH!
// TODO: H0.6.1 - Put with repeated instructions
kasper.putCoin();
kasper.move();
kasper.move();
kasper.move();
kasper.turnLeft();
if (runToSubtask == 4) return; // DO NOT TOUCH!
// TODO: H0.6.2 - Pick with repeated instructions
alfred.move();
alfred.move();
alfred.move();
alfred.pickCoin();
alfred.turnLeft();
if (runToSubtask == 5) return; // DO NOT TOUCH!
// TODO: H0.6.3 - Put with for-loop
kasper.putCoin();
int numberOfSteps = 3;
for (int i = 0; i < numberOfSteps; i++) {
kasper.move();
}
kasper.turnLeft();
if (runToSubtask == 6) return; // DO NOT TOUCH!
// TODO: H0.7.1 - Pick with while-loop
while (alfred.isFrontClear()) {
alfred.move();
}
alfred.pickCoin();
alfred.turnLeft();
if (runToSubtask == 7) return; // DO NOT TOUCH!
// TODO: H0.7.2 - Pick and put with while-loop
kasper.putCoin();
while (alfred.isFrontClear()) {
kasper.move();
alfred.move();
}
alfred.pickCoin();
alfred.turnLeft();
kasper.turnLeft();
if (runToSubtask == 8) return; // DO NOT TOUCH!
// TODO: H0.7.3 - Put with reversed for-loop
for (int i = alfred.getNumberOfCoins(); i > 0; i--) {
alfred.putCoin();
alfred.move();
}
alfred.turnLeft();
}
public static void setupWorld() {
// variable representing width/size of world
final int worldSize = 4;
// setting world size symmetrical, meaning height = width
World.setSize(worldSize, worldSize);
// speed of how fast the world gets refreshed (e.g. how fast the robot(s) act)
// the lower the number, the faster the refresh
World.setDelay(delay);
// make it possible to see the world window
World.setVisible(true);
}
}

View file

@ -0,0 +1,16 @@
package h00;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* An example JUnit test class.
*/
public class ExampleJUnitTest {
@Test
public void testAddition() {
assertEquals(2, 1 + 1);
}
}

1
version Normal file
View file

@ -0,0 +1 @@
0.1.0-SNAPSHOT