diff --git a/H01/.editorconfig b/H01/.editorconfig new file mode 100644 index 0000000..38866d3 --- /dev/null +++ b/H01/.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/H01/.gitignore b/H01/.gitignore new file mode 100644 index 0000000..e3750f8 --- /dev/null +++ b/H01/.gitignore @@ -0,0 +1,86 @@ +### 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 +jagr.conf diff --git a/H01/README.md b/H01/README.md new file mode 100644 index 0000000..e8fedcf --- /dev/null +++ b/H01/README.md @@ -0,0 +1,4 @@ +# Vorlage zu Hausübung 01 + +Beachten Sie die Hinweise zum Herunterladen, Importieren, Bearbeitern, Exportieren und Hochladen in unserem +[Studierenden-Guide](https://wiki.tudalgo.org/) diff --git a/H01/build.gradle.kts b/H01/build.gradle.kts new file mode 100644 index 0000000..7e23463 --- /dev/null +++ b/H01/build.gradle.kts @@ -0,0 +1,37 @@ +import org.sourcegrade.jagr.gradle.task.grader.GraderRunTask + +plugins { + alias(libs.plugins.algomate) +} + +exercise { + assignmentId.set("h01") +} + +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 = "" + firstName = "" + lastName = "" + + // Optionally require own tests for mainBuildSubmission task. Default is false + requireTests = false +} + +dependencies { + implementation(libs.fopbot) +} + +tasks { + withType { + doFirst { + throw GradleException("No public tests are provided for this exercise! For more information go to https://moodle.informatik.tu-darmstadt.de/mod/page/view.php?id=68766") + } + } +} diff --git a/H01/gradle/libs.versions.toml b/H01/gradle/libs.versions.toml new file mode 100644 index 0000000..c23692d --- /dev/null +++ b/H01/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/H01/gradle/wrapper/gradle-wrapper.jar b/H01/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/H01/gradle/wrapper/gradle-wrapper.jar differ diff --git a/H01/gradle/wrapper/gradle-wrapper.properties b/H01/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..79eb9d0 --- /dev/null +++ b/H01/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/H01/gradlew b/H01/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/H01/gradlew @@ -0,0 +1,249 @@ +#!/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##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +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=SC2039,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=SC2039,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, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +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/H01/gradlew.bat b/H01/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/H01/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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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/H01/settings.gradle.kts b/H01/settings.gradle.kts new file mode 100644 index 0000000..ccbe859 --- /dev/null +++ b/H01/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 = "H01-Student" diff --git a/H01/src/main/java/h01/BlueGhost.java b/H01/src/main/java/h01/BlueGhost.java new file mode 100644 index 0000000..3c7eb51 --- /dev/null +++ b/H01/src/main/java/h01/BlueGhost.java @@ -0,0 +1,34 @@ +package h01; + +import org.tudalgo.algoutils.student.annotation.StudentImplementationRequired; + +import fopbot.Robot; +import h01.template.Families; +import h01.template.Ghost; +import h01.template.TickBased; + +/** + * The {@link BlueGhost} is a {@link Robot} that looks like a blue ghost. + * It tries to move in a circle. + */ +public class BlueGhost extends Robot implements Ghost, TickBased { + /** + * Creates a new {@link BlueGhost} at the given position. + * + * @param x the x-coordinate + * @param y the y-coordinate + */ + public BlueGhost(int x, int y) { + super(x, y, Families.GHOST_BLUE); + } + + /** + * Turns the robot to the right and then moves in the first direction that is + * clear. + */ + @Override + @StudentImplementationRequired("H2.1") + public void doMove() { + org.tudalgo.algoutils.student.Student.crash("H2.1 - Remove if implemented"); + } +} diff --git a/H01/src/main/java/h01/GameController.java b/H01/src/main/java/h01/GameController.java new file mode 100644 index 0000000..f6f864f --- /dev/null +++ b/H01/src/main/java/h01/GameController.java @@ -0,0 +1,23 @@ +package h01; + +import h01.template.GameControllerTemplate; + +/** + * The {@link GameController} class is responsible for controlling the game. + */ +public class GameController extends GameControllerTemplate { + /** + * Creates a new {@link GameController} object and sets up the game. + */ + public GameController() { + setup(); + } + + /** + * Checks if the player has won the game. + */ + @Override + public boolean checkWinCondition() { + return pacman.getNumberOfCoins() == totalCoins; + } +} diff --git a/H01/src/main/java/h01/Main.java b/H01/src/main/java/h01/Main.java new file mode 100644 index 0000000..7b003c4 --- /dev/null +++ b/H01/src/main/java/h01/Main.java @@ -0,0 +1,16 @@ +package h01; + +/** + * Main entry point in executing the program. + */ +public class Main { + + /** + * Main entry point in executing the program. + * + * @param args program arguments, currently ignored + */ + public static void main(String[] args) { + new GameController().startGame(); + } +} diff --git a/H01/src/main/java/h01/OrangeGhost.java b/H01/src/main/java/h01/OrangeGhost.java new file mode 100644 index 0000000..6d3c748 --- /dev/null +++ b/H01/src/main/java/h01/OrangeGhost.java @@ -0,0 +1,39 @@ +package h01; + +import org.tudalgo.algoutils.student.annotation.StudentImplementationRequired; + +import fopbot.Robot; +import h01.template.Families; +import h01.template.Ghost; +import h01.template.TickBased; + +/** + * {@link OrangeGhost} is a {@link Robot} that looks like a orange ghost. + * It tries to move in a straight line and alternates between turning left and + * right. + */ +public class OrangeGhost extends Robot implements Ghost, TickBased { + /** + * Creates a new {@link OrangeGhost} at the given position. + * + * @param x the x-coordinate + * @param y the y-coordinate + */ + public OrangeGhost(int x, int y) { + super(x, y, Families.GHOST_ORANGE); + } + + private boolean leftTurnNext = false; + + /** + * Moves the robot in a straight line if possible. + * If the robot cannot move forward, it turns left or right until there is no + * wall in front. + * The robot alternates between turning left and right. + */ + @Override + @StudentImplementationRequired("H2.3") + public void doMove() { + org.tudalgo.algoutils.student.Student.crash("H2.3 - Remove if implemented"); + } +} diff --git a/H01/src/main/java/h01/Pacman.java b/H01/src/main/java/h01/Pacman.java new file mode 100644 index 0000000..41fb772 --- /dev/null +++ b/H01/src/main/java/h01/Pacman.java @@ -0,0 +1,41 @@ +package h01; + +import org.tudalgo.algoutils.student.annotation.StudentImplementationRequired; + +import fopbot.Direction; +import fopbot.Robot; +import h01.template.Controllable; +import h01.template.Families; +import h01.template.TickBased; + +/** + * {@link Pacman} is a {@link Robot} that can be controlled by the user and + * looks like Pacman. + * It can move in four directions and pick up coins. + */ +public class Pacman extends Robot implements Controllable, TickBased { + /** + * Creates a new {@link Pacman} at the given position. + * + * @param x the x-coordinate + * @param y the y-coordinate + */ + public Pacman(int x, int y) { + super(x, y, Families.PACMAN); + } + + /** + * Handles the key input of the user. + * The keys 0, 1, 2, 3 represent the arrow keys up, right, down, left. + * If the key is not in this range, the method does nothing. + * If the key is in the range, the robot turns in the corresponding direction, + * moves one field and collects a coin if there is one. + * + * @param k the int value of the pressed key + */ + @Override + @StudentImplementationRequired("H1.1") + public void handleKeyInput(int k) { + org.tudalgo.algoutils.student.Student.crash("H1.1 - Remove if implemented"); + } +} diff --git a/H01/src/main/java/h01/PinkGhost.java b/H01/src/main/java/h01/PinkGhost.java new file mode 100644 index 0000000..32c5fa9 --- /dev/null +++ b/H01/src/main/java/h01/PinkGhost.java @@ -0,0 +1,36 @@ +package h01; + +import org.tudalgo.algoutils.student.annotation.StudentImplementationRequired; + +import fopbot.Robot; +import h01.template.Families; +import h01.template.Ghost; +import h01.template.TickBased; +import h01.template.Util; + +/** + * The {@link PinkGhost} is a {@link Robot} that looks like a pink ghost. + * It tries to move in a random direction. + */ +public class PinkGhost extends Robot implements Ghost, TickBased { + /** + * Creates a new {@link PinkGhost} at the given position. + * + * @param x the x-coordinate + * @param y the y-coordinate + */ + public PinkGhost(int x, int y) { + super(x, y, Families.GHOST_PINK); + } + + /** + * Finds in how many directions the ghost can move and then turns a random + * amount of times to the left. + * The ghost then moves forward or turns to the left until it can move forward. + */ + @Override + @StudentImplementationRequired("H2.2") + public void doMove() { + org.tudalgo.algoutils.student.Student.crash("H2.2 - Remove if implemented"); + } +} diff --git a/H01/src/main/java/h01/RedGhost.java b/H01/src/main/java/h01/RedGhost.java new file mode 100644 index 0000000..627a5a2 --- /dev/null +++ b/H01/src/main/java/h01/RedGhost.java @@ -0,0 +1,39 @@ +package h01; + +import org.tudalgo.algoutils.student.annotation.StudentImplementationRequired; + +import fopbot.Direction; +import fopbot.Robot; +import h01.template.Families; +import h01.template.Ghost; +import h01.template.TickBased; +import h01.template.Util; + +/** + * The {@link RedGhost} is a {@link Robot} that looks like a red ghost. + * It tries to move in the direction of the chased robot. + */ +public class RedGhost extends Robot implements Ghost, TickBased { + private final Robot chased; + + /** + * Creates a new {@link RedGhost} at the given position. + * + * @param x the x-coordinate + * @param y the y-coordinate + * @param chased the robot that is being chased + */ + public RedGhost(int x, int y, Robot chased) { + super(x, y, Families.GHOST_RED); + this.chased = chased; + } + + /** + * Moves the robot in the direction of the chased robot. + */ + @Override + @StudentImplementationRequired("H2.4") + public void doMove() { + org.tudalgo.algoutils.student.Student.crash("H2.4 - Remove if implemented"); + } +} diff --git a/H01/src/main/java/h01/template/Controllable.java b/H01/src/main/java/h01/template/Controllable.java new file mode 100644 index 0000000..cd648eb --- /dev/null +++ b/H01/src/main/java/h01/template/Controllable.java @@ -0,0 +1,5 @@ +package h01.template; + +public interface Controllable { + void handleKeyInput(int k); +} diff --git a/H01/src/main/java/h01/template/Families.java b/H01/src/main/java/h01/template/Families.java new file mode 100644 index 0000000..1309c6f --- /dev/null +++ b/H01/src/main/java/h01/template/Families.java @@ -0,0 +1,36 @@ +package h01.template; + +import fopbot.RobotFamily; +import fopbot.SvgBasedRobotFamily; + +import java.awt.*; + +public class Families { + public static RobotFamily GHOST_ORANGE = new SvgBasedRobotFamily( + "GHOST_ORANGE", + "/robots/ghost_orange.svg", + "/robots/ghost_orange.svg", + Color.ORANGE); + public static RobotFamily GHOST_BLUE = new SvgBasedRobotFamily( + "GHOST_BLUE", + "/robots/ghost_blue.svg", + "/robots/ghost_blue.svg", + Color.BLUE); + public static RobotFamily GHOST_RED = new SvgBasedRobotFamily( + "GHOST_RED", + "/robots/ghost_red.svg", + "/robots/ghost_red.svg", + Color.RED); + public static RobotFamily GHOST_PINK = new SvgBasedRobotFamily( + "GHOST_PINK", + "/robots/ghost_pink.svg", + "/robots/ghost_pink.svg", + Color.PINK); + public static RobotFamily PACMAN = new SvgBasedRobotFamily( + "PACMAN", + "/robots/pacman.svg", + "/robots/pacman.svg", + Color.YELLOW, + 270, + 270); +} diff --git a/H01/src/main/java/h01/template/GameControllerTemplate.java b/H01/src/main/java/h01/template/GameControllerTemplate.java new file mode 100644 index 0000000..89ba60f --- /dev/null +++ b/H01/src/main/java/h01/template/GameControllerTemplate.java @@ -0,0 +1,378 @@ +package h01.template; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.geom.Ellipse2D; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; + +import fopbot.Coin; +import fopbot.ColorProfile; +import fopbot.GuiPanel; +import fopbot.PaintUtils; +import fopbot.Robot; +import fopbot.World; +import h01.BlueGhost; +import h01.OrangeGhost; +import h01.Pacman; +import h01.PinkGhost; +import h01.RedGhost; + +/** + * A {@link GameControllerTemplate} controls the game loop and the + * {@link Robot}s and checks the win condition. + */ +public abstract class GameControllerTemplate { + /** + * The {@link Timer} that controls the game loop. + */ + private final Timer gameLoopTimer = new Timer(); + + /** + * The {@link GameInputHandler} that handles the input of the user. + */ + private final GameInputHandler inputHandler = new GameInputHandler(); + + /** + * The total umber of coins in the map. + */ + protected int totalCoins; + + /** + * The {@link Robot}s that are controlled by the {@link GameControllerTemplate}. + */ + protected final ArrayList robots = new ArrayList<>(); + + /** + * The {@link Pacman} {@link Robot}. + */ + protected Robot pacman; + + /** + * The {@link BlueGhost} {@link Robot}. + */ + protected Robot blue; + + /** + * The {@link OrangeGhost} {@link Robot}. + */ + protected Robot orange; + + /** + * The {@link PinkGhost} {@link Robot}. + */ + protected Robot pink; + + /** + * The {@link RedGhost} {@link Robot}. + */ + protected Robot red; + + private Point ghostField = new Point(4, 4); + + /** + * A {@link Map} that maps a {@link Robot} to the amount of ticks that have + * passed since the last tick action. + */ + private final Map robotTicks = new HashMap<>(); + + /** + * The {@link TimerTask} that is executed every tick. + */ + private final TimerTask gameLoopTask = new TimerTask() { + @Override + public void run() { + for (final Robot robot : GameControllerTemplate.this.robots) { + if (!(robot instanceof final TickBased tb)) { + continue; + } + if (!GameControllerTemplate.this.robotTicks.containsKey(robot)) { + GameControllerTemplate.this.robotTicks.put(robot, 0); + } + if (GameControllerTemplate.this.robotTicks.get(robot) < tb.getUpdateDelay()) { + GameControllerTemplate.this.robotTicks.put(robot, + GameControllerTemplate.this.robotTicks.get(robot) + 1); + continue; + } + GameControllerTemplate.this.robotTicks.put(robot, 0); + // do tick action + if (robot instanceof final Pacman r) { + r.handleKeyInput( + GameControllerTemplate.this.inputHandler.getDirection()); + } else if (robot instanceof final Ghost r) { + r.doMove(); + } + } + // check win condition + if (checkWinCondition()) + stopGame(true); + if (checkLoseCondition()) + stopGame(false); + } + }; + + /** + * Gets the {@link Pacman} {@link Robot}. + * + * @return the {@link Pacman} {@link Robot} + */ + public Robot getPacman() { + return pacman; + } + + /** + * Gets the {@link BlueGhost} {@link Robot}. + * + * @return the {@link BlueGhost} {@link Robot} + */ + public Robot getBlue() { + return blue; + } + + /** + * Gets the {@link OrangeGhost} {@link Robot}. + * + * @return the {@link OrangeGhost} {@link Robot} + */ + public Robot getOrange() { + return orange; + } + + /** + * Gets the {@link PinkGhost} {@link Robot}. + * + * @return the {@link PinkGhost} {@link Robot} + */ + public Robot getPink() { + return pink; + } + + /** + * Gets the {@link RedGhost} {@link Robot}. + * + * @return the {@link RedGhost} {@link Robot} + */ + public Robot getRed() { + return red; + } + + /** + * Starts the game loop. + */ + public void startGame() { + System.out.println("Starting game..."); + this.gameLoopTimer.scheduleAtFixedRate(this.gameLoopTask, 0, 200); + } + + /** + * Stops the game loop. + */ + public void stopGame(boolean won) { + this.gameLoopTimer.cancel(); + endscreen(won ? Color.GREEN : Color.RED); + } + + public void endscreen(Color color) { + World.getGlobalWorld().getGuiPanel().setColorProfile( + ColorProfile.DEFAULT.toBuilder() + .backgroundColorDark(Color.BLACK) + .backgroundColorLight(Color.BLACK) + .fieldColorDark(color) + .fieldColorLight(color) + .innerBorderColorLight(color) + .innerBorderColorDark(color) + .wallColorDark(Color.BLUE) + .wallColorLight(Color.BLUE) + .outerBorderColorDark(Color.BLUE) + .outerBorderColorLight(Color.BLUE) + .coinColorDark(color) + .coinColorLight(color) + .build()); + World.getGlobalWorld().getGuiPanel().updateGui(); + } + + /** + * Sets up the game. + */ + protected void setup() { + setupWorld(); + setupTheme(); + setupRobots(); + totalCoins = 2;// World.getHeight()*World.getWidth()-2; + setupCoins(totalCoins); + this.inputHandler.install(); + } + + public void setupTheme() { + World.getGlobalWorld().getGuiPanel().setColorProfile( + ColorProfile.DEFAULT.toBuilder() + .backgroundColorDark(Color.BLACK) + .backgroundColorLight(Color.BLACK) + .fieldColorDark(Color.BLACK) + .fieldColorLight(Color.BLACK) + .innerBorderColorLight(Color.BLACK) + .innerBorderColorDark(Color.BLACK) + .wallColorDark(Color.BLUE) + .wallColorLight(Color.BLUE) + .outerBorderColorDark(Color.BLUE) + .outerBorderColorLight(Color.BLUE) + .build()); + } + + /** + * Initializes the {@link World} and adds the {@link Robot}s to it. + */ + public void setupWorld() { + World.setSize(9, 9); + + World.getGlobalWorld().setGuiPanel(new GuiPanel(World.getGlobalWorld()) { + @Override + @SuppressWarnings("UnstableApiUsage") + protected void drawCoin(final Coin c, final Graphics g, final boolean evadeRobots) { + final var g2d = (Graphics2D) g; + final var oldColor = g2d.getColor(); + g2d.setColor(getColorProfile().getCoinColor()); + final Rectangle2D fieldBounds = scale(PaintUtils.getFieldBounds(c, world)); + final double radius = scale(5d); + g2d.fill( + new Ellipse2D.Double( + fieldBounds.getCenterX() - radius, + fieldBounds.getCenterY() - radius, + 2 * radius, + 2 * radius)); + } + }); + + World.setDelay(0); + World.setVisible(true); + World.getGlobalWorld().setDrawTurnedOffRobots(false); + + World.placeVerticalWall(0, 3); + World.placeVerticalWall(0, 4); + World.placeVerticalWall(0, 5); + + World.placeVerticalWall(1, 2); + World.placeVerticalWall(1, 4); + World.placeVerticalWall(1, 6); + + World.placeVerticalWall(2, 2); + World.placeVerticalWall(2, 3); + World.placeVerticalWall(2, 5); + World.placeVerticalWall(2, 6); + + World.placeVerticalWall(3, 4); + World.placeVerticalWall(3, 7); + + World.placeVerticalWall(4, 4); + World.placeVerticalWall(4, 1); + + World.placeVerticalWall(5, 2); + World.placeVerticalWall(5, 3); + World.placeVerticalWall(5, 5); + World.placeVerticalWall(5, 6); + + World.placeVerticalWall(6, 2); + World.placeVerticalWall(6, 4); + World.placeVerticalWall(6, 6); + + World.placeVerticalWall(7, 3); + World.placeVerticalWall(7, 4); + World.placeVerticalWall(7, 5); + + World.placeHorizontalWall(1, 0); + World.placeHorizontalWall(1, 1); + World.placeHorizontalWall(1, 6); + World.placeHorizontalWall(1, 7); + + World.placeHorizontalWall(2, 0); + World.placeHorizontalWall(2, 7); + + World.placeHorizontalWall(3, 0); + World.placeHorizontalWall(3, 2); + World.placeHorizontalWall(3, 5); + + World.placeHorizontalWall(4, 1); + World.placeHorizontalWall(4, 3); + World.placeHorizontalWall(4, 6); + + World.placeHorizontalWall(5, 2); + World.placeHorizontalWall(5, 5); + World.placeHorizontalWall(5, 7); + + World.placeHorizontalWall(6, 0); + World.placeHorizontalWall(6, 7); + + World.placeHorizontalWall(7, 0); + World.placeHorizontalWall(7, 1); + World.placeHorizontalWall(7, 6); + World.placeHorizontalWall(7, 7); + + World.getGlobalWorld().setFieldColor(ghostField.x, ghostField.y, Color.YELLOW); + } + + /** + * Adds the {@link Robot}s to the {@link World}. + */ + public void setupRobots() { + this.robots.add(pacman = new Pacman(4, 3)); + this.robots.add(blue = new BlueGhost(ghostField.x, ghostField.y)); + this.robots.add(orange = new OrangeGhost(ghostField.x, ghostField.y)); + this.robots.add(pink = new PinkGhost(ghostField.x, ghostField.y)); + this.robots.add(red = new RedGhost(ghostField.x, ghostField.y, pacman)); + } + + public void setupCoins(int numberOfCoins) { + if (numberOfCoins > World.getHeight() * World.getWidth() - 2) { + throw new IllegalArgumentException("Too many coins for this world size."); + } + + ArrayList Fields = new ArrayList<>(); + for (int y = 0; y < World.getHeight(); y++) { + for (int x = 0; x < World.getWidth(); x++) { + if (!((x == ghostField.x && y == ghostField.y) || x == pacman.getX() && y == pacman.getY())) + Fields.add(new Point(x, y)); + } + } + + for (int i = 0; i < numberOfCoins; i++) { + int randomIndex = (int) (Math.random() * Fields.size()); + Point spot = Fields.remove(randomIndex); + World.putCoins(spot.x, spot.y, 1); + } + } + + /** + * Checks the win condition. + * + * @return Returns true if the game is won. + */ + public abstract boolean checkWinCondition(); + + /** + * Checks the lose condition. + * + * @return Returns true if the game is lost. + */ + public boolean checkLoseCondition() { + boolean gameDone = pacman.getX() == orange.getX() && pacman.getY() == orange.getY(); + + if (pacman.getX() == blue.getX() && pacman.getY() == blue.getY()) { + gameDone = true; + } + + if (pacman.getX() == pink.getX() && pacman.getY() == pink.getY()) { + gameDone = true; + } + + if (pacman.getX() == red.getX() && pacman.getY() == red.getY()) { + gameDone = true; + } + return gameDone; + } +} diff --git a/H01/src/main/java/h01/template/GameInputHandler.java b/H01/src/main/java/h01/template/GameInputHandler.java new file mode 100644 index 0000000..fa7ffda --- /dev/null +++ b/H01/src/main/java/h01/template/GameInputHandler.java @@ -0,0 +1,108 @@ +package h01.template; + +import fopbot.Direction; +import fopbot.World; + +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * A {@link GameInputHandler} handles the input of the user. + */ +public class GameInputHandler { + /** + * The {@link Direction} to turn to. If {@code -1} the robot should not turn. + */ + private final AtomicInteger direction = new AtomicInteger(-1); + /** + * If {@code true} the robot should put a coin on the current field. + */ + private final AtomicBoolean shouldPutCoins = new AtomicBoolean(false); + /** + * If {@code true} the robot should pick a coin from the current field. + */ + private final AtomicBoolean shouldPickCoins = new AtomicBoolean(false); + + /** + * Parses the inputs to a direction. + * + * @param keysPressed the keys pressed + * @return the direction or null if no direction is pressed + */ + public static Direction getDirectionFromKeysPressed(final Set keysPressed) { + final Map> directionKeys = Map.of( + Direction.UP, List.of(KeyEvent.VK_UP, KeyEvent.VK_W), + Direction.LEFT, List.of(KeyEvent.VK_LEFT, KeyEvent.VK_A), + Direction.DOWN, List.of(KeyEvent.VK_DOWN, KeyEvent.VK_S), + Direction.RIGHT, List.of(KeyEvent.VK_RIGHT, KeyEvent.VK_D) + ); + final Set pressedDirections = new HashSet<>(); + for (final Direction direction : directionKeys.keySet()) { + for (final Integer key : directionKeys.get(direction)) { + if (keysPressed.contains(key)) { + pressedDirections.add(direction); + } + } + } + if (pressedDirections.size() == 1) { + return pressedDirections.iterator().next(); + } else { + return null; + } + } + + /** + * Installs the {@link GameInputHandler} to the {@link World}. + */ + public void install() { + World.getGlobalWorld().getInputHandler().addKeyListener(new KeyAdapter() { + @Override + public void keyTyped(final KeyEvent e) { + updateKeysPressed(); + } + + @Override + public void keyPressed(final KeyEvent e) { + updateKeysPressed(); + } + + @Override + public void keyReleased(final KeyEvent e) { + updateKeysPressed(); + } + }); + } + + /** + * Updates the {@link #direction}, {@link #shouldPutCoins} and {@link #shouldPickCoins} based on the pressed keys. + */ + protected void updateKeysPressed() { + this.direction.set( + Optional.ofNullable(getDirectionFromKeysPressed(World.getGlobalWorld().getInputHandler().getKeysPressed())) + .map(Enum::ordinal) + .orElse(-1) + ); + this.shouldPickCoins.set( + World.getGlobalWorld().getInputHandler().getKeysPressed().contains(KeyEvent.VK_SPACE) + ); + this.shouldPutCoins.set( + World.getGlobalWorld().getInputHandler().getKeysPressed().contains(KeyEvent.VK_R) + ); + } + + /** + * Returns the current {@link Direction} to turn to. If {@code -1} the robot should not turn. + * + * @return the current {@link Direction} to turn to. If {@code -1} the robot should not turn. + */ + public int getDirection() { + return this.direction.get(); + } +} diff --git a/H01/src/main/java/h01/template/Ghost.java b/H01/src/main/java/h01/template/Ghost.java new file mode 100644 index 0000000..d13053f --- /dev/null +++ b/H01/src/main/java/h01/template/Ghost.java @@ -0,0 +1,5 @@ +package h01.template; + +public interface Ghost { + void doMove(); +} diff --git a/H01/src/main/java/h01/template/TickBased.java b/H01/src/main/java/h01/template/TickBased.java new file mode 100644 index 0000000..2b18bee --- /dev/null +++ b/H01/src/main/java/h01/template/TickBased.java @@ -0,0 +1,15 @@ +package h01.template; + +/** + * An interface that enables an object to be updated every n-th tick. + */ +public interface TickBased { + /** + * Returns the number of ticks between two updates. + * + * @return the number of ticks between two updates + */ + default int getUpdateDelay() { + return 1; + } +} diff --git a/H01/src/main/java/h01/template/Util.java b/H01/src/main/java/h01/template/Util.java new file mode 100644 index 0000000..eefcb35 --- /dev/null +++ b/H01/src/main/java/h01/template/Util.java @@ -0,0 +1,55 @@ +package h01.template; + +import java.util.Random; + +import fopbot.Direction; +import fopbot.Robot; + +/** + * Utility class for the ghosts + */ +public class Util { + + private static Random rnd = new Random(); + + /** + * Returns a random integer between min and max (both inclusive) + * + * @param min the minimum value + * @param max the maximum value + * @return a random integer between min and max (both inclusive) + */ + public static int getRandomInteger(int min, int max) { + return min + rnd.nextInt(max - min + 1); + } + + /** + * Returns the direction in which the robot is the closest to the chaser + * + * @param pacman the robot that is being chased + * @param chaser the robot that is chasing + * @return the direction in which the robot is the closest to the chaser + */ + public static Direction furthestDirection(Robot pacman, Robot chaser) { + int px = pacman.getX(); + int py = pacman.getY(); + int cx = chaser.getX(); + int cy = chaser.getY(); + + int xdelta = Math.abs(px - cx); + int ydelta = Math.abs(py - cy); + + if (xdelta > ydelta) { + if (cx > px) + return Direction.LEFT; + else + return Direction.RIGHT; + } else { + if (cy > py) + return Direction.DOWN; + else + return Direction.UP; + } + } + +} diff --git a/H01/src/main/resources/robots/ghost_blue.svg b/H01/src/main/resources/robots/ghost_blue.svg new file mode 100644 index 0000000..2d21577 --- /dev/null +++ b/H01/src/main/resources/robots/ghost_blue.svg @@ -0,0 +1,67 @@ + + + + + + + + + + + + + diff --git a/H01/src/main/resources/robots/ghost_orange.svg b/H01/src/main/resources/robots/ghost_orange.svg new file mode 100644 index 0000000..21428d3 --- /dev/null +++ b/H01/src/main/resources/robots/ghost_orange.svg @@ -0,0 +1,31 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/H01/src/main/resources/robots/ghost_pink.svg b/H01/src/main/resources/robots/ghost_pink.svg new file mode 100644 index 0000000..589d67d --- /dev/null +++ b/H01/src/main/resources/robots/ghost_pink.svg @@ -0,0 +1,67 @@ + + + + + + + + + + + + + diff --git a/H01/src/main/resources/robots/ghost_red.svg b/H01/src/main/resources/robots/ghost_red.svg new file mode 100644 index 0000000..a1eca1a --- /dev/null +++ b/H01/src/main/resources/robots/ghost_red.svg @@ -0,0 +1,67 @@ + + + + + + + + + + + + + diff --git a/H01/src/main/resources/robots/pacman.svg b/H01/src/main/resources/robots/pacman.svg new file mode 100644 index 0000000..9c8a8cb --- /dev/null +++ b/H01/src/main/resources/robots/pacman.svg @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + diff --git a/H01/src/test/java/h01/ExampleJUnitTest.java b/H01/src/test/java/h01/ExampleJUnitTest.java new file mode 100644 index 0000000..14bb830 --- /dev/null +++ b/H01/src/test/java/h01/ExampleJUnitTest.java @@ -0,0 +1,16 @@ +package h01; + +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); + } +}