diff --git a/solution/H00/.editorconfig b/solution/H00/.editorconfig new file mode 100644 index 0000000..38866d3 --- /dev/null +++ b/solution/H00/.editorconfig @@ -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 diff --git a/solution/H00/.gitignore b/solution/H00/.gitignore new file mode 100644 index 0000000..528b8e0 --- /dev/null +++ b/solution/H00/.gitignore @@ -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 diff --git a/solution/H00/README.md b/solution/H00/README.md new file mode 100644 index 0000000..6ecba2c --- /dev/null +++ b/solution/H00/README.md @@ -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/) diff --git a/solution/H00/build.gradle.kts b/solution/H00/build.gradle.kts new file mode 100644 index 0000000..d553dce --- /dev/null +++ b/solution/H00/build.gradle.kts @@ -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") + } + } +} diff --git a/solution/H00/gradle/libs.versions.toml b/solution/H00/gradle/libs.versions.toml new file mode 100644 index 0000000..b1b0a38 --- /dev/null +++ b/solution/H00/gradle/libs.versions.toml @@ -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"} diff --git a/solution/H00/gradle/wrapper/gradle-wrapper.jar b/solution/H00/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..c1962a7 Binary files /dev/null and b/solution/H00/gradle/wrapper/gradle-wrapper.jar differ diff --git a/solution/H00/gradle/wrapper/gradle-wrapper.properties b/solution/H00/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..36074ad --- /dev/null +++ b/solution/H00/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/solution/H00/gradlew b/solution/H00/gradlew new file mode 100755 index 0000000..aeb74cb --- /dev/null +++ b/solution/H00/gradlew @@ -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" "$@" diff --git a/solution/H00/gradlew.bat b/solution/H00/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/solution/H00/gradlew.bat @@ -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 diff --git a/solution/H00/settings.gradle.kts b/solution/H00/settings.gradle.kts new file mode 100644 index 0000000..4ca351d --- /dev/null +++ b/solution/H00/settings.gradle.kts @@ -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" diff --git a/solution/H00/src/graderPrivate/java/h00/H00_RubricProvider.java b/solution/H00/src/graderPrivate/java/h00/H00_RubricProvider.java new file mode 100644 index 0000000..35b7b92 --- /dev/null +++ b/solution/H00/src/graderPrivate/java/h00/H00_RubricProvider.java @@ -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 | Let’s 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 | Let’s 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; + } + +} diff --git a/solution/H00/src/graderPrivate/java/h00/MainTest.java b/solution/H00/src/graderPrivate/java/h00/MainTest.java new file mode 100644 index 0000000..8e7caa4 --- /dev/null +++ b/solution/H00/src/graderPrivate/java/h00/MainTest.java @@ -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>> SUBTASK_ROBOT_TRANSITIONS = new ArrayList<>(); + private static final List> 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 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 kasperTransitions = World.getGlobalWorld() + .getTrace(getRobot(KASPAR)) + .getTransitions(); + List 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> 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 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 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 expectedMovements = deserializeRobotActions(params.get(robotSpec.name)); + List actualMovements = toRobotActions(SUBTASK_ROBOT_TRANSITIONS.get(subtaskToIndex(subtask)).get(robotSpec)); + + assertEquals(expectedMovements, actualMovements, emptyContext(), result -> + robotSpec.name + "'s movements are incorrect for task " + subtask); + } + } +} diff --git a/solution/H00/src/graderPrivate/java/h00/Utils.java b/solution/H00/src/graderPrivate/java/h00/Utils.java new file mode 100644 index 0000000..5a4080b --- /dev/null +++ b/solution/H00/src/graderPrivate/java/h00/Utils.java @@ -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 deserializeRobotActions(List 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 toRobotActions(List 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; + }; + } +} diff --git a/solution/H00/src/graderPrivate/resources/h00/H0_4.json b/solution/H00/src/graderPrivate/resources/h00/H0_4.json new file mode 100644 index 0000000..f2bf384 --- /dev/null +++ b/solution/H00/src/graderPrivate/resources/h00/H0_4.json @@ -0,0 +1,4 @@ +[ { + "Kaspar" : [ "NONE" ], + "Alfred" : [ "NONE" ] +} ] diff --git a/solution/H00/src/graderPrivate/resources/h00/H0_5_1.json b/solution/H00/src/graderPrivate/resources/h00/H0_5_1.json new file mode 100644 index 0000000..a9911fc --- /dev/null +++ b/solution/H00/src/graderPrivate/resources/h00/H0_5_1.json @@ -0,0 +1,4 @@ +[ { + "Kaspar" : [ "NONE" ], + "Alfred" : [ "TURN_LEFT", "TURN_LEFT", "NONE" ] +} ] diff --git a/solution/H00/src/graderPrivate/resources/h00/H0_5_2.json b/solution/H00/src/graderPrivate/resources/h00/H0_5_2.json new file mode 100644 index 0000000..a9911fc --- /dev/null +++ b/solution/H00/src/graderPrivate/resources/h00/H0_5_2.json @@ -0,0 +1,4 @@ +[ { + "Kaspar" : [ "NONE" ], + "Alfred" : [ "TURN_LEFT", "TURN_LEFT", "NONE" ] +} ] diff --git a/solution/H00/src/graderPrivate/resources/h00/H0_5_3.json b/solution/H00/src/graderPrivate/resources/h00/H0_5_3.json new file mode 100644 index 0000000..dbaab71 --- /dev/null +++ b/solution/H00/src/graderPrivate/resources/h00/H0_5_3.json @@ -0,0 +1,4 @@ +[ { + "Kaspar" : [ "TURN_LEFT", "NONE" ], + "Alfred" : [ "NONE" ] +} ] diff --git a/solution/H00/src/graderPrivate/resources/h00/H0_6_1.json b/solution/H00/src/graderPrivate/resources/h00/H0_6_1.json new file mode 100644 index 0000000..eaaa45e --- /dev/null +++ b/solution/H00/src/graderPrivate/resources/h00/H0_6_1.json @@ -0,0 +1,4 @@ +[ { + "Kaspar" : [ "PUT_COIN", "MOVE", "MOVE", "MOVE", "TURN_LEFT", "NONE" ], + "Alfred" : [ "NONE" ] +} ] diff --git a/solution/H00/src/graderPrivate/resources/h00/H0_6_2.json b/solution/H00/src/graderPrivate/resources/h00/H0_6_2.json new file mode 100644 index 0000000..b87d9f2 --- /dev/null +++ b/solution/H00/src/graderPrivate/resources/h00/H0_6_2.json @@ -0,0 +1,4 @@ +[ { + "Kaspar" : [ "NONE" ], + "Alfred" : [ "MOVE", "MOVE", "MOVE", "PICK_COIN", "TURN_LEFT", "NONE" ] +} ] diff --git a/solution/H00/src/graderPrivate/resources/h00/H0_6_3.json b/solution/H00/src/graderPrivate/resources/h00/H0_6_3.json new file mode 100644 index 0000000..eaaa45e --- /dev/null +++ b/solution/H00/src/graderPrivate/resources/h00/H0_6_3.json @@ -0,0 +1,4 @@ +[ { + "Kaspar" : [ "PUT_COIN", "MOVE", "MOVE", "MOVE", "TURN_LEFT", "NONE" ], + "Alfred" : [ "NONE" ] +} ] diff --git a/solution/H00/src/graderPrivate/resources/h00/H0_7_1.json b/solution/H00/src/graderPrivate/resources/h00/H0_7_1.json new file mode 100644 index 0000000..b87d9f2 --- /dev/null +++ b/solution/H00/src/graderPrivate/resources/h00/H0_7_1.json @@ -0,0 +1,4 @@ +[ { + "Kaspar" : [ "NONE" ], + "Alfred" : [ "MOVE", "MOVE", "MOVE", "PICK_COIN", "TURN_LEFT", "NONE" ] +} ] diff --git a/solution/H00/src/graderPrivate/resources/h00/H0_7_2.json b/solution/H00/src/graderPrivate/resources/h00/H0_7_2.json new file mode 100644 index 0000000..971f1ef --- /dev/null +++ b/solution/H00/src/graderPrivate/resources/h00/H0_7_2.json @@ -0,0 +1,4 @@ +[ { + "Kaspar" : [ "PUT_COIN", "MOVE", "MOVE", "MOVE", "TURN_LEFT", "NONE" ], + "Alfred" : [ "MOVE", "MOVE", "MOVE", "PICK_COIN", "TURN_LEFT", "NONE" ] +} ] diff --git a/solution/H00/src/graderPrivate/resources/h00/H0_7_3.json b/solution/H00/src/graderPrivate/resources/h00/H0_7_3.json new file mode 100644 index 0000000..0468afd --- /dev/null +++ b/solution/H00/src/graderPrivate/resources/h00/H0_7_3.json @@ -0,0 +1,4 @@ +[ { + "Alfred" : [ "PUT_COIN", "MOVE", "PUT_COIN", "MOVE", "PUT_COIN", "MOVE", "TURN_LEFT", "NONE" ], + "Kaspar" : [ "NONE" ] +} ] diff --git a/solution/H00/src/main/java/h00/Main.java b/solution/H00/src/main/java/h00/Main.java new file mode 100644 index 0000000..bea6d86 --- /dev/null +++ b/solution/H00/src/main/java/h00/Main.java @@ -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); + } +} diff --git a/solution/H00/src/test/java/h00/ExampleJUnitTest.java b/solution/H00/src/test/java/h00/ExampleJUnitTest.java new file mode 100644 index 0000000..ac6b21a --- /dev/null +++ b/solution/H00/src/test/java/h00/ExampleJUnitTest.java @@ -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); + } +} diff --git a/solution/H00/version b/solution/H00/version new file mode 100644 index 0000000..b694fe3 --- /dev/null +++ b/solution/H00/version @@ -0,0 +1 @@ +0.1.0-SNAPSHOT