commit d5e7d75218a12049c09ccfcf42a2355e8e0fe23f Author: Oshgnacknak Date: Sat Jan 11 16:41:00 2025 +0100 Squashed 'H04/' content from commit 56e60eb git-subtree-dir: H04 git-subtree-split: 56e60eb1fcd414e90e1eab14872c5821ca25899a diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..38866d3 --- /dev/null +++ b/.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/.gitignore b/.gitignore new file mode 100644 index 0000000..e3750f8 --- /dev/null +++ b/.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/README.md b/README.md new file mode 100644 index 0000000..df08fae --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +# Vorlage zu Hausübung 04 + +Beachten Sie die Hinweise zum Herunterladen, Importieren, Bearbeitern, Exportieren und Hochladen in unserem +[Studierenden-Guide](https://wiki.tudalgo.org/) diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..a176678 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,37 @@ +import org.sourcegrade.jagr.gradle.task.grader.GraderRunTask + +plugins { + alias(libs.plugins.algomate) +} + +exercise { + assignmentId.set("h04") +} + +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/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..23bd65f --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,5 @@ +[plugins] +algomate = { id = "org.tudalgo.algomate", version = "0.7.1" } + +[libraries] +fopbot = { module = "org.tudalgo:fopbot", version = "0.8.1" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..79eb9d0 --- /dev/null +++ b/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/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/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/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..5e94aa2 --- /dev/null +++ b/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 = "H04-Student" diff --git a/src/main/java/h04/GameController.java b/src/main/java/h04/GameController.java new file mode 100644 index 0000000..ce26e4e --- /dev/null +++ b/src/main/java/h04/GameController.java @@ -0,0 +1,18 @@ +package h04; + +import h04.template.ChessUtils; +import h04.template.GameControllerTemplate; +import h04.chesspieces.King; + +public class GameController extends GameControllerTemplate { + public GameController() { + super(); + setup(); + } + + @Override + public boolean checkWinCondition() { + //TODO H4.1 + return false; + } +} diff --git a/src/main/java/h04/Main.java b/src/main/java/h04/Main.java new file mode 100644 index 0000000..9a639e2 --- /dev/null +++ b/src/main/java/h04/Main.java @@ -0,0 +1,17 @@ +package h04; + +import fopbot.World; + +/** + * 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(final String[] args) { + new GameController().startGame(); + } +} diff --git a/src/main/java/h04/chesspieces/Bishop.java b/src/main/java/h04/chesspieces/Bishop.java new file mode 100644 index 0000000..4ac0078 --- /dev/null +++ b/src/main/java/h04/chesspieces/Bishop.java @@ -0,0 +1,24 @@ +package h04.chesspieces; + +import fopbot.Robot; +//Wichtig für Implementation +//import h04.movement.MoveStrategy; + +import java.awt.Point; + + +public class Bishop extends Robot { + + private final Team team; + + public Bishop(final int x, final int y, final Team team){ + super(x, y, team == Team.WHITE ? Families.BISHOP_WHITE : Families.BISHOP_BLACK); + this.team = team; + } + + //Wichtig für Implementation + //@Override + public Team getTeam() { return team;} + + //TODO H4.5 +} diff --git a/src/main/java/h04/chesspieces/ChessPiece.java b/src/main/java/h04/chesspieces/ChessPiece.java new file mode 100644 index 0000000..fba1515 --- /dev/null +++ b/src/main/java/h04/chesspieces/ChessPiece.java @@ -0,0 +1,20 @@ +package h04.chesspieces; +//Wichtig für Implementation +//import h04.movement.MoveStrategy; + +import java.awt.Point; + +public interface ChessPiece { + Team getTeam(); + int getX(); + int getY(); + /** + * Returns {@code true} if this robot is turned off. + * + * @return {@code true} if this robot is turned off + */ + boolean isTurnedOff(); + void turnOff(); + + //TODO H4.3 +} diff --git a/src/main/java/h04/chesspieces/Families.java b/src/main/java/h04/chesspieces/Families.java new file mode 100644 index 0000000..e1df0a4 --- /dev/null +++ b/src/main/java/h04/chesspieces/Families.java @@ -0,0 +1,81 @@ +package h04.chesspieces; + +import fopbot.RobotFamily; +import fopbot.SvgBasedRobotFamily; + +import java.awt.Color; + +public class Families { + public static RobotFamily PAWN_WHITE = new SvgBasedRobotFamily( + "PAWN_WHITE", + "/pieces/pawn_white.svg", + "/pieces/pawn_white.svg", + Color.WHITE + ); + public static RobotFamily PAWN_BLACK = new SvgBasedRobotFamily( + "PAWN_BLACK", + "/pieces/pawn_black.svg", + "/pieces/pawn_black.svg", + Color.BLACK + ); + public static RobotFamily ROOK_WHITE = new SvgBasedRobotFamily( + "ROOK_WHITE", + "/pieces/rook_white.svg", + "/pieces/rook_white.svg", + Color.WHITE + ); + public static RobotFamily ROOK_BLACK = new SvgBasedRobotFamily( + "ROOK_BLACK", + "/pieces/rook_black.svg", + "/pieces/rook_black.svg", + Color.BLACK + ); + public static RobotFamily KNIGHT_WHITE = new SvgBasedRobotFamily( + "KNIGHT_WHITE", + "/pieces/knight_white.svg", + "/pieces/knight_white.svg", + Color.WHITE + ); + public static RobotFamily KNIGHT_BLACK = new SvgBasedRobotFamily( + "KNIGHT_BLACK", + "/pieces/knight_black.svg", + "/pieces/knight_black.svg", + Color.BLACK + ); + public static RobotFamily BISHOP_WHITE = new SvgBasedRobotFamily( + "BISHOP_WHITE", + "/pieces/bishop_white.svg", + "/pieces/bishop_white.svg", + Color.WHITE + ); + public static RobotFamily BISHOP_BLACK = new SvgBasedRobotFamily( + "BISHOP_BLACK", + "/pieces/bishop_black.svg", + "/pieces/bishop_black.svg", + Color.BLACK + ); + public static RobotFamily QUEEN_WHITE = new SvgBasedRobotFamily( + "QUEEN_WHITE", + "/pieces/queen_white.svg", + "/pieces/queen_white.svg", + Color.WHITE + ); + public static RobotFamily QUEEN_BLACK = new SvgBasedRobotFamily( + "QUEEN_BLACK", + "/pieces/queen_black.svg", + "/pieces/queen_black.svg", + Color.BLACK + ); + public static RobotFamily KING_WHITE = new SvgBasedRobotFamily( + "KING_WHITE", + "/pieces/king_white.svg", + "/pieces/king_white.svg", + Color.WHITE + ); + public static RobotFamily KING_BLACK = new SvgBasedRobotFamily( + "KING_BLACK", + "/pieces/king_black.svg", + "/pieces/king_black.svg", + Color.BLACK + ); +} diff --git a/src/main/java/h04/chesspieces/King.java b/src/main/java/h04/chesspieces/King.java new file mode 100644 index 0000000..118e181 --- /dev/null +++ b/src/main/java/h04/chesspieces/King.java @@ -0,0 +1,25 @@ +package h04.chesspieces; + +import fopbot.Robot; +//Wichtig für Implementation +//import h04.movement.MoveStrategy; +import h04.template.ChessUtils; + +import java.awt.Point; + +public class King extends Robot implements ChessPiece { + + private final Team team; + + public King(final int x, final int y, final Team team) { + super(x, y, team == Team.WHITE ? Families.KING_WHITE : Families.KING_BLACK); + this.team = team; + } + + @Override + public Team getTeam() { + return team; + } + + //TODO H4.4 +} diff --git a/src/main/java/h04/chesspieces/Knight.java b/src/main/java/h04/chesspieces/Knight.java new file mode 100644 index 0000000..ac2ddf6 --- /dev/null +++ b/src/main/java/h04/chesspieces/Knight.java @@ -0,0 +1,47 @@ +package h04.chesspieces; + +import fopbot.Robot; +//Wichtig für Implementation +//import h04.movement.MoveStrategy; +import h04.template.ChessUtils; + +import java.awt.Point; + +public class Knight extends Robot implements ChessPiece { + + private final Team team; + + public Knight(final int x, final int y, final Team team) { + super(x, y, team == Team.WHITE ? Families.KNIGHT_WHITE : Families.KNIGHT_BLACK); + this.team = team; + } + + @Override + public Team getTeam() { + return team; + } + + //Wichtig für Implementation + /* + @Override + public void moveStrategy(final int dx, final int dy, final MoveStrategy strategy) { + strategy.move(this, dx, dy); + } + @Override + */ + public Point[] getPossibleMoveFields() { + final Point[] possibleMoves = new Point[8]; + int index = 0; + for (final Point delta : new Point[]{new Point(1, 2), new Point(2, 1)}) { + for (int i = 0; i < 4; i++) { + final Point move = new Point(getX() + delta.x, getY() + delta.y); + if (ChessUtils.isValidCoordinate(move) && ChessUtils.getTeamAt(move) != getTeam()) { + possibleMoves[index++] = move; + } + //noinspection SuspiciousNameCombination + delta.setLocation(-delta.y, delta.x); + } + } + return possibleMoves; + } +} diff --git a/src/main/java/h04/chesspieces/Pawn.java b/src/main/java/h04/chesspieces/Pawn.java new file mode 100644 index 0000000..ba4943a --- /dev/null +++ b/src/main/java/h04/chesspieces/Pawn.java @@ -0,0 +1,57 @@ +package h04.chesspieces; + +import fopbot.Robot; +//Wichtig für Implementation +//import h04.movement.MoveStrategy; + +import java.awt.Point; + +import static h04.template.ChessUtils.getTeamAt; +import static h04.template.ChessUtils.isValidCoordinate; + +public class Pawn extends Robot implements ChessPiece { + private final Team team; + + boolean firstMove = true; + + public Pawn(final int x, final int y, final Team team) { + super(x, y, team == Team.WHITE ? Families.PAWN_WHITE : Families.PAWN_BLACK); + this.team = team; + } + + @Override + public Team getTeam() { + return team; + } + + //Wichtig für Implementation + /* + @Override + public void moveStrategy(final int dx, final int dy, final MoveStrategy strategy) { + strategy.move(this, dx, dy); + firstMove = false; + } + @Override + */ + public Point[] getPossibleMoveFields() { + final Point[] possibleMoves = new Point[4]; + int index = 0; + final int direction = team == Team.WHITE ? 1 : -1; + final Point front1 = new Point(getX(), getY() + direction); + if (isValidCoordinate(front1) && getTeamAt(front1) == null) { + possibleMoves[index++] = front1; + final Point front2 = new Point(getX(), getY() + 2 * direction); + if (firstMove && isValidCoordinate(front2) && getTeamAt(front2) == null) { + possibleMoves[index++] = front2; + } + } + //attack + for (final int i : new int[]{-1, 1}) { + final Point p = new Point(getX() + i, getY() + direction); + if (isValidCoordinate(p) && getTeamAt(p) == getTeam().getOpponent()) { + possibleMoves[index++] = p; + } + } + return possibleMoves; + } +} diff --git a/src/main/java/h04/chesspieces/Queen.java b/src/main/java/h04/chesspieces/Queen.java new file mode 100644 index 0000000..0cf090a --- /dev/null +++ b/src/main/java/h04/chesspieces/Queen.java @@ -0,0 +1,25 @@ +package h04.chesspieces; + +import fopbot.Robot; +//Wichtig für Implementation +//import h04.movement.MoveStrategy; +import h04.template.ChessUtils; + +import java.awt.Point; + +public class Queen extends Robot { + private final Team team; + + public Queen(final int x, final int y, final Team team) { + super(x, y, team == Team.WHITE ? Families.QUEEN_WHITE : Families.QUEEN_BLACK); + this.team = team; + } + + //Wichtig für Implementation + //@Override + public Team getTeam() { + return team; + } + + //TODO H4.6 +} diff --git a/src/main/java/h04/chesspieces/Rook.java b/src/main/java/h04/chesspieces/Rook.java new file mode 100644 index 0000000..1935c62 --- /dev/null +++ b/src/main/java/h04/chesspieces/Rook.java @@ -0,0 +1,25 @@ +package h04.chesspieces; + +import fopbot.Robot; +//Wichtig für Implementation +//import h04.movement.MoveStrategy; +import h04.template.ChessUtils; + +import java.awt.Point; + +public class Rook extends Robot { + private final Team team; + + public Rook(final int x, final int y, final Team team){ + super(x, y, team == Team.WHITE ? Families.ROOK_WHITE : Families.ROOK_BLACK); + this.team = team; + } + + //Wichtig für Implementation + //@Override + public Team getTeam() { + return team; + } + + //TODO H4.5 +} diff --git a/src/main/java/h04/chesspieces/Team.java b/src/main/java/h04/chesspieces/Team.java new file mode 100644 index 0000000..8c4365b --- /dev/null +++ b/src/main/java/h04/chesspieces/Team.java @@ -0,0 +1,25 @@ +package h04.chesspieces; + +import java.awt.Color; + +public enum Team { + WHITE(Color.WHITE), + BLACK(Color.BLACK); + private final Color color; + + Team(final Color color) { + this.color = color; + } + + public Color getColor() { + return color; + } + + public boolean isOpponent(final Team other) { + return this != other; + } + + public Team getOpponent() { + return this == WHITE ? BLACK : WHITE; + } +} diff --git a/src/main/java/h04/template/ChessUtils.java b/src/main/java/h04/template/ChessUtils.java new file mode 100644 index 0000000..71394c7 --- /dev/null +++ b/src/main/java/h04/template/ChessUtils.java @@ -0,0 +1,82 @@ +package h04.template; + +import fopbot.World; +import h04.chesspieces.ChessPiece; +import h04.chesspieces.King; +import h04.chesspieces.Team; +import org.jetbrains.annotations.Nullable; + +import java.awt.Color; +import java.awt.Point; +import java.util.Optional; +import java.util.function.Predicate; + +public class ChessUtils { + + public static @Nullable ChessPiece getPieceAt(final int x, final int y) { + return World.getGlobalWorld().getField(x, y).getEntities() + .stream() + .filter(ChessPiece.class::isInstance) + .map(ChessPiece.class::cast) + .filter(Predicate.not(ChessPiece::isTurnedOff)) + .findFirst() + .orElse(null); + } + + public static @Nullable ChessPiece getPieceAt(final Point p) { + return getPieceAt(p.x, p.y); + } + + public static King[] getKings() { + return World.getGlobalWorld().getAllFieldEntities() + .stream() + .filter(King.class::isInstance) + .map(King.class::cast) + .toArray(King[]::new); + } + + /** + * Returns the team at the given position, or {@code null} if there is no team. + * + * @param x the x-coordinate + * @param y the y-coordinate + * @return the team at the given position, or {@code null} if there is no team + */ + public static @Nullable Team getTeamAt(final int x, final int y) { + return Optional.ofNullable(getPieceAt(x, y)) + .map(ChessPiece::getTeam) + .orElse(null); + } + + public static @Nullable Team getTeamAt(final Point p) { + return getTeamAt(p.x, p.y); + } + + public static boolean isValidCoordinate(final int x, final int y) { + return x >= 0 && x < 8 && y >= 0 && y < 8; + } + + public static boolean isValidCoordinate(final Point p) { + return isValidCoordinate(p.x, p.y); + } + + public static void setFieldColor(final Point field, final @Nullable Color c) { + World.getGlobalWorld().getField(field.x, field.y).setFieldColor(c); + } + + public static void colorMoveFields(final Point... fields) { + for (final Point field : fields) { + if (field == null) + continue; + setFieldColor(field, getPieceAt(field) != null ? Color.RED : Color.GREEN); + } + } + + public static void resetFieldColor() { + for (int y = 0; y < World.getHeight(); y++) { + for (int x = 0; x < World.getWidth(); x++) { + setFieldColor(new Point(x, y), null); + } + } + } +} diff --git a/src/main/java/h04/template/GameControllerTemplate.java b/src/main/java/h04/template/GameControllerTemplate.java new file mode 100644 index 0000000..f5686c9 --- /dev/null +++ b/src/main/java/h04/template/GameControllerTemplate.java @@ -0,0 +1,188 @@ +package h04.template; + +import fopbot.ColorProfile; +import fopbot.Robot; +import fopbot.World; +import h04.GameController; +import h04.template.InputHandler; +import h04.chesspieces.Bishop; +import h04.chesspieces.ChessPiece; +import h04.chesspieces.King; +import h04.chesspieces.Knight; +import h04.chesspieces.Pawn; +import h04.chesspieces.Queen; +import h04.chesspieces.Rook; +import h04.chesspieces.Team; +//Wichtig für Implementation +//import h04.movement.MoveStrategy; +//Wichtig für Implementation +//import h04.movement.TeleportingMoveStrategy; +//Wichtig für Implementation +//import h04.movement.WalkingMoveStrategy; +import org.jetbrains.annotations.Nullable; +import org.tudalgo.algoutils.student.io.PropertyUtils; + +import java.awt.Color; +import java.util.Arrays; +import java.util.Objects; + +/** + * A {@link GameControllerTemplate} controls the game loop and the {@link Robot}s and checks the win condition. + */ +public abstract class GameControllerTemplate { + /** + * The {@link InputHandler} that handles the input of the user. + */ + private final InputHandler inputHandler = new InputHandler((GameController) this); + + /** + * The {@link Robot}s that are controlled by the {@link GameControllerTemplate}. + */ + + protected Team nextToMove = Team.WHITE; + + protected boolean gameOver = false; + + protected @Nullable ChessPiece selectedPiece; + + //Wichtig für Implementation + /* + protected MoveStrategy moveStrategy = PropertyUtils.getBooleanProperty( + "h04.properties", + "USE_TELEPORT_MOVE_STRATEGY" + ) ? new TeleportingMoveStrategy() : new WalkingMoveStrategy(); + */ + + /** + * Starts the game loop. + */ + public void startGame() { + System.out.println("Starting game..."); + + while (!gameOver) { + final var point = inputHandler.getNextInput(nextToMove); + + //Wichtig für Implementation + /* + if (ChessUtils.getTeamAt(point) == nextToMove) { + // select piece + selectedPiece = ChessUtils.getPieceAt(point); + //highlight possible moves + final var possibleMoves = Objects.requireNonNull(selectedPiece).getPossibleMoveFields(); + ChessUtils.resetFieldColor(); + ChessUtils.colorMoveFields(possibleMoves); + continue; + } + if (selectedPiece != null) { + // check if piece can move to point + final var possibleMoves = selectedPiece.getPossibleMoveFields(); + if (Arrays.stream(possibleMoves) + .filter(Objects::nonNull) + .noneMatch(point::equals) + ) { + System.out.println("Invalid move"); + // deselect piece + selectedPiece = null; + ChessUtils.resetFieldColor(); + continue; + } + // valid move selected, move piece + final var oldPiece = ChessUtils.getPieceAt(point); + selectedPiece.moveStrategy( + point.x - selectedPiece.getX(), + point.y - selectedPiece.getY(), + moveStrategy + ); + if (oldPiece != null) { + oldPiece.turnOff(); + } + if (selectedPiece instanceof Pawn && (selectedPiece.getY() == 0 || selectedPiece.getY() == World.getHeight() - 1)) { + selectedPiece.turnOff(); + new Queen(selectedPiece.getX(), selectedPiece.getY(), selectedPiece.getTeam()); + } + ChessUtils.resetFieldColor(); + if (checkWinCondition()) stopGame(nextToMove); + + + nextToMove = nextToMove.getOpponent(); + selectedPiece = null; + } + */ + } + } + + public abstract boolean checkWinCondition(); + + + /** + * Stops the game loop. + */ + public void stopGame(final Team winner) { + gameOver = true; + inputHandler.setStatusText(winner.name() + " wins!"); + } + + /** + * Sets up the game. + */ + protected void setup() { + setupWorld(); + setupTheme(); + setupPieces(); + //this.inputHandler.install(); + } + + public void setupTheme() { + //noinspection UnstableApiUsage + World.getGlobalWorld().setColorProfile( + ColorProfile.DEFAULT.toBuilder() + .fieldColorLight(Color.decode("#e0ba97")) + .fieldColorDark(Color.decode("#8d4d2a")) + .customFieldColorPattern( + (cp, p) -> (p.x + p.y) % 2 == 0 ? cp.fieldColorLight() : cp.fieldColorDark() + ) + .backgroundColorDark(Color.decode("#8d4d2a")) + .backgroundColorLight(Color.decode("#8d4d2a")) + .innerBorderColorLight(new Color(0, 0, 0, 0)) + .innerBorderColorDark(new Color(0, 0, 0, 0)) + .fieldBorderThickness(0) + .outerBorderColorDark(Color.BLACK) + .outerBorderColorLight(Color.BLACK) + .build() + ); + } + + /** + * Initializes the {@link World} and adds the {@link Robot}s to it. + */ + public void setupWorld() { + World.setSize(8, 8); + + World.setDelay(0); + World.setVisible(true); + World.getGlobalWorld().setDrawTurnedOffRobots(false); + inputHandler.install(); + } + + public void setupPieces() { + for (final int y : new int[]{0, 1, World.getHeight() - 2, World.getHeight() - 1}) { + for (int x = 0; x < World.getWidth(); x++) { + if (y == 1 || y == World.getHeight() - 2) + new Pawn(x, y, y == 1 ? Team.WHITE : Team.BLACK); + else if (x == 0 || x == World.getWidth() - 1) { + new Rook(x, y, y == 0 ? Team.WHITE : Team.BLACK); + } else if (x == 1 || x == World.getWidth() - 2) { + new Knight(x, y, y == 0 ? Team.WHITE : Team.BLACK); + } else if (x == 2 || x == World.getWidth() - 3) { + new Bishop(x, y, y == 0 ? Team.WHITE : Team.BLACK); + } else if (x == 3) { + new Queen(x, y, y == 0 ? Team.WHITE : Team.BLACK); + } else if (x == World.getWidth() - 4) { + new King(x, y, y == 0 ? Team.WHITE : Team.BLACK); + } + } + } + } + + +} diff --git a/src/main/java/h04/template/InputHandler.java b/src/main/java/h04/template/InputHandler.java new file mode 100644 index 0000000..be7b499 --- /dev/null +++ b/src/main/java/h04/template/InputHandler.java @@ -0,0 +1,68 @@ +package h04.template; + +import fopbot.World; +import h04.GameController; +import h04.chesspieces.Team; + +import java.awt.Color; +import java.awt.Point; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.LinkedBlockingDeque; +import javax.swing.JLabel; +import java.beans.PropertyChangeEvent; + +public class InputHandler { + /** + * The input queue. + */ + private final BlockingDeque inputQueue = new LinkedBlockingDeque<>(); + + public final GameController controller; + + private final JLabel statusLabel = new JLabel(""); + + public InputHandler(final GameController controller) { + this.controller = controller; + } + + @SuppressWarnings("UnstableApiUsage") + public void install() { + final var guiPanel = World.getGlobalWorld().getGuiPanel(); + World.getGlobalWorld().getInputHandler().addFieldClickListener(e -> addInput(e.getField().getX(), e.getField().getY())); + statusLabel.setFont(statusLabel.getFont().deriveFont(20.0f)); + guiPanel.add(statusLabel, JLabel.CENTER); + guiPanel.addDarkModeChangeListener(this::onDarkModeChange); + // trigger dark mode change to set the correct color + guiPanel.setDarkMode(World.getGlobalWorld().getGuiPanel().isDarkMode()); + } + + public void onDarkModeChange(final PropertyChangeEvent e) { + final var darkMode = (boolean) e.getNewValue(); + statusLabel.setForeground(darkMode ? Color.white : Color.black); + } + + private void addInput(final int x, final int y) { + inputQueue.add(new Point(x,y)); + System.out.println("Added input: "+x+","+y); + } + + public Point getNextInput(final Team currentPlayer) { + + statusLabel.setText(currentPlayer.name()+" to move."); + + try { + return inputQueue.take(); + } catch (final InterruptedException e) { + throw new RuntimeException(e); + } + + } + + public JLabel getStatusLabel() { + return statusLabel; + } + + public void setStatusText(final String s) { + statusLabel.setText(s); + } +} diff --git a/src/main/resources/h04.properties b/src/main/resources/h04.properties new file mode 100644 index 0000000..dd353c4 --- /dev/null +++ b/src/main/resources/h04.properties @@ -0,0 +1,2 @@ +# Whether to use the TeleportMoveStrategy or not. If not, the WalkingMoveStrategy will be used. +USE_TELEPORT_MOVE_STRATEGY=false diff --git a/src/main/resources/pieces/bishop_black.svg b/src/main/resources/pieces/bishop_black.svg new file mode 100644 index 0000000..6b816b6 --- /dev/null +++ b/src/main/resources/pieces/bishop_black.svg @@ -0,0 +1,46 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/bishop_white.svg b/src/main/resources/pieces/bishop_white.svg new file mode 100644 index 0000000..29a08b2 --- /dev/null +++ b/src/main/resources/pieces/bishop_white.svg @@ -0,0 +1,47 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/king_black.svg b/src/main/resources/pieces/king_black.svg new file mode 100644 index 0000000..5c9c769 --- /dev/null +++ b/src/main/resources/pieces/king_black.svg @@ -0,0 +1,46 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/king_white.svg b/src/main/resources/pieces/king_white.svg new file mode 100644 index 0000000..46941f4 --- /dev/null +++ b/src/main/resources/pieces/king_white.svg @@ -0,0 +1,47 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/knight_black.svg b/src/main/resources/pieces/knight_black.svg new file mode 100644 index 0000000..942d016 --- /dev/null +++ b/src/main/resources/pieces/knight_black.svg @@ -0,0 +1,46 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/knight_white.svg b/src/main/resources/pieces/knight_white.svg new file mode 100644 index 0000000..e2b58fa --- /dev/null +++ b/src/main/resources/pieces/knight_white.svg @@ -0,0 +1,47 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/pawn_black.svg b/src/main/resources/pieces/pawn_black.svg new file mode 100644 index 0000000..d83505b --- /dev/null +++ b/src/main/resources/pieces/pawn_black.svg @@ -0,0 +1,46 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/pawn_white.svg b/src/main/resources/pieces/pawn_white.svg new file mode 100644 index 0000000..2c431d5 --- /dev/null +++ b/src/main/resources/pieces/pawn_white.svg @@ -0,0 +1,47 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/queen_black.svg b/src/main/resources/pieces/queen_black.svg new file mode 100644 index 0000000..7a378ec --- /dev/null +++ b/src/main/resources/pieces/queen_black.svg @@ -0,0 +1,46 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/queen_white.svg b/src/main/resources/pieces/queen_white.svg new file mode 100644 index 0000000..98e87c6 --- /dev/null +++ b/src/main/resources/pieces/queen_white.svg @@ -0,0 +1,47 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/rook_black.svg b/src/main/resources/pieces/rook_black.svg new file mode 100644 index 0000000..2787d91 --- /dev/null +++ b/src/main/resources/pieces/rook_black.svg @@ -0,0 +1,46 @@ + + + + + + + + + + diff --git a/src/main/resources/pieces/rook_white.svg b/src/main/resources/pieces/rook_white.svg new file mode 100644 index 0000000..670de3a --- /dev/null +++ b/src/main/resources/pieces/rook_white.svg @@ -0,0 +1,47 @@ + + + + + + + + + + diff --git a/src/test/java/h04/ExampleJUnitTest.java b/src/test/java/h04/ExampleJUnitTest.java new file mode 100644 index 0000000..e3cc28c --- /dev/null +++ b/src/test/java/h04/ExampleJUnitTest.java @@ -0,0 +1,16 @@ +package h04; + +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); + } +}