Compare commits

..

7 Commits

Author SHA1 Message Date
Hanmac
da886202c0 SacrificeEffect now use Remember on SpellAbility 2018-12-26 10:30:56 +01:00
Hanmac
4ab45ae42b AbilityUtils: calcAmount use new getRemembered 2018-12-25 21:37:43 +01:00
Hanmac
bae8819630 Manifest: RememberManifested to SpellAbility 2018-12-25 21:37:43 +01:00
Hanmac
19fbe18235 CountersRemoveAllEffect: use SpellAbility Remember 2018-12-25 21:37:43 +01:00
Hanmac
5e7d542d36 CounterRemove: move remember to SA 2018-12-25 21:37:43 +01:00
Hanmac
5e32834fb8 WrappedAbility: fix SpellAbility remember for trigger 2018-12-25 21:36:54 +01:00
Hanmac
738e68f468 SpellAbility: add Remember to SpellAbility 2018-12-25 21:36:54 +01:00
44757 changed files with 363907 additions and 1443719 deletions

7
.classpath Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="con" path="org.testng.TESTNG_CONTAINER"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@@ -1,38 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
type: 'Bug'
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@@ -1,21 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
type: 'Feature'
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@@ -1,176 +0,0 @@
name: Publish Desktop Forge
on:
workflow_dispatch:
inputs:
debug_enabled:
type: boolean
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
release_android:
type: boolean
description: 'Also try to release android build'
required: false
default: false
jobs:
build:
if: github.repository_owner == 'Card-Forge'
runs-on: ubuntu-latest
permissions:
contents: write
deployments: write
packages: write
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: 'maven'
server-id: cardforge-repo
server-username: ${{ secrets.FTP_USERNAME }}
server-password: ${{ secrets.FTP_PASSWORD }}
settings-path: ${{ github.workspace }} # location for the settings.xml file
- name: Install virtual framebuffer (if not available) to allow running GUI on a headless server
run: command -v Xvfb >/dev/null 2>&1 || { sudo apt update && sudo apt install -y xvfb; }
- name: Configure Git User
run: |
git config user.email "actions@github.com"
git config user.name "GitHub Actions"
- name: Install old maven (3.8.1)
run: |
curl -o apache-maven-3.8.1-bin.tar.gz https://archive.apache.org/dist/maven/maven-3/3.8.1/binaries/apache-maven-3.8.1-bin.tar.gz
tar xf apache-maven-3.8.1-bin.tar.gz
export PATH=$PWD/apache-maven-3.8.1/bin:$PATH
export MAVEN_HOME=$PWD/apache-maven-3.8.1
mvn --version
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && inputs.debug_enabled }}
- name: Setup android requirements
if: ${{ github.event_name == 'workflow_dispatch' && inputs.release_android }}
run: |
JAVA_HOME=${JAVA_HOME_17_X64} ${ANDROID_SDK_ROOT}/cmdline-tools/latest/bin/sdkmanager --sdk_root=$ANDROID_SDK_ROOT --install "build-tools;35.0.0" "platform-tools" "platforms;android-35"
cd forge-gui-android
echo "${{ secrets.FORGE_KEYSTORE }}" > forge.keystore.asc
gpg -d --passphrase "${{ secrets.FORGE_KEYSTORE_PASSPHRASE }}" --batch forge.keystore.asc > forge.keystore
cd -
mkdir -p ~/.m2/repository/com/simpligility/maven/plugins/android-maven-plugin/4.6.2
cd ~/.m2/repository/com/simpligility/maven/plugins/android-maven-plugin/4.6.2
curl -L -o android-maven-plugin-4.6.2.jar https://github.com/Card-Forge/android-maven-plugin/releases/download/4.6.2/android-maven-plugin-4.6.2.jar
curl -L -o android-maven-plugin-4.6.2.pom https://github.com/Card-Forge/android-maven-plugin/releases/download/4.6.2/android-maven-plugin-4.6.2.pom
cd -
mvn install -Dmaven.test.skip=true
mvn dependency:tree
- name: Build/Install/Publish Desktop to GitHub Packages Apache Maven
if: ${{ github.event_name == 'workflow_dispatch' && !inputs.release_android }}
run: |
export DISPLAY=":1"
Xvfb :1 -screen 0 800x600x8 &
export _JAVA_OPTIONS="-Xmx2g"
d=$(date +%m.%d)
# build only desktop and only try to move desktop files
mvn -U -B clean -P windows-linux install -DskipTests -Dskip.flatten=true -e -T 1C release:clean release:prepare release:perform
mkdir izpack
# move bz2 and jar from work dir to izpack dir
mv /home/runner/work/forge/forge/forge-installer/*/*.{bz2,jar} izpack/
# move desktop build.txt and version.txt to izpack
mv /home/runner/work/forge/forge/forge-gui-desktop/target/classes/*.txt izpack/
cd izpack
ls
echo "GIT_TAG=`echo $(git describe --tags --abbrev=0)`" >> $GITHUB_ENV
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Build/Install/Publish Desktop+Android to GitHub Packages Apache Maven
if: ${{ github.event_name == 'workflow_dispatch' && inputs.release_android }}
run: |
export DISPLAY=":1"
Xvfb :1 -screen 0 800x600x8 &
export _JAVA_OPTIONS="-Xmx2g"
d=$(date +%m.%d)
# build both desktop and android
mvn -U -B clean -P windows-linux,android-release-build install -e -Dcardforge-repo.username=${{ secrets.FTP_USERNAME }} -Dcardforge-repo.password=${{ secrets.FTP_PASSWORD }} -Dandroid.sdk.path=/usr/local/lib/android/sdk -Dandroid.buildToolsVersion=35.0.0
mkdir izpack
# move bz2 and jar from work dir to izpack dir
mv /home/runner/work/forge/forge/forge-installer/*/*.{bz2,jar} izpack/
# move desktop build.txt and version.txt to izpack
mv /home/runner/work/forge/forge/forge-gui-desktop/target/classes/*.txt izpack/
# move android apk and assets.zip
mv /home/runner/work/forge/forge/forge-gui-android/target/*-signed-aligned.apk izpack/
mv /home/runner/work/forge/forge/forge-gui-android/target/assets.zip izpack/
cd izpack
ls
echo "GIT_TAG=`echo $(git describe --tags --abbrev=0)`" >> $GITHUB_ENV
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Upload snapshot to GitHub Prerelease
uses: ncipollo/release-action@v1
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
name: Release ${{ env.GIT_TAG }}
tag: ${{ env.GIT_TAG }}
artifacts: izpack/*
allowUpdates: true
removeArtifacts: true
makeLatest: true
- name: 🔧 Install XML tools
run: |
sudo apt-get update
sudo apt-get install -y libxml2-utils
- name: 🔼 Bump versionCode in root POM
id: bump_version
run: |
cd /home/runner/work/forge/forge/
current_version=$(xmllint --xpath "//*[local-name()='versionCode']/text()" pom.xml)
echo "Current versionCode: $current_version"
IFS='.' read -r major minor patch <<< "${current_version}"
new_patch=$(printf "%02d" $((10#$patch + 1)))
new_version="${major}.${minor}.${new_patch}"
sed -i -E "s|<versionCode>.*</versionCode>|<versionCode>${new_version}</versionCode>|" pom.xml
echo "version_code=${new_version}" >> $GITHUB_OUTPUT
- name: ♻️ Restore {revision} in child POMs
run: |
find . -name pom.xml ! -path "./pom.xml" | while read -r pom; do
sed -i -E 's|<version>2\.0+\.[0-9]+(-SNAPSHOT)?</version>|<version>${revision}</version>|' "$pom"
done
- name: 💾 Commit restored {revision}
run: |
# Add only pom.xml files
find . -name pom.xml -exec git add {} \;
# Commit if there are changes
if git diff --cached --quiet; then
echo "No pom.xml changes to commit."
else
git commit -m "Restore POM files for preparation of next release" || echo "No changes to commit"
git push
fi
- name: Send failure notification to Discord
if: failure() # This step runs only if the job fails
run: |
curl -X POST -H "Content-Type: application/json" \
-d "{\"content\": \"🔴 Release Build Failed in branch: \`${{ github.ref_name }}\` by \`${{ github.actor }}\`.\nCheck logs: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\"}" \
${{ secrets.DISCORD_AUTOMATION_WEBHOOK }}

View File

@@ -1,89 +0,0 @@
name: Publish Android Release
on:
workflow_dispatch:
inputs:
debug_enabled:
type: boolean
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: write
deployments: write
packages: write
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: 'maven'
server-id: cardforge-repo
server-username: ${{ secrets.FTP_USERNAME }}
server-password: ${{ secrets.FTP_PASSWORD }}
settings-path: ${{ github.workspace }} # location for the settings.xml file
- name: Install old maven (3.8.1)
run: |
curl -o apache-maven-3.8.1-bin.tar.gz https://archive.apache.org/dist/maven/maven-3/3.8.1/binaries/apache-maven-3.8.1-bin.tar.gz
tar xf apache-maven-3.8.1-bin.tar.gz
export PATH=$PWD/apache-maven-3.8.1/bin:$PATH
export MAVEN_HOME=$PWD/apache-maven-3.8.1
mvn --version
- name: Install android SDK
uses: maxim-lobanov/setup-android-tools@v1
with:
packages: |
platforms;android-35
build-tools;35.0.0
- name: Install virtual framebuffer (if not available) to allow running GUI on a headless server
run: |
command -v Xvfb >/dev/null 2>&1 || { sudo apt update && sudo apt install -y xvfb; }
export DISPLAY=":1"
Xvfb :1 -screen 0 800x600x8 &
- name: Extract Android keystore
run: |
ls
cd forge-gui-android
echo "${{ secrets.FORGE_KEYSTORE }}" > forge.keystore.asc
gpg -d --passphrase "${{ secrets.FORGE_KEYSTORE_PASSPHRASE }}" --batch forge.keystore.asc > forge.keystore
cd -
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && inputs.debug_enabled }}
- name: Configure Git User
run: |
git config user.email "actions@github.com"
git config user.name "GitHub Actions"
- name: Install Android maven plugin
run: |
mkdir -p ~/.m2/repository/com/simpligility/maven/plugins/android-maven-plugin/4.6.2
cd ~/.m2/repository/com/simpligility/maven/plugins/android-maven-plugin/4.6.2
curl -L -o android-maven-plugin-4.6.2.jar https://github.com/Card-Forge/android-maven-plugin/releases/download/4.6.2/android-maven-plugin-4.6.2.jar
curl -L -o android-maven-plugin-4.6.2.pom https://github.com/Card-Forge/android-maven-plugin/releases/download/4.6.2/android-maven-plugin-4.6.2.pom
#mvn install:install-file -Dfile=android-maven-plugin-4.6.2.jar -DgroupId=com.simpligility.maven.plugins -DartifactId=android-maven-plugin -Dversion=4.6.2 -Dpackaging=jar
cd -
mvn install -Dmaven.test.skip=true
mvn dependency:tree
- name: Build/Install/Publish to GitHub Packages Apache Maven
run: |
export _JAVA_OPTIONS="-Xmx2g"
mvn -U -B -P android-release-build,android-release-upload install -e -Dcardforge-repo.username=${{ secrets.FTP_USERNAME }} -Dcardforge-repo.password=${{ secrets.FTP_PASSWORD }} -Dandroid.sdk.path=/usr/local/lib/android/sdk -Dandroid.buildToolsVersion=35.0.0 -Dmaven.test.skip=true
env:
GITHUB_TOKEN: ${{ github.token }}

View File

@@ -1,19 +0,0 @@
name: Remove stale branches
on:
workflow_dispatch:
schedule:
- cron: "0 0 * * *" # Everday at midnight
jobs:
remove-stale-branches:
if: github.repository_owner == 'Card-Forge'
name: Remove Stale Branches
runs-on: ubuntu-latest
steps:
- uses: fpicalausa/remove-stale-branches@v2.1.0
with:
dry-run: false # Check out the console output before setting this to false
ignore-unknown-authors: true
ignore-branches-with-open-prs: true
default-recipient: tehdiplomat

View File

@@ -1,132 +0,0 @@
name: Create Snapshot Desktop and Android
on:
workflow_dispatch:
inputs:
debug_enabled:
type: boolean
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
schedule:
# * is a special character in YAML so you have to quote this string
- cron: '00 18 * * *'
jobs:
build:
if: github.repository_owner == 'Card-Forge'
runs-on: ubuntu-latest
permissions:
contents: write
deployments: write
packages: write
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: 'maven'
server-id: cardforge-repo
server-username: ${{ secrets.FTP_USERNAME }}
server-password: ${{ secrets.FTP_PASSWORD }}
settings-path: ${{ github.workspace }} # location for the settings.xml file
- name: Install virtual framebuffer (if not available) to allow running GUI on a headless server
run: command -v Xvfb >/dev/null 2>&1 || { sudo apt update && sudo apt install -y xvfb; }
- name: Configure Git User
run: |
git config user.email "actions@github.com"
git config user.name "GitHub Actions"
- name: Install old maven (3.8.1)
run: |
curl -o apache-maven-3.8.1-bin.tar.gz https://archive.apache.org/dist/maven/maven-3/3.8.1/binaries/apache-maven-3.8.1-bin.tar.gz
tar xf apache-maven-3.8.1-bin.tar.gz
export PATH=$PWD/apache-maven-3.8.1/bin:$PATH
export MAVEN_HOME=$PWD/apache-maven-3.8.1
mvn --version
- name: Set Up Android tools
run: |
JAVA_HOME=${JAVA_HOME_17_X64} ${ANDROID_SDK_ROOT}/cmdline-tools/latest/bin/sdkmanager --sdk_root=$ANDROID_SDK_ROOT --install "build-tools;35.0.0" "platform-tools" "platforms;android-35"
- name: Extract Android keystore
run: |
ls
cd forge-gui-android
echo "${{ secrets.FORGE_KEYSTORE }}" > forge.keystore.asc
gpg -d --passphrase "${{ secrets.FORGE_KEYSTORE_PASSPHRASE }}" --batch forge.keystore.asc > forge.keystore
cd -
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && inputs.debug_enabled }}
- name: Install Android maven plugin
run: |
mkdir -p ~/.m2/repository/com/simpligility/maven/plugins/android-maven-plugin/4.6.2
cd ~/.m2/repository/com/simpligility/maven/plugins/android-maven-plugin/4.6.2
curl -L -o android-maven-plugin-4.6.2.jar https://github.com/Card-Forge/android-maven-plugin/releases/download/4.6.2/android-maven-plugin-4.6.2.jar
curl -L -o android-maven-plugin-4.6.2.pom https://github.com/Card-Forge/android-maven-plugin/releases/download/4.6.2/android-maven-plugin-4.6.2.pom
#mvn install:install-file -Dfile=android-maven-plugin-4.6.2.jar -DgroupId=com.simpligility.maven.plugins -DartifactId=android-maven-plugin -Dversion=4.6.2 -Dpackaging=jar
cd -
mvn install -Dmaven.test.skip=true
mvn dependency:tree
- name: Build/Install/Publish to GitHub Packages Apache Maven
run: |
export DISPLAY=":1"
Xvfb :1 -screen 0 800x600x8 &
export _JAVA_OPTIONS="-Xmx2g"
d=$(date +%m.%d)
# build both desktop and android
mvn -U -B clean -P windows-linux,android-release-build install -e -Dcardforge-repo.username=${{ secrets.FTP_USERNAME }} -Dcardforge-repo.password=${{ secrets.FTP_PASSWORD }} -Dandroid.sdk.path=/usr/local/lib/android/sdk -Dandroid.buildToolsVersion=35.0.0
mkdir izpack
# move bz2 and jar from work dir to izpack dir
mv /home/runner/work/forge/forge/forge-installer/*/*.{bz2,jar} izpack/
# move desktop build.txt and version.txt to izpack
mv /home/runner/work/forge/forge/forge-gui-desktop/target/classes/*.txt izpack/
# move android apk and assets.zip
mv /home/runner/work/forge/forge/forge-gui-android/target/*-signed-aligned.apk izpack/
mv /home/runner/work/forge/forge/forge-gui-android/target/assets.zip izpack/
cd izpack
# rename files and append date
for file in *.jar; do
bname="${file%.*}"
echo "file renamed to ${bname}-${d}.jar"
mv "${bname}.jar" "${bname}-${d}.jar"
done
for file in *.bz2; do
# remove .bz2
fname="${file%.*}"
# remove .tar
bname="${fname%.*}"
echo "file renamed to ${bname}-${d}.tar.bz2"
mv "${fname}.bz2" "${bname}-${d}.tar.bz2"
done
ls
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Upload snapshot to GitHub Prerelease
uses: ncipollo/release-action@v1
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
name: Daily Snapshot
tag: daily-snapshots
prerelease: true
artifacts: izpack/*
allowUpdates: true
removeArtifacts: true
- name: Send failure notification to Discord
if: failure() # This step runs only if the job fails
run: |
curl -X POST -H "Content-Type: application/json" \
-d "{\"content\": \"🔴 Snapshot Build Failed in branch: \`${{ github.ref_name }}\` by \`${{ github.actor }}\`.\nCheck logs: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\"}" \
${{ secrets.DISCORD_AUTOMATION_WEBHOOK }}

View File

@@ -1,114 +0,0 @@
name: Create Android Snapshot
on:
workflow_dispatch:
inputs:
debug_enabled:
type: boolean
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
#upload_package:
# type: boolean
# description: 'Upload the completed Android package'
# required: false
# default: true
jobs:
build:
if: github.repository_owner == 'Card-Forge'
runs-on: ubuntu-latest
permissions:
contents: write
deployments: write
packages: write
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: 'maven'
server-id: cardforge-repo
server-username: ${{ secrets.FTP_USERNAME }}
server-password: ${{ secrets.FTP_PASSWORD }}
settings-path: ${{ github.workspace }} # location for the settings.xml file
- name: Install old maven (3.8.1)
run: |
curl -o apache-maven-3.8.1-bin.tar.gz https://archive.apache.org/dist/maven/maven-3/3.8.1/binaries/apache-maven-3.8.1-bin.tar.gz
tar xf apache-maven-3.8.1-bin.tar.gz
export PATH=$PWD/apache-maven-3.8.1/bin:$PATH
export MAVEN_HOME=$PWD/apache-maven-3.8.1
mvn --version
- name: Set Up Android tools
run: |
JAVA_HOME=${JAVA_HOME_17_X64} ${ANDROID_SDK_ROOT}/cmdline-tools/latest/bin/sdkmanager --sdk_root=$ANDROID_SDK_ROOT --install "build-tools;35.0.0" "platform-tools" "platforms;android-35"
- name: Install virtual framebuffer (if not available) to allow running GUI on a headless server
run: |
command -v Xvfb >/dev/null 2>&1 || { sudo apt update && sudo apt install -y xvfb; }
export DISPLAY=":1"
Xvfb :1 -screen 0 800x600x8 &
- name: Extract Android keystore
run: |
ls
cd forge-gui-android
echo "${{ secrets.FORGE_KEYSTORE }}" > forge.keystore.asc
gpg -d --passphrase "${{ secrets.FORGE_KEYSTORE_PASSPHRASE }}" --batch forge.keystore.asc > forge.keystore
cd -
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && inputs.debug_enabled }}
- name: Configure Git User
run: |
git config user.email "actions@github.com"
git config user.name "GitHub Actions"
- name: Install Android maven plugin
run: |
mkdir -p ~/.m2/repository/com/simpligility/maven/plugins/android-maven-plugin/4.6.2
cd ~/.m2/repository/com/simpligility/maven/plugins/android-maven-plugin/4.6.2
curl -L -o android-maven-plugin-4.6.2.jar https://github.com/Card-Forge/android-maven-plugin/releases/download/4.6.2/android-maven-plugin-4.6.2.jar
curl -L -o android-maven-plugin-4.6.2.pom https://github.com/Card-Forge/android-maven-plugin/releases/download/4.6.2/android-maven-plugin-4.6.2.pom
#mvn install:install-file -Dfile=android-maven-plugin-4.6.2.jar -DgroupId=com.simpligility.maven.plugins -DartifactId=android-maven-plugin -Dversion=4.6.2 -Dpackaging=jar
cd -
mvn install -Dmaven.test.skip=true
mvn dependency:tree
- name: Build/Install/Publish to GitHub Packages Apache Maven
run: |
export _JAVA_OPTIONS="-Xmx2g"
mvn -U -B -P android-release-build install -e -Dcardforge-repo.username=${{ secrets.FTP_USERNAME }} -Dcardforge-repo.password=${{ secrets.FTP_PASSWORD }} -Dandroid.sdk.path=/usr/local/lib/android/sdk -Dandroid.buildToolsVersion=35.0.0 -Dmaven.test.skip=true
mkdir upload
mv /home/runner/work/forge/forge/forge-gui-android/target/*-signed-aligned.apk upload/
mv /home/runner/work/forge/forge/forge-gui-android/target/assets.zip upload/
mv /home/runner/work/forge/forge/forge-gui-android/target/classes/assets/version.txt upload/
cd upload
ls
env:
GITHUB_TOKEN: ${{ github.token }}
- name: 📂 Sync files
uses: SamKirkland/FTP-Deploy-Action@v4.3.4
#if: ${{ inputs.upload_package }}
with:
server: ftp.cardforge.org
username: ${{ secrets.FTP_USERNAME }}
password: ${{ secrets.FTP_PASSWORD }}
local-dir: upload/
server-dir: downloads/dailysnapshots/
state-name: .ftp-deploy-android-sync-state.json
- name: Send failure notification to Discord
if: failure() # This step runs only if the job fails
run: |
curl -X POST -H "Content-Type: application/json" \
-d "{\"content\": \"🔴 Android Snapshot Build Failed in branch: \`${{ github.ref_name }}\` by \`${{ github.actor }}\`.\nCheck logs: ${{ github.run_url }}\"}" \
${{ secrets.DISCORD_AUTOMATION_WEBHOOK }}

View File

@@ -1,95 +0,0 @@
name: Create Desktop Snapshot
on:
workflow_dispatch:
inputs:
debug_enabled:
type: boolean
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
jobs:
build:
if: github.repository_owner == 'Card-Forge'
runs-on: ubuntu-latest
permissions:
contents: write
deployments: write
packages: write
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: 'maven'
server-id: cardforge-repo
server-username: ${{ secrets.FTP_USERNAME }}
server-password: ${{ secrets.FTP_PASSWORD }}
settings-path: ${{ github.workspace }} # location for the settings.xml file
- name: Install virtual framebuffer (if not available) to allow running GUI on a headless server
run: command -v Xvfb >/dev/null 2>&1 || { sudo apt update && sudo apt install -y xvfb; }
- name: Configure Git User
run: |
git config user.email "actions@github.com"
git config user.name "GitHub Actions"
- name: Build/Install Snapshot
run: |
export DISPLAY=":1"
Xvfb :1 -screen 0 800x600x8 &
mvn -U -B clean -P windows-linux install -T 1C -Dcardforge-repo.username=${{ secrets.FTP_USERNAME }} -Dcardforge-repo.password=${{ secrets.FTP_PASSWORD }}
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && inputs.debug_enabled }}
- name: Rename before upload
run: |
mkdir izpack
# move bz2 and jar from work dir to izpack dir
mv /home/runner/work/forge/forge/forge-installer/*/*.{bz2,jar} izpack/
# move desktop build.txt to izpack
mv /home/runner/work/forge/forge/forge-gui-desktop/target/classes/build.txt izpack/
cd izpack
d=$(date +%m.%d)
# rename files and append date
for file in *.jar; do
bname="${file%.*}"
echo "file renamed to ${bname}-${d}.jar"
mv "${bname}.jar" "${bname}-${d}.jar"
done
for file in *.bz2; do
# remove .bz2
fname="${file%.*}"
# remove .tar
bname="${fname%.*}"
echo "file renamed to ${bname}-${d}.tar.bz2"
mv "${fname}.bz2" "${bname}-${d}.tar.bz2"
done
- name: 📂 Sync files
uses: SamKirkland/FTP-Deploy-Action@v4.3.4
with:
server: ftp.cardforge.org
username: ${{ secrets.FTP_USERNAME }}
password: ${{ secrets.FTP_PASSWORD }}
local-dir: izpack/
server-dir: downloads/dailysnapshots/
exclude: |
*.pom
*.repositories
*.xml
- name: Send failure notification to Discord
if: failure() # This step runs only if the job fails
run: |
curl -X POST -H "Content-Type: application/json" \
-d "{\"content\": \"🔴 Desktop Snapshot Build Failed in branch: \`${{ github.ref_name }}\` by \`${{ github.actor }}\`.\nCheck logs: ${{ github.run_url }}\"}" \
${{ secrets.DISCORD_AUTOMATION_WEBHOOK }}

View File

@@ -1,34 +0,0 @@
# This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time.
#
# You can adjust the behavior by modifying this file.
# For more information, see:
# https://github.com/actions/stale
name: Mark stale issues and pull requests
on:
schedule:
- cron: '21 9 * * *'
jobs:
stale:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v5
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: "This issue has not been updated in a while and has now been marked as stale. Stale messages will be auto closed."
stale-pr-message: 'This PR has not been updated in a while nad has been marked on stale. Stale PRs will be auto closed'
close-issue-message: 'This issue was closed because it has been stalled for 5 days with no activity.'
stale-issue-label: 'no-issue-activity'
stale-pr-label: 'no-pr-activity'
exempt-issue-labels: 'keep'
exempt-pr-labels: 'awaiting-approval,work-in-progress,keep'
days-before-issue-stale: 30
days-before-pr-stale: 45
days-before-issue-close: 5
days-before-pr-close: 10

View File

@@ -1,60 +0,0 @@
name: Test Android build
on:
push:
paths: [ 'forge-gui-android/**' ]
pull_request:
paths: [ 'forge-gui-android/**' ]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: write
deployments: write
packages: write
strategy:
matrix:
java: [ '17' ]
name: Test with Java ${{ matrix.Java }}
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: ${{ matrix.java }}
distribution: 'temurin'
cache: 'maven'
- name: Install old maven (3.8.1)
run: |
curl -o apache-maven-3.8.1-bin.tar.gz https://archive.apache.org/dist/maven/maven-3/3.8.1/binaries/apache-maven-3.8.1-bin.tar.gz
tar xf apache-maven-3.8.1-bin.tar.gz
export PATH=$PWD/apache-maven-3.8.1/bin:$PATH
export MAVEN_HOME=$PWD/apache-maven-3.8.1
mvn --version
- name: Set Up Android tools
run: |
JAVA_HOME=${JAVA_HOME_17_X64} ${ANDROID_SDK_ROOT}/cmdline-tools/latest/bin/sdkmanager --sdk_root=$ANDROID_SDK_ROOT --install "build-tools;35.0.0" "platform-tools" "platforms;android-35"
- name: Install Android maven plugin
run: |
mkdir -p ~/.m2/repository/com/simpligility/maven/plugins/android-maven-plugin/4.6.2
cd ~/.m2/repository/com/simpligility/maven/plugins/android-maven-plugin/4.6.2
curl -L -o android-maven-plugin-4.6.2.jar https://github.com/Card-Forge/android-maven-plugin/releases/download/4.6.2/android-maven-plugin-4.6.2.jar
curl -L -o android-maven-plugin-4.6.2.pom https://github.com/Card-Forge/android-maven-plugin/releases/download/4.6.2/android-maven-plugin-4.6.2.pom
#mvn install:install-file -Dfile=android-maven-plugin-4.6.2.jar -DgroupId=com.simpligility.maven.plugins -DartifactId=android-maven-plugin -Dversion=4.6.2 -Dpackaging=jar
cd -
mvn install -Dmaven.test.skip=true
mvn dependency:tree
- name: Install virtual framebuffer (if not available) to allow running GUI on a headless server
run: command -v Xvfb >/dev/null 2>&1 || { sudo apt update && sudo apt install -y xvfb; }
- name: Run build in virtual framebuffer
run: |
export DISPLAY=":1"
Xvfb :1 -screen 0 800x600x8 &
mvn -U -B -P android-test-build verify -e -T 1C -Dandroid.sdk.path=$ANDROID_SDK_ROOT -Dandroid.buildToolsVersion=35.0.0 -Dmaven.test.skip=true

View File

@@ -1,29 +0,0 @@
name: Test build
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
java: ['17', '21']
name: Test with Java ${{ matrix.Java }}
steps:
- uses: actions/checkout@v3
- name: Setup java
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
cache: 'maven'
- name: Install virtual framebuffer (if not available) to allow running GUI on a headless server
run: command -v Xvfb >/dev/null 2>&1 || { sudo apt update && sudo apt install -y xvfb; }
- name: Run tests in virtual framebuffer
run: |
export DISPLAY=":1"
Xvfb :1 -screen 0 800x600x8 &
mvn -U -B clean test

View File

@@ -1,48 +0,0 @@
name: Maven test for settings
on:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: write
deployments: write
packages: write
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: 'maven'
server-id: cardforge-repo
server-username: ${{ secrets.FTP_USERNAME }}
server-password: ${{ secrets.FTP_PASSWORD }}
settings-path: ${{ github.workspace }} # location for the settings.xml file
- name: Check settings after java setup
run: |
cat ${{ github.workspace }}/settings.xml
- name: maven-settings-xml-action
uses: whelk-io/maven-settings-xml-action@v20
with:
servers: '[{ "id": "cardforge-repo", "username": "${{ secrets.FTP_USERNAME }}", "password": "Fake_password" }]'
- name: Check settings after xml action
run: |
cat ~/.m2/settings.xml
- name: Check settings after xml action
run: |
cat ${{ github.workspace }}/.mvn/local-settings.xml
- name: Where are maven settings
run: |
mvn -X clean -Dcardforge-repo.username=${{ secrets.FTP_USERNAME }} -Dcardforge-repo.password=${{ secrets.FTP_PASSWORD }} | grep "settings"

305
.gitignore vendored
View File

@@ -1,96 +1,233 @@
# Ignore IDEA config files
*.idea
*.iml
*.tmp
.metadata
.recommenders
# Ignore Eclipse config files
.settings
.classpath
.project
.checkstyle
# Ignore VS Code config files
.vscode/settings.json
.vscode/launch.json
.factorypath
# Ignore NetBeans config files
nbactions.xml
# Ignore flattened pom
.flattened-pom.xml
# Ignore binaries, temp files and test output, everywhere
target
test-output
bin
gen
*.log
# Ignore macOS Spotlight rubbish
.DS_Store
# ignore vim swapfiles
*.swp
# TODO: specify what these ignores are for (releasing?)
forge.profile.properties
/jgv.txt
pom.xml.next
pom.xml.releaseBackup
pom.xml.tag
release.properties
# Ignore mobile-related resources
forge-gui-android/res/*/*
!forge-gui-android/res/*/ic_launcher.png
!forge-gui-android/res/*/ic_launcher*.png
!forge-gui-android/res/layout/main.xml
/*.idea
/*.iml
/*.tmp
/.metadata
/.recommenders
forge-ai/forge-ai.iml
forge-ai/target
forge-core/forge-core.iml
forge-core/target
forge-game/*.iml
forge-game/target
forge-gui-android/*.iml
forge-gui-android/*.keystore
forge-gui-android/**/Thumbs.db
forge-gui-mobile-dev/**/Thumbs.db
forge-gui-android/assets/fallback_skin/Thumbs.db
forge-gui-android/bin
forge-gui-android/gen
forge-gui-android/res/Thumbs.db
forge-gui-android/res/bin
forge-gui-android/res/drawable-hdpi/Thumbs.db
forge-gui-android/res/drawable-hdpi/bin
forge-gui-android/res/drawable-hdpi/gen
forge-gui-android/res/drawable-hdpi/target
forge-gui-android/res/drawable-ldpi/Thumbs.db
forge-gui-android/res/drawable-ldpi/bin
forge-gui-android/res/drawable-ldpi/gen
forge-gui-android/res/drawable-ldpi/target
forge-gui-android/res/drawable-mdpi/Thumbs.db
forge-gui-android/res/drawable-mdpi/bin
forge-gui-android/res/drawable-mdpi/gen
forge-gui-android/res/drawable-mdpi/target
forge-gui-android/res/drawable-xhdpi/Thumbs.db
forge-gui-android/res/drawable-xhdpi/bin
forge-gui-android/res/drawable-xhdpi/gen
forge-gui-android/res/drawable-xhdpi/target
forge-gui-android/res/drawable-xxhdpi/Thumbs.db
forge-gui-android/res/drawable-xxhdpi/bin
forge-gui-android/res/drawable-xxhdpi/gen
forge-gui-android/res/drawable-xxhdpi/target
forge-gui-android/res/gen
forge-gui-android/res/layout/Thumbs.db
forge-gui-android/res/layout/bin
forge-gui-android/res/layout/gen
forge-gui-android/res/layout/target
forge-gui-android/res/target
forge-gui-android/res/values/Thumbs.db
forge-gui-android/res/values/bin
forge-gui-android/res/values/gen
forge-gui-android/res/values/target
forge-gui-android/target
forge-gui-desktop/*.iml
forge-gui-desktop/target
forge-gui-ios/*.iml
forge-gui-ios/target
forge-gui-mobile-dev/*.iml
forge-gui-mobile-dev/bin
forge-gui-mobile-dev/fallback_skin/Thumbs.db
forge-gui-mobile-dev/res
forge-gui-mobile-dev/target
forge-gui-mobile-dev/testAssets
forge-gui/res/cardsfolder/*.bat
# Generated changelog file
forge-gui/release-files/CHANGES.txt
forge-gui-mobile/*.iml
forge-gui-mobile/bin
forge-gui-mobile/target
forge-gui/forge-gui.iml
forge-gui/forge.profile.properties
forge-gui/res/*.log
forge-gui/res/PerSetTrackingResults
forge-gui/res/cardsfolder/*.bat
forge-gui/res/decks
forge-gui/res/layouts
forge-gui/res/pics*
forge-gui/res/pics_product
forge-gui/res/skins/**/PerSetTrackingResults
forge-gui/res/skins/**/decks
forge-gui/res/skins/**/layouts
forge-gui/res/skins/**/pics*
forge-gui/res/skins/**/pics_product
forge-gui/res/quest/world/1996-05[!!-~]Ice[!!-~]Age/duels/.directory
forge-gui/res/skins/*.log
forge-gui/res/skins/PerSetTrackingResults
forge-gui/res/skins/Thumbs.db
forge-gui/res/skins/arabian_nights/*.log
forge-gui/res/skins/arabian_nights/PerSetTrackingResults
forge-gui/res/skins/arabian_nights/Thumbs.db
forge-gui/res/skins/arabian_nights/decks
forge-gui/res/skins/arabian_nights/layouts
forge-gui/res/skins/arabian_nights/pics*
forge-gui/res/skins/arabian_nights/pics_product
forge-gui/res/skins/comic/*.log
forge-gui/res/skins/comic/PerSetTrackingResults
forge-gui/res/skins/comic/Thumbs.db
forge-gui/res/skins/comic/decks
forge-gui/res/skins/comic/layouts
forge-gui/res/skins/comic/pics*
forge-gui/res/skins/comic/pics_product
forge-gui/res/skins/dark_ascension/*.log
forge-gui/res/skins/dark_ascension/PerSetTrackingResults
forge-gui/res/skins/dark_ascension/Thumbs.db
forge-gui/res/skins/dark_ascension/decks
forge-gui/res/skins/dark_ascension/layouts
forge-gui/res/skins/dark_ascension/pics*
forge-gui/res/skins/dark_ascension/pics_product
forge-gui/res/skins/decks
forge-gui/res/skins/default/*.log
forge-gui/res/skins/default/PerSetTrackingResults
forge-gui/res/skins/default/Thumbs.db
forge-gui/res/skins/default/decks
forge-gui/res/skins/default/layouts
forge-gui/res/skins/default/pics*
forge-gui/res/skins/default/pics_product
forge-gui/res/skins/firebloom/*.log
forge-gui/res/skins/firebloom/PerSetTrackingResults
forge-gui/res/skins/firebloom/Thumbs.db
forge-gui/res/skins/firebloom/decks
forge-gui/res/skins/firebloom/layouts
forge-gui/res/skins/firebloom/pics*
forge-gui/res/skins/firebloom/pics_product
forge-gui/res/skins/inferno/*.log
forge-gui/res/skins/inferno/PerSetTrackingResults
forge-gui/res/skins/inferno/Thumbs.db
forge-gui/res/skins/inferno/decks
forge-gui/res/skins/inferno/layouts
forge-gui/res/skins/inferno/pics*
forge-gui/res/skins/inferno/pics_product
forge-gui/res/skins/innistrad/*.log
forge-gui/res/skins/innistrad/PerSetTrackingResults
forge-gui/res/skins/innistrad/Thumbs.db
forge-gui/res/skins/innistrad/decks
forge-gui/res/skins/innistrad/layouts
forge-gui/res/skins/innistrad/pics*
forge-gui/res/skins/innistrad/pics_product
forge-gui/res/skins/journeyman/*.log
forge-gui/res/skins/journeyman/PerSetTrackingResults
forge-gui/res/skins/journeyman/Thumbs.db
forge-gui/res/skins/journeyman/decks
forge-gui/res/skins/journeyman/layouts
forge-gui/res/skins/journeyman/pics*
forge-gui/res/skins/journeyman/pics_product
forge-gui/res/skins/kamigawa/*.log
forge-gui/res/skins/kamigawa/PerSetTrackingResults
forge-gui/res/skins/kamigawa/Thumbs.db
forge-gui/res/skins/kamigawa/decks
forge-gui/res/skins/kamigawa/layouts
forge-gui/res/skins/kamigawa/pics*
forge-gui/res/skins/kamigawa/pics_product
forge-gui/res/skins/layouts
forge-gui/res/skins/marble_blue/*.log
forge-gui/res/skins/marble_blue/PerSetTrackingResults
forge-gui/res/skins/marble_blue/Thumbs.db
forge-gui/res/skins/marble_blue/decks
forge-gui/res/skins/marble_blue/layouts
forge-gui/res/skins/marble_blue/pics*
forge-gui/res/skins/marble_blue/pics_product
forge-gui/res/skins/metalcraft/*.log
forge-gui/res/skins/metalcraft/PerSetTrackingResults
forge-gui/res/skins/metalcraft/Thumbs.db
forge-gui/res/skins/metalcraft/decks
forge-gui/res/skins/metalcraft/layouts
forge-gui/res/skins/metalcraft/pics*
forge-gui/res/skins/metalcraft/pics_product
forge-gui/res/skins/mythic_rare/*.log
forge-gui/res/skins/mythic_rare/PerSetTrackingResults
forge-gui/res/skins/mythic_rare/Thumbs.db
forge-gui/res/skins/mythic_rare/decks
forge-gui/res/skins/mythic_rare/layouts
forge-gui/res/skins/mythic_rare/pics*
forge-gui/res/skins/mythic_rare/pics_product
forge-gui/res/skins/phyrexia/*.log
forge-gui/res/skins/phyrexia/PerSetTrackingResults
forge-gui/res/skins/phyrexia/Thumbs.db
forge-gui/res/skins/phyrexia/decks
forge-gui/res/skins/phyrexia/layouts
forge-gui/res/skins/phyrexia/pics*
forge-gui/res/skins/phyrexia/pics_product
forge-gui/res/skins/pics*
forge-gui/res/skins/pics_product
forge-gui/res/skins/ravnica/*.log
forge-gui/res/skins/ravnica/PerSetTrackingResults
forge-gui/res/skins/ravnica/Thumbs.db
forge-gui/res/skins/ravnica/decks
forge-gui/res/skins/ravnica/layouts
forge-gui/res/skins/ravnica/pics*
forge-gui/res/skins/ravnica/pics_product
forge-gui/res/skins/rebel/*.log
forge-gui/res/skins/rebel/PerSetTrackingResults
forge-gui/res/skins/rebel/Thumbs.db
forge-gui/res/skins/rebel/decks
forge-gui/res/skins/rebel/layouts
forge-gui/res/skins/rebel/pics*
forge-gui/res/skins/rebel/pics_product
forge-gui/res/skins/sleeping_forest/*.log
forge-gui/res/skins/sleeping_forest/PerSetTrackingResults
forge-gui/res/skins/sleeping_forest/Thumbs.db
forge-gui/res/skins/sleeping_forest/decks
forge-gui/res/skins/sleeping_forest/layouts
forge-gui/res/skins/sleeping_forest/pics*
forge-gui/res/skins/sleeping_forest/pics_product
forge-gui/res/skins/smith/*.log
forge-gui/res/skins/smith/PerSetTrackingResults
forge-gui/res/skins/smith/Thumbs.db
forge-gui/res/skins/smith/decks
forge-gui/res/skins/smith/layouts
forge-gui/res/skins/smith/pics*
forge-gui/res/skins/smith/pics_product
forge-gui/res/skins/the_dale/*.log
forge-gui/res/skins/the_dale/PerSetTrackingResults
forge-gui/res/skins/the_dale/Thumbs.db
forge-gui/res/skins/the_dale/decks
forge-gui/res/skins/the_dale/layouts
forge-gui/res/skins/the_dale/pics*
forge-gui/res/skins/the_dale/pics_product
forge-gui/res/skins/the_simpsons/*.log
forge-gui/res/skins/the_simpsons/PerSetTrackingResults
forge-gui/res/skins/the_simpsons/Thumbs.db
forge-gui/res/skins/the_simpsons/decks
forge-gui/res/skins/the_simpsons/layouts
forge-gui/res/skins/the_simpsons/pics*
forge-gui/res/skins/the_simpsons/pics_product
forge-gui/res/skins/zendikar/*.log
forge-gui/res/skins/zendikar/PerSetTrackingResults
forge-gui/res/skins/zendikar/Thumbs.db
forge-gui/res/skins/zendikar/decks
forge-gui/res/skins/zendikar/layouts
forge-gui/res/skins/zendikar/pics*
forge-gui/res/skins/zendikar/pics_product
forge-gui/target
forge-gui/tools/AllCards.json
forge-gui/tools/EditionTrackingResults
forge-gui/tools/PerSetTrackingResults
*.tiled-session
/forge-gui/res/adventure/*.tiled-project
/forge-gui/res/adventure/*.tiled-session
# Ignore python temporaries
__pycache__
*.pyc
forge-gui/tools/oracleScript.log
/forge.profile.properties
/jgv.txt
/nbactions.xml
/pom.xml.next
/pom.xml.releaseBackup
/pom.xml.tag
/release.properties
/target
/test-output

View File

@@ -1,11 +0,0 @@
<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 http://maven.apache.org/xsd/settings-1.2.0.xsd">
<servers>
<server>
<id>cardforge-repo</id>
<username>${cardforge-repo.username}</username>
<password>${cardforge-repo.password}</password>
</server>
</servers>
</settings>

View File

@@ -1,2 +0,0 @@
--settings
./.mvn/local-settings.xml

12
.project Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>forge</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,7 @@
add_header=true
add_todo=false
eclipse.preferences.version=1
header_text=/*\n * Forge\: Play Magic\: the Gathering.\n * Copyright (C) 2011 Forge Team\n *\n * This program is free software\: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http\://www.gnu.org/licenses/>.\n */
project_specific_settings=true
replacements=<?xml version\="1.0" standalone\="yes"?>\n\n<replacements>\n<replacement key\="get" scope\="1" mode\="0">Gets the</replacement>\n<replacement key\="set" scope\="1" mode\="0">Sets the</replacement>\n<replacement key\="add" scope\="1" mode\="0">Adds the</replacement>\n<replacement key\="edit" scope\="1" mode\="0">Edits the</replacement>\n<replacement key\="remove" scope\="1" mode\="0">Removes the</replacement>\n<replacement key\="init" scope\="1" mode\="0">Inits the</replacement>\n<replacement key\="parse" scope\="1" mode\="0">Parses the</replacement>\n<replacement key\="create" scope\="1" mode\="0">Creates the</replacement>\n<replacement key\="build" scope\="1" mode\="0">Builds the</replacement>\n<replacement key\="is" scope\="1" mode\="0">Checks if is</replacement>\n<replacement key\="print" scope\="1" mode\="0">Prints the</replacement>\n<replacement key\="has" scope\="1" mode\="0">Checks for</replacement>\n</replacements>\n\n
visibility_private=false

View File

@@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@@ -0,0 +1,284 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.7
org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
org.eclipse.jdt.core.formatter.alignment_for_assignment=0
org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80
org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0
org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0
org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16
org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16
org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16
org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16
org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
org.eclipse.jdt.core.formatter.blank_lines_after_package=1
org.eclipse.jdt.core.formatter.blank_lines_before_field=0
org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0
org.eclipse.jdt.core.formatter.blank_lines_before_imports=1
org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1
org.eclipse.jdt.core.formatter.blank_lines_before_method=1
org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
org.eclipse.jdt.core.formatter.blank_lines_before_package=0
org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1
org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1
org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line
org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line
org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line
org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line
org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line
org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line
org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line
org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line
org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line
org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line
org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false
org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false
org.eclipse.jdt.core.formatter.comment.format_block_comments=true
org.eclipse.jdt.core.formatter.comment.format_header=false
org.eclipse.jdt.core.formatter.comment.format_html=true
org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true
org.eclipse.jdt.core.formatter.comment.format_line_comments=true
org.eclipse.jdt.core.formatter.comment.format_source_code=true
org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true
org.eclipse.jdt.core.formatter.comment.indent_root_tags=true
org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert
org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert
org.eclipse.jdt.core.formatter.comment.line_length=80
org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true
org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true
org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false
org.eclipse.jdt.core.formatter.compact_else_if=true
org.eclipse.jdt.core.formatter.continuation_indentation=2
org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2
org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off
org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on
org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false
org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true
org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true
org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true
org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true
org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true
org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true
org.eclipse.jdt.core.formatter.indent_empty_lines=false
org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false
org.eclipse.jdt.core.formatter.indentation.size=4
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert
org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert
org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert
org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert
org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert
org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert
org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert
org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert
org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert
org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert
org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert
org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert
org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert
org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert
org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert
org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert
org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert
org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert
org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert
org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert
org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert
org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
org.eclipse.jdt.core.formatter.join_lines_in_comments=true
org.eclipse.jdt.core.formatter.join_wrapped_lines=true
org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false
org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false
org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
org.eclipse.jdt.core.formatter.lineSplit=120
org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false
org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
org.eclipse.jdt.core.formatter.tabulation.char=space
org.eclipse.jdt.core.formatter.tabulation.size=4
org.eclipse.jdt.core.formatter.use_on_off_tags=false
org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=true
org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true
org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@@ -1,195 +0,0 @@
# Contributing to Forge
[Official repo](https://github.com/Card-Forge/forge.git).
Dev instructions here: [Getting Started](https://github.com/Card-Forge/forge/wiki) (Somewhat outdated)
## Requirements / Tools
- your favourite Java IDE (IntelliJ, Eclipse, VSCodium, Emacs, Vi...)
- Java JDK 17 or later
- Git
- Git client (optional)
- Maven
- GitHub account
- Libgdx (optional: familiarity with this library is helpful for mobile platform development)
- Android SDK (optional: for Android releases)
- RoboVM (optional: for iOS releases) (TBD: Current status of support by libgdx)
## Project Quick Setup
- Login into GitHub with your user account and fork the project.
- Clone your forked project to your local machine
- Go to the project location on your machine. Run Maven to download all dependencies and build a snapshot. Example for Windows & Linux: `mvn -U -B clean -P windows-linux install`
## IntelliJ
IntelliJ is the recommended IDE for Forge development. Quick start guide for [setting up the Forge project within IntelliJ](https://github.com/Card-Forge/forge/wiki/IntelliJ-setup).
## Eclipse
Eclipse includes Maven integration so a separate install is not necessary. For other IDEs, your mileage may vary.
At this time, Eclipse is not the recommended IDE for Forge development.
### Project Setup
- Follow the instructions for cloning from GitHub. You'll need to setup an account and your SSH key.
If you are on a Windows machine you can use Putty with TortoiseGit for SSH keys. Run puttygen.exe to generate the key -- save the private key and export
the OpenSSH public key. If you just leave the dialog open, you can copy and paste the key from it to your GitHub profile under
"SSH keys". Run pageant.exe and add the private key generated earlier. TortoiseGit will use this for accessing GitHub.
- Fork the Forge git repo to your GitHub account.
- Clone your forked repo to your local machine.
- Make sure the Java SDK is installed -- not just the JRE. Java 17 or newer required. If you execute `java -version` at the shell or command prompt, it should report version 17 or later.
- Install Eclipse 2021-12 or later for Java. Launch it.
- Create a workspace. Go to the workbench. Right-click inside of Package Explorer > Import... > Maven > Existing Maven Projects > Navigate to root path of the local forge repo and
ensure everything is checked > Finish.
- Let Eclipse run through building the project. You may be prompted for resolving any missing Maven plugins -- accept the ones offered. You may see errors appear in the "Problems" tab. These should
be automatically resolved as plug-ins are installed and Eclipse continues the build process. If this is the first time for some plug-in installs, Eclipse may prompt you to restart. Do so. Be patient
for this first time through.
- Once everything builds, all errors should disappear. You can now advance to Project launch.
### Project Launch
#### Desktop
This is the standard configuration used for releasing to Windows / Linux / MacOS.
- Right-click on forge-gui-desktop > Run As... > Java Application > "Main - forge.view" > Ok
- The familiar Forge splash screen, etc. should appear. Enjoy!
#### Mobile (Desktop dev)
This is the configuration used for doing mobile development using the Windows / Linux / MacOS front-end. Knowledge of libgdx is helpful here.
- Right-click on forge-gui-mobile-dev > Run As... > Java Application > "Main - forge.app" > Ok.
- A view similar to a mobile phone should appear. Enjoy!
### Eclipse / Android SDK Integration
Google no longer supports Android SDK releases for Eclipse. use IntelliJ.
#### Android SDK
TBD
##### Windows
TBD
##### Linux / Mac OSX
TBD
#### Android Plugin for Eclipse
TBD
#### Android Platform
In Intellij, if the SDK Manager is not already running, go to Tools > Android > Android SDK Manager. Install the following options / versions:
- Android SDK Build-tools 35.0.0
- Android 15 (API 35) SDK Platform
#### Proguard update
Standalone Proguard 7.6.0 is included with the project (proguard.jar) under forge-gui-android > tools and supports up to Java 23 (latest android uses Java 17).
#### Android Build
TBD
#### Android Deploy
TBD
#### Android Debugging
TBD
### Windows / Linux SNAPSHOT build
SNAPSHOT builds can be built via the Maven integration in Eclipse.
1. Create a Maven build for the forge top-level project. Right-click on the forge project. Run as.. > Maven build...
- On the Main tab, set Goals: clean install, set Profiles: windows-linux
2. Run forge Maven build. If everything built, you should see "BUILD SUCCESS" in the Console View.
The resulting snapshot will be found at: forge-gui-desktop/target/forge-gui-desktop-[version]-SNAPSHOT
## Card Scripting
Visit [this page](https://github.com/Card-Forge/forge/wiki/Card-scripting-API) for information on scripting.
Card scripting resources are found in the forge-gui/res/ path.
## General Notes
### Project Hierarchy
Forge is divided into 4 primary projects with additional projects that target specific platform releases. The primary projects are:
- forge-ai
- forge-core
- forge-game
- forge-gui
The platform-specific projects are:
- forge-gui-android
- forge-gui-desktop
- forge-gui-ios
- forge-gui-mobile
- forge-gui-mobile-dev
#### forge-ai
The forge-ai project contains the computer opponent logic for gameplay. It includes decision-making algorithms for specific abilities, cards and turn phases.
#### forge-core
The forge-core project contains the core game engine, card mechanics, rules engine, and fundamental game logic. It includes the implementation of Magic: The Gathering rules, card interactions, and the game state management system.
#### forge-game
The forge-game project handles the game session management, player interactions, and game flow control. It includes implementations for multiplayer support, game modes, matchmaking, and game state persistence. This module bridges the core game engine with the user interface and networking components.
#### forge-gui
The forge-gui project contains the user interface components and rendering logic for the game. It includes the main game window, card displays, player interactions, and the scripting resource definitions in the res/ path.
#### forge-gui-android
Libgdx-based backend targeting Android. Requires Android SDK and relies on forge-gui-mobile for GUI logic.
#### forge-gui-desktop
Java Swing based GUI targeting desktop machines.
Screen layout and game logic revolving around the GUI is found here. For example, the overlay arrows (when enabled) that indicate attackers and blockers, or the targets of the stack are defined and drawn by this.
#### forge-gui-ios
Libgdx-based backend targeting iOS. Relies on forge-gui-mobile for GUI logic.
#### forge-gui-mobile
Mobile GUI game logic utilizing [libgdx](https://libgdx.badlogicgames.com/) library. Screen layout and game logic revolving around the GUI for the mobile platforms is found here.
#### forge-gui-mobile-dev
Libgdx backend for desktop development for mobile backends. Utilizes LWJGL. Relies on forge-gui-mobile for GUI logic.

674
LICENSE
View File

@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

105
README.md
View File

@@ -1,105 +0,0 @@
# ⚔️ Forge: The Magic: The Gathering Rules Engine
Join the **Forge community** on [Discord](https://discord.gg/HcPJNyD66a)!
[![Test build](https://github.com/Card-Forge/forge/actions/workflows/test-build.yaml/badge.svg)](https://github.com/Card-Forge/forge/actions/workflows/test-build.yaml)
---
## ✨ Introduction
**Forge** is a dynamic and open-source **Rules Engine** tailored for **Magic: The Gathering** enthusiasts. Developed by a community of passionate programmers, Forge allows players to explore the rich universe of MTG through a flexible, engaging platform.
**Note:** Forge operates independently and is not affiliated with Wizards of the Coast.
---
## 🌟 Key Features
- **🌐 Cross-Platform Support:** Play on **Windows, Mac, Linux,** and **Android**.
- **🔧 Extensible Architecture:** Built in **Java**, Forge encourages developers to contribute by adding features and cards.
- **🎮 Versatile Gameplay:** Dive into single-player modes or challenge opponents online!
---
## 🛠️ Installation Guide
### 📥 Desktop Installation
1. **Latest Releases:** Download the latest version [here](https://github.com/Card-Forge/forge/releases/latest).
2. **Snapshot Build:** For the latest development version, grab the `forge-gui-desktop` tarball from our [Snapshot Build](https://github.com/Card-Forge/forge/releases/tag/daily-snapshots).
- **Tip:** Extract to a new folder to prevent version conflicts.
3. **User Data Management:** Previous players data is preserved during upgrades.
4. **Java Requirement:** Ensure you have **Java 17 or later** installed.
### 📱 Android Installation
- _(Note: **Android 11** is the minimum requirements with at least **6GB RAM** to run smoothly. You need to enable **"Install unknown apps"** for Forge to initialize and update itself)_
- Download the **APK** from the [Snapshot Build](https://github.com/Card-Forge/forge/releases/tag/daily-snapshots). On the first launch, Forge will automatically download all necessary assets.
---
## 🎮 Modes of Play
Forge offers various exciting gameplay options:
### 🌍 Adventure Mode
Embark on a thrilling single-player journey where you can:
- Explore an overworld map.
- Challenge diverse AI opponents.
- Collect cards and items to boost your abilities.
<img width="1282" height="752" alt="Shandalar World" src="https://github.com/user-attachments/assets/9af31471-d688-442f-9418-9807d8635b72" />
### 🔍 Quest Modes
Engage in focused gameplay without the overworld exploration—perfect for quick sessions!
<img width="1282" height="752" alt="Quest Duels" src="https://github.com/user-attachments/assets/b9613b1c-e8c3-4320-8044-6922c519aad4" />
### 🤖 AI Formats
Test your skills against AI in multiple formats:
- **Sealed**
- **Draft**
- **Commander**
- **Cube**
For comprehensive gameplay instructions, visit our [Gameplay Guide](https://github.com/Card-Forge/forge/wiki/Gameplay-Guide).
<img width="1282" height="752" alt="Sealed" src="https://github.com/user-attachments/assets/ae603dbd-4421-4753-a333-87cb0a28d772" />
---
## 💬 Support & Community
Need help? Join our vibrant Discord community!
- 📜 Read the **#rules** and explore the **FAQ**.
- ❓ Ask your questions in the **#help** channel for assistance.
---
## 🤝 Contributing to Forge
We love community contributions! Interested in helping? Check out our [Contributing Guidelines](CONTRIBUTING.md) for details on how to get started.
---
## About Forge
Forge aims to deliver an immersive and customizable Magic: The Gathering experience for fans around the world.
### 📊 Repository Statistics
| Metric | Count |
|----------------|-------------------------------------------------------------|
| **⭐ Stars:** | [![GitHub stars](https://img.shields.io/github/stars/Card-Forge/forge?style=flat-square)](https://github.com/Card-Forge/forge/stargazers) |
| **🍴 Forks:** | [![GitHub forks](https://img.shields.io/github/forks/Card-Forge/forge?style=flat-square)](https://github.com/Card-Forge/forge/network) |
| **👥 Contributors:** | [![GitHub contributors](https://img.shields.io/github/contributors/Card-Forge/forge?style=flat-square)](https://github.com/Card-Forge/forge/graphs/contributors) |
---
**📄 License:** [GPL-3.0](LICENSE)
<div align="center" style="display: flex; align-items: center; justify-content: center;">
<div style="margin-left: auto;">
<a href="#top">
<img src="https://img.shields.io/badge/Back%20to%20Top-000000?style=for-the-badge&logo=github&logoColor=white" alt="Back to Top">
</a>
</div>
</div>

View File

@@ -1,117 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>forge</artifactId>
<groupId>forge</groupId>
<version>${revision}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>adventure-editor</artifactId>
<packaging>jar</packaging>
<name>Adventure Editor</name>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>${project.basedir}</directory>
<includes>
<include>**/gear.gif</include>
</includes>
</resource>
</resources>
<finalName>adventure-editor</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<basedir>${basedir}/${configSourceDirectory}</basedir>
<filesToInclude>adventure-editor.sh, adventure-editor.command, adventure-editor.cmd</filesToInclude>
<outputBasedir>${project.build.directory}</outputBasedir>
<outputDir>.</outputDir>
<regex>false</regex>
<replacements>
<replacement>
<token>$project.build.finalName$</token>
<value>${project.build.finalName}-jar-with-dependencies.jar</value>
</replacement>
</replacements>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<attach>false</attach>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>forge.adventure.Main</mainClass>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<SplashScreen-Image>splash/gear.gif</SplashScreen-Image>
</manifestEntries>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<!-- this is used for inheritance merges -->
<phase>package</phase>
<!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>forge</groupId>
<artifactId>forge-gui</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>forge</groupId>
<artifactId>forge-gui-mobile</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>26.0.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
</project>

View File

@@ -1,14 +0,0 @@
# ideally this should be using HTTPS, but this is fine for now
dsn=http://a0b8dbad9b8a49cfa51bf65d462e8dae@sentry.cardforge.org:9000/2
stacktrace.app.packages=forge
# where to store events if offline or can't reach the above server
buffer.dir=sentry-events
buffer.size=100
# allow ample time for graceful shutdown
buffer.shutdowntimeout=5000
async.shutdowntimeout=5000
# allow longer messages
maxmessagelength=1500

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

View File

@@ -1,24 +0,0 @@
@echo off
pushd %~dp0
java -version 1>nul 2>nul || (
echo no java installed
popd
exit /b 2
)
for /f tokens^=2^ delims^=.-_^+^" %%j in ('java -fullversion 2^>^&1') do set "jver=%%j"
if %jver% LEQ 16 (
echo unsupported java
popd
exit /b 2
)
if %jver% GEQ 17 (
java -Xmx4096m -Dfile.encoding=UTF-8 -jar $project.build.finalName$
popd
exit /b 0
)
popd

View File

@@ -1,3 +0,0 @@
#!/bin/sh
cd $(dirname "${0}")
java -Xmx4096m -Dfile.encoding=UTF-8 -jar $project.build.finalName$

View File

@@ -1,3 +0,0 @@
#!/bin/sh
cd $(dirname "${0}")
java -Xmx4096m -Dfile.encoding=UTF-8 -jar $project.build.finalName$

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 222 KiB

View File

@@ -1,21 +0,0 @@
package forge.adventure;
import forge.GuiMobile;
import forge.adventure.editor.EditorMainWindow;
import forge.adventure.util.Config;
import forge.gui.GuiBase;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Main entry point
*/
public class Main {
public static void main(String[] args) {
GuiBase.setInterface(new GuiMobile(Files.exists(Paths.get("./res"))?"./":"../forge-gui/"));
GuiBase.setDeviceInfo(null, 0, 0, System.getProperty("user.home") + "/Downloads/");
new EditorMainWindow(Config.instance());
}
}

View File

@@ -1,175 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.DialogData;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class ActionEdit extends FormPanel {
DialogData.ActionData currentData;
JTextField issueQuest = new JTextField();
JTextField characterFlagName = new JTextField();
JTextField mapFlagName = new JTextField();
JTextField questFlagName = new JTextField();
JTextField advanceCharacterFlag = new JTextField();
JTextField advanceMapFlag = new JTextField();
JTextField advanceQuestFlag = new JTextField();
JTextField battleWithActorID = new JTextField();
JTextField activateObjectID = new JTextField();
JTextField deleteMapObject = new JTextField();
JTextField setColorIdentity = new JTextField();
JSpinner addReputation = new JSpinner(new SpinnerNumberModel(0, -1000, 1000, 1));
JSpinner addLife = new JSpinner(new SpinnerNumberModel(0, -1000, 1000, 1));
JTextField POIReference = new JTextField();
JTextField removeItem = new JTextField();
JSpinner characterFlagValue = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
JSpinner mapFlagValue = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
JSpinner questFlagValue = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
private boolean updating=false;
public ActionEdit()
{
//todo: add info pane to explain primary usage
add("Issue Quest:",issueQuest);
add("Set Map Flag Name:",mapFlagName);
add("Map Flag value to set:",mapFlagValue);
add("Set Quest Flag name:",questFlagName);
add("Quest Flag value to set:",questFlagValue);
add("Set Character Flag name:",characterFlagName);
add("Character Flag value to set:",characterFlagValue);
add("Advance Map Flag name:",advanceMapFlag);
add("Advance Quest Flag name:",advanceQuestFlag);
add("Advance Character Flag name:",advanceCharacterFlag);
add("Battle with actor ID:",battleWithActorID);
add("Delete map object:",deleteMapObject);
add("Set color identity:",setColorIdentity);
add("Add Reputation:",addReputation);
add("Add Life:",addLife);
add("POI Reference:",POIReference);
add("Remove Item:",removeItem);
issueQuest.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
mapFlagName.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
mapFlagValue.getModel().addChangeListener(e -> ActionEdit.this.updateAction());
questFlagName.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
questFlagValue.getModel().addChangeListener(e -> ActionEdit.this.updateAction());
advanceMapFlag.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
advanceQuestFlag.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
battleWithActorID.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
activateObjectID.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
deleteMapObject.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
setColorIdentity.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
addLife.getModel().addChangeListener(e -> ActionEdit.this.updateAction());
addReputation.getModel().addChangeListener(e -> ActionEdit.this.updateAction());
POIReference.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
removeItem.getDocument().addDocumentListener(new DocumentChangeListener(ActionEdit.this::updateAction));
}
private void updateAction() {
if(updating)
return;
if (currentData == null)
currentData = new DialogData.ActionData();
DialogData.ActionData.QuestFlag characterFlag = new DialogData.ActionData.QuestFlag();
characterFlag.key = characterFlagName.getText();
characterFlag.val = (int)characterFlagValue.getModel().getValue();
currentData.setCharacterFlag= characterFlag;
DialogData.ActionData.QuestFlag mapFlag = new DialogData.ActionData.QuestFlag();
mapFlag.key = mapFlagName.getText();
mapFlag.val = (int)mapFlagValue.getModel().getValue();
currentData.setMapFlag= mapFlag;
DialogData.ActionData.QuestFlag questFlag = new DialogData.ActionData.QuestFlag();
questFlag.key = questFlagName.getText();
questFlag.val = (int)questFlagValue.getModel().getValue();
currentData.setQuestFlag= questFlag;
currentData.issueQuest = issueQuest.getText();
currentData.advanceMapFlag= advanceMapFlag.getText();
currentData.advanceQuestFlag= advanceQuestFlag.getText();
currentData.advanceCharacterFlag= advanceCharacterFlag.getText();
currentData.battleWithActorID= Integer.parseInt(battleWithActorID.getText());
currentData.activateMapObject= Integer.parseInt((activateObjectID.getText()));
currentData.deleteMapObject= Integer.parseInt(deleteMapObject.getText());
currentData.setColorIdentity= setColorIdentity.getText();
currentData.addLife= (int) addLife.getModel().getValue();
currentData.addMapReputation= (int)addReputation.getModel().getValue();
currentData.POIReference= POIReference.getText();
currentData.removeItem= removeItem.getText();
//These need a dedicated effect editor
// JTextField setEffect = new JTextField();
// JTextField giveBlessing = new JTextField();
// currentData.giveBlessing= giveBlessing.getText();
// currentData.setEffect= setEffect.getText();
//These are valid pre-existing fields, but should be handled through the dedicated rewards editor
// currentData.addGold =;
// currentData.addItem=;
// currentData.grantRewards =;
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
public void setCurrentAction(DialogData.ActionData data)
{
currentData=data;
refresh();
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
updating=true;
mapFlagName.setText(currentData.setMapFlag==null?"":currentData.setMapFlag.key);
mapFlagValue.getModel().setValue(currentData.setMapFlag==null?0:currentData.setMapFlag.val);
questFlagName.setText(currentData.setQuestFlag==null?"":currentData.setQuestFlag.key);
questFlagValue.getModel().setValue(currentData.setQuestFlag==null?0:currentData.setQuestFlag.val);
issueQuest.setText(currentData.issueQuest);
advanceMapFlag.setText(currentData.advanceMapFlag);
advanceQuestFlag.setText(currentData.advanceQuestFlag);
advanceCharacterFlag.setText(currentData.advanceCharacterFlag);
battleWithActorID.setText(String.valueOf(currentData.battleWithActorID));
activateObjectID.setText(String.valueOf(currentData.battleWithActorID));
deleteMapObject.setText(String.valueOf(currentData.deleteMapObject));
setColorIdentity.setText(currentData.setColorIdentity);
addLife.getModel().setValue(currentData.addLife);
addReputation.getModel().setValue(currentData.addMapReputation);
POIReference.setText(currentData.POIReference);
removeItem.setText(currentData.removeItem);
updating=false;
}
}

View File

@@ -1,144 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.DialogData;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionListener;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class ActionEditor extends JComponent {
DefaultListModel<DialogData.ActionData> model = new DefaultListModel<>();
JList<DialogData.ActionData> list = new JList<>(model);
JToolBar toolBar = new JToolBar("toolbar");
ActionEdit edit = new ActionEdit();
boolean updating;
public class RewardDataRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (!(value instanceof DialogData.ActionData))
return label;
/*DialogData.ActionData action=(DialogData.ActionData) value;
StringBuilder builder=new StringBuilder();
if(action.type==null||action.type.isEmpty())
builder.append("Action");
else
builder.append(action.type);*/
label.setText("Action");
return label;
}
}
public void addButton(String name, ActionListener action) {
JButton newButton = new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public ActionEditor() {
list.setCellRenderer(new RewardDataRenderer());
list.addListSelectionListener(e -> ActionEditor.this.updateEdit());
addButton("add", e -> ActionEditor.this.addAction());
addButton("remove", e -> ActionEditor.this.remove());
addButton("copy", e -> ActionEditor.this.copy());
BorderLayout layout = new BorderLayout();
setLayout(layout);
add(list, BorderLayout.LINE_START);
add(toolBar, BorderLayout.PAGE_START);
add(edit, BorderLayout.CENTER);
edit.addChangeListener(e -> emitChanged());
}
protected void emitChanged() {
if (updating)
return;
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
private void copy() {
int selected = list.getSelectedIndex();
if (selected < 0)
return;
DialogData.ActionData data = new DialogData.ActionData(model.get(selected));
model.add(model.size(), data);
}
private void updateEdit() {
int selected = list.getSelectedIndex();
if (selected < 0)
return;
edit.setCurrentAction(model.get(selected));
}
void addAction() {
DialogData.ActionData data = new DialogData.ActionData();
model.add(model.size(), data);
}
void remove() {
int selected = list.getSelectedIndex();
if (selected < 0)
return;
model.remove(selected);
}
public void setAction(DialogData.ActionData[] actions) {
model.clear();
if (actions == null)
return;
for (int i = 0; i < actions.length; i++) {
if (actions[i].grantRewards.length > 0) {
continue; //handled in separate editor and joined in on save, will get duplicated if it appears here
}
model.add(i, actions[i]);
}
}
public DialogData.ActionData[] getAction() {
DialogData.ActionData[] action = new DialogData.ActionData[model.getSize()];
for (int i = 0; i < model.getSize(); i++) {
action[i] = model.get(i);
}
return action;
}
public void clear() {
updating = true;
model.clear();
updating = false;
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
}

View File

@@ -1,125 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.BiomeData;
import javax.swing.*;
public class BiomeEdit extends FormPanel {
BiomeData currentData;
public JSpinner startPointX= new JSpinner(new SpinnerNumberModel(0.0f, 0.f, 1f, 0.1f));
public JSpinner startPointY= new JSpinner(new SpinnerNumberModel(0.0f, 0.f, 1f, 0.1f));
public JSpinner noiseWeight= new JSpinner(new SpinnerNumberModel(0.0f, 0.f, 1f, 0.1f));
public JSpinner distWeight= new JSpinner(new SpinnerNumberModel(0.0f, 0.f, 1f, 0.1f));
public JTextField name=new JTextField();
public FilePicker tilesetAtlas=new FilePicker(new String[]{"atlas"});
public JTextField tilesetName=new JTextField();
public JSpinner width= new JSpinner(new SpinnerNumberModel(0.0f, 0.f, 1f, 0.1f));
public JSpinner height= new JSpinner(new SpinnerNumberModel(0.0f, 0.f, 1f, 0.1f));
public JTextField color=new JTextField();
public JCheckBox collision=new JCheckBox();
public TextListEdit spriteNames =new TextListEdit();
public TextListEdit enemies =new TextListEdit();
public TextListEdit pointsOfInterest =new TextListEdit();
public TerrainsEditor terrain =new TerrainsEditor();
public StructureEditor structures =new StructureEditor();
private boolean updating=false;
public BiomeEdit()
{
FormPanel center=new FormPanel() { };
center.add("startPointX:",startPointX);
center.add("startPointY:",startPointY);
center.add("noiseWeight:",noiseWeight);
center.add("distWeight:",distWeight);
center.add("name:",name);
center.add("tilesetAtlas:",tilesetAtlas);
center.add("tilesetName:",tilesetName);
center.add("width:",width);
center.add("height:",height);
center.add("spriteNames:",spriteNames);
center.add("enemies:",enemies);
center.add("POITags:",pointsOfInterest);
center.add("color:",color);
center.add("collision:",collision);
center.add("terrain/structures:",new JLabel(""));
add(center);
add(terrain);
add(structures);
name.getDocument().addDocumentListener(new DocumentChangeListener(BiomeEdit.this::updateTerrain));
tilesetName.getDocument().addDocumentListener(new DocumentChangeListener(BiomeEdit.this::updateTerrain));
color.getDocument().addDocumentListener(new DocumentChangeListener(BiomeEdit.this::updateTerrain));
collision.addChangeListener(e -> BiomeEdit.this.updateTerrain());
spriteNames.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(BiomeEdit.this::updateTerrain));
enemies.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(BiomeEdit.this::updateTerrain));
terrain.addChangeListener(e -> BiomeEdit.this.updateTerrain());
startPointX.addChangeListener(e -> BiomeEdit.this.updateTerrain());
startPointY.addChangeListener(e -> BiomeEdit.this.updateTerrain());
noiseWeight.addChangeListener(e -> BiomeEdit.this.updateTerrain());
distWeight.addChangeListener(e -> BiomeEdit.this.updateTerrain());
tilesetAtlas.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(BiomeEdit.this::updateTerrain));
width.addChangeListener(e -> BiomeEdit.this.updateTerrain());
height.addChangeListener(e -> BiomeEdit.this.updateTerrain());
refresh();
}
protected void updateTerrain() {
if(currentData==null||updating)
return;
currentData.startPointX = (Float) startPointX.getValue();
currentData.startPointY = (Float) startPointY.getValue();
currentData.noiseWeight = (Float) noiseWeight.getValue();
currentData.distWeight = (Float)distWeight.getValue();
currentData.name = name.getText();
currentData.tilesetAtlas = tilesetAtlas.edit.getText();
currentData.tilesetName = tilesetName.getText();
currentData.terrain = terrain.getBiomeTerrainData();
currentData.structures = structures.getBiomeStructureData();
currentData.width = (Float) width.getValue();
currentData.height = (Float) height.getValue();
currentData.color = color.getText();
currentData.collision = collision.isSelected();
currentData.spriteNames = spriteNames.getList();
currentData.enemies = enemies.getList();
currentData.pointsOfInterest = pointsOfInterest.getList();
}
public void setCurrentBiome(BiomeData data)
{
currentData=data;
refresh();
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
updating=true;
startPointX.setValue(currentData.startPointX);
startPointY.setValue(currentData.startPointY);
noiseWeight.setValue(currentData.noiseWeight);
distWeight.setValue(currentData.distWeight);
name.setText(currentData.name);
tilesetAtlas.edit.setText( currentData.tilesetAtlas);
tilesetName.setText(currentData.tilesetName);
terrain.setTerrains(currentData);
structures.setStructures(currentData);
width.setValue(currentData.width);
height.setValue(currentData.height);
color.setText(currentData.color);
spriteNames.setText(currentData.spriteNames);
enemies.setText(currentData.enemies);
collision.setSelected(currentData.collision);
pointsOfInterest.setText(currentData.pointsOfInterest);
updating=false;
}
}

View File

@@ -1,170 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.BiomeStructureData;
import forge.adventure.util.Config;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class BiomeStructureDataMappingEditor extends JComponent {
DefaultListModel<BiomeStructureData.BiomeStructureDataMapping> model = new DefaultListModel<>();
JList<BiomeStructureData.BiomeStructureDataMapping> list = new JList<>(model);
JToolBar toolBar = new JToolBar("toolbar");
BiomeStructureDataMappingEdit edit=new BiomeStructureDataMappingEdit();
private BiomeStructureData data;
public void setCurrent(BiomeStructureData data) {
this.data=data;
model.clear();
if(data==null||data.mappingInfo==null)
return;
for(int i=0;i<data.mappingInfo.length;i++)
model.addElement(data.mappingInfo[i]);
list.setSelectedIndex(0);
}
public BiomeStructureData.BiomeStructureDataMapping[] getCurrent()
{
BiomeStructureData.BiomeStructureDataMapping[] array=new BiomeStructureData.BiomeStructureDataMapping[model.size()];
for(int i=0;i<array.length;i++)
array[i]=model.get(i);
return array;
}
public class BiomeStructureDataMappingRenderer extends DefaultListCellRenderer {
private final BiomeStructureDataMappingEditor editor;
public BiomeStructureDataMappingRenderer(BiomeStructureDataMappingEditor biomeStructureDataMappingEditor) {
this.editor=biomeStructureDataMappingEditor;
}
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof BiomeStructureData.BiomeStructureDataMapping biomeData))
return label;
// Get the renderer component from parent class
label.setText(biomeData.name);
if(editor.data!=null)
{
SwingAtlas itemAtlas=new SwingAtlas(Config.instance().getFile(editor.data.structureAtlasPath));
if(itemAtlas.has(biomeData.name))
label.setIcon(itemAtlas.get(biomeData.name));
else
{
ImageIcon img=itemAtlas.getAny();
if(img!=null)
label.setIcon(img);
}
}
return label;
}
}
public void addButton(String name, ActionListener action)
{
JButton newButton=new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public BiomeStructureDataMappingEditor()
{
list.setCellRenderer(new BiomeStructureDataMappingEditor.BiomeStructureDataMappingRenderer(this));
list.addListSelectionListener(e -> BiomeStructureDataMappingEditor.this.updateEdit());
addButton("add", e -> BiomeStructureDataMappingEditor.this.add());
addButton("remove", e -> BiomeStructureDataMappingEditor.this.remove());
addButton("copy", e -> BiomeStructureDataMappingEditor.this.copy());
BorderLayout layout=new BorderLayout();
setLayout(layout);
add(new JScrollPane(list), BorderLayout.WEST);
add(toolBar, BorderLayout.NORTH);
add(edit,BorderLayout.CENTER);
}
private void copy() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
BiomeStructureData.BiomeStructureDataMapping data=new BiomeStructureData.BiomeStructureDataMapping(model.get(selected));
model.add(model.size(),data);
}
private void updateEdit() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
edit.setCurrent(model.get(selected));
}
void add()
{
BiomeStructureData.BiomeStructureDataMapping data=new BiomeStructureData.BiomeStructureDataMapping();
data.name="Structure "+model.getSize();
model.add(model.size(),data);
}
void remove()
{
int selected=list.getSelectedIndex();
if(selected<0)
return;
model.remove(selected);
}
private class BiomeStructureDataMappingEdit extends FormPanel{
BiomeStructureData.BiomeStructureDataMapping currentData;
public JTextField name=new JTextField();
public JTextField color=new JTextField();
public JCheckBox collision=new JCheckBox();
private boolean updating=false;
public BiomeStructureDataMappingEdit()
{
add("name:",name);
add("color:",color);
add("collision:",collision);
name.getDocument().addDocumentListener(new DocumentChangeListener(BiomeStructureDataMappingEdit.this::update));
color.getDocument().addDocumentListener(new DocumentChangeListener(BiomeStructureDataMappingEdit.this::update));
collision.addChangeListener(e -> BiomeStructureDataMappingEdit.this.update());
refresh();
}
private void update() {
if(currentData==null||updating)
return;
currentData.name = name.getText();
currentData.color = color.getText();
currentData.collision = collision.isSelected();
}
public void setCurrent(BiomeStructureData.BiomeStructureDataMapping data)
{
currentData=data;
refresh();
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
updating=true;
name.setText(currentData.name);
color.setText(currentData.color);
collision.setSelected(currentData.collision);
updating=false;
}
}
}

View File

@@ -1,136 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.BiomeData;
import forge.adventure.data.BiomeStructureData;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class BiomeStructureEdit extends FormPanel {
private boolean updating=false;
BiomeStructureData currentData;
BiomeData currentBiomeData;
public JTextField structureAtlasPath=new JTextField();
public FloatSpinner x= new FloatSpinner();
public FloatSpinner y= new FloatSpinner();
public FloatSpinner width= new FloatSpinner();
public FloatSpinner height= new FloatSpinner();
public JCheckBox randomPosition=new JCheckBox();
public IntSpinner N= new IntSpinner();
public JTextField sourcePath= new JTextField();
public JTextField maskPath= new JTextField();
public JCheckBox periodicInput= new JCheckBox();
public IntSpinner ground= new IntSpinner();
public IntSpinner symmetry= new IntSpinner();
public JCheckBox periodicOutput= new JCheckBox();
public BiomeStructureDataMappingEditor data=new BiomeStructureDataMappingEditor();
public BiomeStructureEdit()
{
FormPanel center=new FormPanel();
center.add("structureAtlasPath:",structureAtlasPath);
center.add("x:",x);
center.add("y:",y);
center.add("width:",width);
center.add("height:",height);
center.add("N:",N);
center.add("sourcePath:",sourcePath);
center.add("maskPath:",maskPath);
center.add("periodicInput:",periodicInput);
center.add("ground:",ground);
center.add("symmetry:",symmetry);
center.add("periodicOutput:",periodicOutput);
add(center);
add(data);
structureAtlasPath.getDocument().addDocumentListener(new DocumentChangeListener(BiomeStructureEdit.this::updateStructure));
x.addChangeListener(e -> BiomeStructureEdit.this.updateStructure());
y.addChangeListener(e -> BiomeStructureEdit.this.updateStructure());
width.addChangeListener(e -> BiomeStructureEdit.this.updateStructure());
height.addChangeListener(e -> BiomeStructureEdit.this.updateStructure());
randomPosition.addChangeListener(e -> BiomeStructureEdit.this.updateStructure());
N.addChangeListener(e -> BiomeStructureEdit.this.updateStructure());
sourcePath.getDocument().addDocumentListener(new DocumentChangeListener(BiomeStructureEdit.this::updateStructure));
maskPath.getDocument().addDocumentListener(new DocumentChangeListener(BiomeStructureEdit.this::updateStructure));
periodicInput.addChangeListener(e -> BiomeStructureEdit.this.updateStructure());
ground.addChangeListener(e -> BiomeStructureEdit.this.updateStructure());
symmetry.addChangeListener(e -> BiomeStructureEdit.this.updateStructure());
periodicOutput.addChangeListener(e -> BiomeStructureEdit.this.updateStructure());
refresh();
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
data.setCurrent(null);
return;
}
updating=true;
structureAtlasPath.setText(currentData.structureAtlasPath);
x.setValue(currentData.x);
y.setValue(currentData.y);
width.setValue(currentData.width);
height.setValue(currentData.height);
randomPosition.setSelected(currentData.randomPosition);
N.setValue(currentData.N);
sourcePath.setText(currentData.sourcePath);
maskPath.setText(currentData.maskPath);
periodicInput.setSelected(currentData.periodicInput);
ground.setValue(currentData.ground);
symmetry.setValue(currentData.symmetry);
periodicOutput.setSelected(currentData.periodicOutput);
data.setCurrent(currentData);
updating=false;
}
public void updateStructure()
{
if(currentData==null||updating)
return;
currentData.structureAtlasPath=structureAtlasPath.getText();
currentData.x= x.floatValue();
currentData.y= y.floatValue();
currentData.width= width.floatValue();
currentData.height= height.floatValue();
currentData.randomPosition=randomPosition.isSelected();
currentData.mappingInfo= data.getCurrent();
currentData.N= N.intValue();
currentData.sourcePath= sourcePath.getText();
currentData.maskPath= maskPath.getText();
currentData.periodicInput= periodicInput.isSelected();
currentData.ground= ground.intValue();
currentData.symmetry= symmetry.intValue();
currentData.periodicOutput= periodicOutput.isSelected();
emitChanged();
}
public void setCurrentStructure(BiomeStructureData biomeTerrainData, BiomeData data) {
currentData =biomeTerrainData;
currentBiomeData=data;
refresh();
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
protected void emitChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
}

View File

@@ -1,84 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.BiomeData;
import forge.adventure.data.BiomeTerrainData;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class BiomeTerrainEdit extends FormPanel {
SwingAtlasPreview preview=new SwingAtlasPreview(128);
private boolean updating=false;
BiomeTerrainData currentData;
BiomeData currentBiomeData;
public JTextField spriteName=new JTextField();
public JSpinner min= new JSpinner(new SpinnerNumberModel(0.0f, 0.f, 1f, 0.1f));
public JSpinner max= new JSpinner(new SpinnerNumberModel(0.0f, 0.f, 1f, 0.1f));
public JSpinner resolution= new JSpinner(new SpinnerNumberModel(0.0f, 0.f, 1f, 0.1f));
public BiomeTerrainEdit()
{
FormPanel center=new FormPanel() { };
center.add("spriteName:",spriteName);
center.add("min:",min);
center.add("max:",max);
center.add("resolution:",resolution);
add(center,preview);
spriteName.getDocument().addDocumentListener(new DocumentChangeListener(BiomeTerrainEdit.this::updateTerrain));
min.addChangeListener(e -> BiomeTerrainEdit.this.updateTerrain());
max.addChangeListener(e -> BiomeTerrainEdit.this.updateTerrain());
resolution.addChangeListener(e -> BiomeTerrainEdit.this.updateTerrain());
refresh();
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
updating=true;
spriteName.setText(currentData.spriteName);
min.setValue(currentData.min);
max.setValue(currentData.max);
resolution.setValue(currentData.resolution);
if(currentBiomeData!=null&&currentData!= null)
preview.setSpritePath(currentBiomeData.tilesetAtlas,currentData.spriteName);
updating=false;
}
public void updateTerrain()
{
if(currentData==null||updating)
return;
currentData.spriteName=spriteName.getText();
currentData.min= (float) min.getValue();
currentData.max= (float) max.getValue();
currentData.resolution= (float) resolution.getValue();
preview.setSpritePath(currentBiomeData.tilesetAtlas,currentData.spriteName);
emitChanged();
}
public void setCurrentTerrain(BiomeTerrainData biomeTerrainData, BiomeData data) {
currentData =biomeTerrainData;
currentBiomeData=data;
refresh();
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
protected void emitChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
}

View File

@@ -1,155 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.DialogData;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
public class DialogEdit extends FormPanel {
private boolean updating=false;
DialogData currentData;
public JTextField name=new JTextField(80);
public JTextField text=new JTextField(80);
public JTextField locname=new JTextField(80);
public JTextField loctext=new JTextField(80);
JPanel namePanel;
JPanel locNamePanel;
public JButton addNode = new JButton("Add node");
public JButton removeNode = new JButton("Remove node");
public DialogEdit()
{
FormPanel center=new FormPanel() { };
name.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
if (!updating)
emitChanged();
}
@Override
public void removeUpdate(DocumentEvent e) {
if (!updating)
emitChanged();
}
@Override
public void changedUpdate(DocumentEvent e) {
if (!updating)
emitChanged();
}
});
text.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
if (!updating)
emitChanged();
}
@Override
public void removeUpdate(DocumentEvent e) {
if (!updating)
emitChanged();
}
@Override
public void changedUpdate(DocumentEvent e) {
if (!updating)
emitChanged();
}
});
JPanel editData = new JPanel();
editData.setLayout(new BoxLayout(editData, BoxLayout.Y_AXIS));
namePanel = new JPanel();
namePanel.setLayout(new FlowLayout());
namePanel.add(new JLabel("Name:"));
namePanel.add(name);
editData.add(namePanel);
JPanel textPanel = new JPanel();
textPanel.setLayout(new FlowLayout());
textPanel.add(new JLabel("Text:"));
textPanel.add(text);
editData.add(textPanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(addNode);
buttonPanel.add(removeNode);
editData.add(buttonPanel);
editData.add(new JLabel("localization tokens for translation"));
locNamePanel = new JPanel();
locNamePanel.setLayout(new FlowLayout());
locNamePanel.add(new JLabel("Name Token:"));
locNamePanel.add(locname);
JPanel locTextPanel = new JPanel();
locTextPanel.setLayout(new FlowLayout());
locTextPanel.add(new JLabel("Text Token:"));
locTextPanel.add(loctext);
editData.add(locNamePanel);
editData.add(locTextPanel);
center.add(editData);
add(center);
refresh();
}
public void refresh(){
refresh(false);
}
public void refresh(boolean onRootNode) {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
updating=true;
name.setText(currentData.name);
locname.setText(currentData.locname);
text.setText(currentData.text);
loctext.setText(currentData.loctext);
namePanel.setVisible(!onRootNode);
locNamePanel.setVisible(!onRootNode);
updating=false;
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
protected void emitChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
}

View File

@@ -1,242 +0,0 @@
package forge.adventure.editor;
import com.google.common.collect.ObjectArrays;
import forge.adventure.data.DialogData;
import forge.adventure.data.RewardData;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class DialogEditor extends JComponent{
private boolean updating = false;
private java.util.List<DialogData> allNodes = new ArrayList<>();
public JTextArea text =new JTextArea("(Initial dialog text)", 3, 80);
public RewardsEditor rewardsEditor = new RewardsEditor();
public ActionEditor actionEditor = new ActionEditor();
public DialogOptionEditor optionEditor = new DialogOptionEditor();
public DialogTree navTree = new DialogTree();
public DialogEdit edit = new DialogEdit();
private DialogData root = new DialogData();
private DialogData current = new DialogData();
public DialogEditor(){
buildUI();
navTree.addSelectionListener(q -> loadNewNodeSelection());
edit.addChangeListener(q-> acceptEdits());
edit.addNode.addActionListener(q -> addNode());
edit.removeNode.addActionListener(q -> removeNode());
}
public void loadData(DialogData rootDialogData){
updating = true;
if (rootDialogData == null)
{
rootDialogData = new DialogData();
}
root = rootDialogData;
navTree.loadDialog(rootDialogData);
text.setText(rootDialogData.text);
updating = false;
}
public DialogData getDialogData(){
return root;
}
JTabbedPane tabs = new JTabbedPane();
JToolBar conditionsToolbar = new JToolBar("conditionsToolbar");
JToolBar actionsToolbar = new JToolBar("actionsToolbar");
JToolBar optionsToolbar = new JToolBar("optionsToolbar");
JToolBar tokensToolbar = new JToolBar("tokensToolbar");
JPanel conditionsPanel = new JPanel();
JPanel actionsPanel = new JPanel();
JPanel optionsPanel = new JPanel();
JPanel rewardsPanel = new JPanel();
JPanel tokensPanel = new JPanel();
class QuestTextDocumentListener implements DocumentListener {
public void changedUpdate(DocumentEvent e) {
root.text = text.getText();
emitChanged();
}
public void removeUpdate(DocumentEvent e) {
root.text = text.getText();
emitChanged();
}
public void insertUpdate(DocumentEvent e) {
root.text = text.getText();
emitChanged();
}
}
public void buildUI(){
buildTabs();
BorderLayout layout=new BorderLayout();
setLayout(layout);
JPanel textArea = new JPanel();
textArea.setLayout(new FlowLayout());
textArea.add(new JLabel("Dialog Start"));
textArea.add(text);
text.getDocument().addDocumentListener(new QuestTextDocumentListener());
JSplitPane splitPane = new JSplitPane();
splitPane.setLeftComponent(navTree);
splitPane.setRightComponent(tabs);
splitPane.setResizeWeight(0.2);
splitPane.setDividerLocation(.2);
add(textArea, BorderLayout.NORTH);
add(splitPane, BorderLayout.CENTER);
}
public void loadNewNodeSelection(){
updating = true;
current = navTree.getSelectedData();
edit.currentData = navTree.getSelectedData();
edit.refresh(root.equals(current));
rewardsEditor.clear();
actionEditor.clear();
if (navTree.getSelectedData() != null) {
for (DialogData.ActionData action : navTree.getSelectedData().action) {
if (action.grantRewards != null && action.grantRewards.length > 0)
rewardsEditor.setRewards(action.grantRewards);
}
actionEditor.setAction(navTree.getSelectedData().action);
}
updating = false;
}
public void acceptEdits(){
if (current == null)
return;
current.name = edit.name.getText();
current.text = edit.text.getText();
current.locname = edit.locname.getText();
current.loctext = edit.loctext.getText();
root.text = text.getText();
DialogData.ActionData[] action = actionEditor.getAction();
ArrayList<DialogData.ActionData> actionsList = new ArrayList<>(Arrays.stream(action).collect(Collectors.toList()));
RewardData[] rewards= rewardsEditor.getRewards();
if (rewards.length > 0)
{
DialogData.ActionData rewardAction = new DialogData.ActionData();
rewardAction.grantRewards = rewards;
actionsList.add(rewardAction);
}
current.action = actionsList.toArray(current.action);
navTree.replaceCurrent();
emitChanged();
}
public void addNode(){
DialogData newNode = new DialogData();
newNode.name = "NewResponse";
DialogData parent = navTree.getSelectedData()!=null?navTree.getSelectedData():root;
parent.options = ObjectArrays.concat(parent.options, newNode);
navTree.loadDialog(root);
navTree.setSelectedData(newNode);
emitChanged();
}
public void removeNode(){
if (navTree.getSelectedData() == null)
return;
navTree.removeSelectedData();
emitChanged();
}
public void buildTabs(){
buildToolBars();
actionsPanel.add(actionsToolbar);
actionsPanel.add(actionEditor);
optionsPanel.add(edit);
rewardsPanel.add(rewardsEditor);
rewardsEditor.addChangeListener(e -> DialogEditor.this.acceptEdits());
actionEditor.addChangeListener(e -> DialogEditor.this.acceptEdits());
tokensPanel.add(tokensToolbar);
tokensPanel.add(new JLabel("Insert token editor here"));
tabs.addTab("Options", optionsPanel);
tabs.addTab("Conditions", conditionsPanel);
tabs.addTab("Actions", actionsPanel);
tabs.addTab("Rewards", rewardsPanel);
tabs.addTab("Tokens",tokensPanel);
}
public void buildToolBars(){
conditionsToolbar.setFloatable(false);
actionsToolbar.setFloatable(false);
optionsToolbar.setFloatable(false);
JButton addOption = new JButton("Add Option");
addOption.addActionListener(e -> DialogEditor.this.addOption());
optionsToolbar.add(addOption);
JButton copyOption = new JButton("Copy Selected");
copyOption.addActionListener(e -> DialogEditor.this.copyOption());
optionsToolbar.add(copyOption);
JButton removeOption = new JButton("Remove Selected");
removeOption.addActionListener(e -> DialogEditor.this.removeOption());
optionsToolbar.add(removeOption);
}
public void addOption(){
optionEditor.addOption();
emitChanged();
}
public void copyOption(){
emitChanged();
}
public void removeOption(){
int selected=optionEditor.list.getSelectedIndex();
if(selected<0)
return;
optionEditor.model.remove(selected);
emitChanged();
}
protected void emitChanged() {
if (updating)
return;
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
}

View File

@@ -1,85 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.DialogData;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class DialogOptionEdit extends FormPanel {
DialogData currentData;
JLabel nameLabel = new JLabel("Name (Player dialog / action)");
JLabel textLabel = new JLabel("Text (Game response to Name - Leave blank to end dialog)");
JTextArea text =new JTextArea(3,80);
JTextArea name =new JTextArea(3,80);
JButton add = new JButton();
JButton load = new JButton();
private boolean updating=false;
public DialogOptionEdit()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel upper = new JPanel();
upper.setLayout(new BorderLayout());
upper.add(nameLabel, BorderLayout.NORTH);
upper.add(name, BorderLayout.CENTER);
add(upper);
JPanel middle = new JPanel();
middle.setLayout(new BorderLayout());
middle.add(textLabel, BorderLayout.NORTH);
middle.add(text, BorderLayout.CENTER);
add(middle);
name.getDocument().addDocumentListener(new DocumentChangeListener(DialogOptionEdit.this::updateDialog));
text.getDocument().addDocumentListener(new DocumentChangeListener(DialogOptionEdit.this::updateDialog));
}
private void updateDialog() {
if(currentData==null||updating)
return;
currentData.text = text.getText().trim();
currentData.name = name.getText().trim();
//currentData.condition = conditionEditor.getConditions();
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
public void setCurrentOption(DialogData data)
{
currentData=data;
refresh();
}
private void refresh() {
setEnabled(currentData!=null);
updating=true;
text.setText(currentData.text!=null?currentData.text:"");
name.setText(currentData.name!=null?currentData.name:"");
updating=false;
}
}

View File

@@ -1,138 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.DialogData;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionListener;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class DialogOptionEditor extends JComponent{
DefaultListModel<DialogData> model = new DefaultListModel<>();
JList<DialogData> list = new JList<>(model);
JToolBar toolBar = new JToolBar("toolbar");
DialogOptionEdit edit=new DialogOptionEdit();
public class DialogDataRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof DialogData dialog))
return label;
StringBuilder builder=new StringBuilder();
if(dialog.name==null||dialog.name.isEmpty())
builder.append("[[Blank Option]]");
else
builder.append(dialog.name, 0, Math.min(dialog.name.length(), 25));
label.setText(builder.toString());
return label;
}
}
public void addButton(String name, ActionListener action)
{
JButton newButton=new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public DialogOptionEditor()
{
list.setCellRenderer(new DialogDataRenderer());
list.addListSelectionListener(e -> DialogOptionEditor.this.updateEdit());
addButton("add", e -> DialogOptionEditor.this.addOption());
addButton("remove", e -> DialogOptionEditor.this.remove());
addButton("copy", e -> DialogOptionEditor.this.copy());
BorderLayout layout=new BorderLayout();
setLayout(layout);
add(list, BorderLayout.LINE_START);
add(toolBar, BorderLayout.PAGE_START);
toolBar.setFloatable(false);
add(edit,BorderLayout.CENTER);
edit.setVisible(false);
edit.addChangeListener(e -> emitChanged());
}
protected void emitChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
private void copy() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
DialogData data=new DialogData(model.get(selected));
model.add(model.size(),data);
}
private void updateEdit() {
int selected=list.getSelectedIndex();
if(selected<0)
edit.setCurrentOption(new DialogData());
else
edit.setCurrentOption(model.get(selected));
}
void addOption()
{
DialogData data=new DialogData();
model.add(model.size(),data);
edit.setVisible(true);
list.setSelectedIndex(model.size() - 1);
}
void remove()
{
int selected=list.getSelectedIndex();
if(selected<0)
return;
model.remove(selected);
edit.setVisible(model.size() > 0);
}
public void setOptions(DialogData[] options) {
model.clear();
if(options==null || options.length == 0)
options = new DialogData[0];
for (int i=0;i<options.length;i++) {
model.add(i,options[i]);
}
if (model.size() > 0)
{
edit.setVisible(true);
list.setSelectedIndex(0);
updateEdit();
}
else{
edit.setVisible(false);
}
}
public DialogData[] getOptions() {
DialogData[] options= new DialogData[model.getSize()];
for(int i=0;i<model.getSize();i++)
{
options[i]=model.get(i);
}
return options;
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
}

View File

@@ -1,116 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.DialogData;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DialogTree extends JPanel {
private JTree dialogTree;
private JScrollPane scrollPane;
public DialogTree(){
setLayout(new BorderLayout());
// Create the JTree component
dialogTree = new JTree();
dialogTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
addSelectionListener();
// Create a scroll pane to contain the JTree
scrollPane = new JScrollPane(dialogTree);
// Add the scroll pane to the panel
add(scrollPane, BorderLayout.CENTER);
}
public void loadDialog(DialogData dialogData){
// rootNode = buildBranches(dialogData);
// ((DefaultTreeModel)dialogTree.getModel()).setRoot(rootNode);
((DefaultTreeModel)dialogTree.getModel()).setRoot(buildBranches(dialogData));
}
public DefaultMutableTreeNode buildBranches(DialogData dialogData)
{
DefaultMutableTreeNode node = new DefaultMutableTreeNode(dialogData);
for (DialogData option : dialogData.options){
node.add(buildBranches(option));
}
return node;
}
private final List<TreeSelectionListener> selectionListeners = new ArrayList<>();
public void addSelectionListener(){
//subscribe to valueChanged, change to that object in edit pane
dialogTree.getSelectionModel().addTreeSelectionListener(this::emitChanged);
}
public void addSelectionListener(final TreeSelectionListener listener) {
selectionListeners.remove(listener); //ensure listener not added multiple times
selectionListeners.add(listener);
}
protected void emitChanged(TreeSelectionEvent evt) {
if (selectionListeners != null && selectionListeners.size() > 0) {
for (TreeSelectionListener listener : selectionListeners) {
listener.valueChanged(evt);
}
}
}
public void replaceCurrent(){
if (dialogTree.getSelectionPath() == null || dialogTree.getSelectionPath().getLastPathComponent() == null)
return;
dialogTree.updateUI();
}
public DialogData getSelectedData() {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) dialogTree.getLastSelectedPathComponent();
if (selectedNode != null) {
return (DialogData) selectedNode.getUserObject();
}
return null;
}
public void removeSelectedData() {
//Todo: Enhance this to not collapse any nodes (after setSelectedData other paths are still collapsed)
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) dialogTree.getLastSelectedPathComponent();
DialogData parentData = (DialogData) ((DefaultMutableTreeNode)selectedNode.getParent()).getUserObject();
parentData.options = Arrays.stream(parentData.options).filter(q -> q != selectedNode.getUserObject()).toArray(DialogData[]::new);
((DefaultTreeModel) dialogTree.getModel()).removeNodeFromParent(selectedNode);
((DefaultTreeModel) dialogTree.getModel()).reload();
setSelectedData(parentData);
}
public void setSelectedData(DialogData data) {
// Find the node with the given data object and select it in the tree
DefaultMutableTreeNode node = findNode((DefaultMutableTreeNode)dialogTree.getModel().getRoot(), data);
if (node != null) {
dialogTree.setSelectionPath(new TreePath(node.getPath()));
}
}
private DefaultMutableTreeNode findNode(DefaultMutableTreeNode parent, DialogData data) {
// Search for the node with the given data object in the subtree rooted at the parent node
if (parent.getUserObject() == data) {
return parent;
}
for (int i = 0; i < parent.getChildCount(); i++) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode) parent.getChildAt(i);
DefaultMutableTreeNode result = findNode(child, data);
if (result != null) {
return result;
}
}
return null;
}
}

View File

@@ -1,32 +0,0 @@
package forge.adventure.editor;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class DocumentChangeListener implements DocumentListener {
private final Runnable run;
public DocumentChangeListener(Runnable run)
{
this.run = run;
}
@Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
run.run();
}
}

View File

@@ -1,97 +0,0 @@
package forge.adventure.editor;
import forge.adventure.util.Config;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.List;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class EditorMainWindow extends JFrame {
public final static WorldEditor worldEditor = new WorldEditor();
JTabbedPane tabs = new JTabbedPane();
public EditorMainWindow(Config config) {
UIManager.LookAndFeelInfo[] var1 = UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo info : var1) {
if ("Nimbus".equals(info.getName())) {
try {
UIManager.setLookAndFeel(info.getClassName());
} catch (Throwable ignored) {
}
break;
}
}
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setVisible(false);
System.exit(0);
}
});
BorderLayout layout = new BorderLayout();
JToolBar toolBar = new JToolBar("toolbar");
JButton newButton = new JButton("GDX Particle Editor Tool");
newButton.addActionListener(e -> EventQueue.invokeLater(() -> {
newButton.setEnabled(false);
try {
CodeSource codeSource = EditorMainWindow.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();
Desktop.getDesktop().open(new File(jarDir + "/gdx-particle-editor.jar"));
} catch (Exception ex) {
new ErrorDialog("Error", ex.getMessage());
newButton.setEnabled(true);
}
}));
JButton quit = new JButton("Quit");
quit.addActionListener(e -> System.exit(0));
toolBar.add(newButton);
toolBar.add(quit);
setLayout(layout);
toolBar.setFloatable(false);
add(toolBar, BorderLayout.NORTH);
add(tabs, BorderLayout.CENTER);
tabs.addTab("World", worldEditor);
tabs.addTab("POI", new PointOfInterestEditor());
tabs.addTab("Items", new ItemsEditor());
tabs.addTab("Enemies", new EnemyEditor());
tabs.addTab("Quests", new QuestEditor());
setSize(config.getSettingData().width, config.getSettingData().height);
setLocationRelativeTo(null);
setVisible(true);
}
static class ErrorDialog {
public ErrorDialog(String title, String message) {
List<Object> options = new ArrayList<>();
JButton ok = new JButton("OK");
options.add(ok);
JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, options.toArray());
JDialog dlg = pane.createDialog(JOptionPane.getRootFrame(), title);
ok.addActionListener(e -> {
dlg.setVisible(false);
System.exit(0);
});
dlg.setResizable(false);
dlg.setVisible(true);
}
}
}

View File

@@ -1,113 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.EffectData;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class EffectEditor extends JComponent {
EffectData currentData;
JTextField name =new JTextField();
JSpinner changeStartCards = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
JSpinner lifeModifier = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
JSpinner moveSpeed = new JSpinner(new SpinnerNumberModel(0f, 0, 1, 0.1f));
TextListEdit startBattleWithCard =new TextListEdit();
JCheckBox colorView =new JCheckBox();
EffectEditor opponent = null;
private boolean updating=false;
public EffectEditor(boolean isOpponentEffect)
{
if(!isOpponentEffect)
opponent=new EffectEditor(true);
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
FormPanel parameters=new FormPanel();
parameters.setBorder(BorderFactory.createTitledBorder("Effect"));
parameters.add("Name:", name);
parameters.add("Start with extra cards:", changeStartCards);
parameters.add("Change life:", lifeModifier);
parameters.add("Movement speed:", moveSpeed);
parameters.add("Start battle with cards:", startBattleWithCard);
parameters.add("color view:", colorView);
add(parameters);
if(!isOpponentEffect)
{ add(new JLabel("Opponent:")); add(opponent);}
changeStartCards.addChangeListener(e -> EffectEditor.this.updateEffect());
lifeModifier.addChangeListener(e -> EffectEditor.this.updateEffect());
moveSpeed.addChangeListener(e -> EffectEditor.this.updateEffect());
colorView.addChangeListener(e -> EffectEditor.this.updateEffect());
name.getDocument().addDocumentListener(new DocumentChangeListener(EffectEditor.this::updateEffect));
startBattleWithCard.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(EffectEditor.this::updateEffect));
if(opponent!=null)
opponent.addChangeListener(e -> EffectEditor.this.updateEffect());
}
private void updateEffect() {
if(currentData==null||updating)
return;
currentData.name=name.getText();
currentData.changeStartCards = (Integer) changeStartCards.getValue();
currentData.lifeModifier = (Integer) lifeModifier.getValue();
currentData.moveSpeed = (Float) moveSpeed.getValue();
currentData.startBattleWithCard = startBattleWithCard.getList();
currentData.colorView = colorView.isSelected();
currentData.opponent = opponent.currentData;
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
public void setCurrentEffect(EffectData data)
{
if(data==null)
return;
currentData=data;
refresh();
}
public EffectData getCurrentEffect()
{
return currentData;
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
updating=true;
name.setText(currentData.name);
lifeModifier.setValue(currentData.lifeModifier);
changeStartCards.setValue(currentData.changeStartCards);
startBattleWithCard.setText(currentData.startBattleWithCard);
colorView.setSelected(currentData.colorView);
moveSpeed.setValue(currentData.moveSpeed);
if(opponent!=null)
opponent.setCurrentEffect(currentData.opponent);
updating=false;
}
}

View File

@@ -1,337 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.EnemyData;
import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Enumeration;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class EnemyEdit extends FormPanel {
EnemyData currentData;
JTextField nameField=new JTextField();
JTextField nameOverride=new JTextField();
JTextField colorField=new JTextField();
JTextField ai=new JTextField();
JCheckBox flying=new JCheckBox();
JCheckBox boss=new JCheckBox();
JCheckBox ignoreDungeonEffect=new JCheckBox();
FloatSpinner lifeFiled= new FloatSpinner(0, 1000, 1);
FloatSpinner spawnRate= new FloatSpinner( 0.f, 1, 0.1f);
FloatSpinner scale= new FloatSpinner( 0.f, 8, 0.1f);
FloatSpinner difficulty= new FloatSpinner( 0.f, 1, 0.1f);
FloatSpinner speed= new FloatSpinner( 0.f, 100.f, 1.0f);
FilePicker deck=new FilePicker(new String[]{"dck","json"});
FilePicker atlas=new FilePicker(new String[]{"atlas"});
JTextField equipment=new JTextField();
RewardsEditor rewards=new RewardsEditor();
SwingAtlasPreview preview=new SwingAtlasPreview();
JTextField manualEntry = new JTextField(20);
private boolean updating=false;
DefaultListModel<String> existingModel = new DefaultListModel<>();
DefaultListModel<String> enemyModel = new DefaultListModel<>();
JList<String> existingTags;
JList<String> enemyTags;
public EnemyEdit()
{
setLayout(new BorderLayout());
FormPanel top=new FormPanel() { };
add(top, BorderLayout.NORTH);
JTabbedPane tabs = new JTabbedPane();
add(tabs, BorderLayout.CENTER);
FormPanel basicInfo=new FormPanel() { };
tabs.addTab("Basic Info", basicInfo);
top.add("Name:",nameField);
top.add("Display Name:", nameOverride);
basicInfo.add("Life:",lifeFiled);
basicInfo.add("Spawn rate:",spawnRate);
basicInfo.add("Scale:",scale);
basicInfo.add("Difficulty:",difficulty);
basicInfo.add("Speed:",speed);
basicInfo.add("Deck:",deck);
basicInfo.add("Equipment:",equipment);
basicInfo.add("Colors:",colorField);
basicInfo.add("ai:",ai);
basicInfo.add("flying:",flying);
basicInfo.add("boss:",boss);
JPanel visual = new JPanel();
visual.add("Sprite:",atlas);
visual.add(preview);
JPanel tags = new JPanel();
existingTags = new JList<>();
existingTags.getInputMap(JList.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke("ENTER"), "addSelected");
existingTags.getActionMap().put("addSelected", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
addSelected();
int index = existingTags.getSelectedIndex();
String selectedItem = existingTags.getSelectedValue();
if (selectedItem != null) {
enemyModel.addElement(selectedItem);
existingTags.grabFocus();
existingTags.setSelectedIndex(index<existingModel.size()?index:index-1);
}
}
});
existingModel = QuestController.getInstance().getEnemyTags();
existingTags.setModel(existingModel);
enemyTags = new JList<>();
enemyModel = new DefaultListModel<>();
enemyTags.setModel(enemyModel);
enemyTags.getModel().addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent e) {
doUpdate();
}
@Override
public void intervalRemoved(ListDataEvent e) {
doUpdate();
}
@Override
public void contentsChanged(ListDataEvent e) {
doUpdate();
}
});
JButton select = new JButton("Select");
select.addActionListener(q -> addSelected());
JButton add = new JButton("Manual Add");
add.addActionListener(q -> manualAdd(enemyModel));
JButton remove = new JButton("Remove Item");
remove.addActionListener(q -> removeSelected());
tags.setLayout(new BorderLayout());
JPanel left = new JPanel();
left.setLayout(new BorderLayout());
left.add(new JLabel("Tags already in use"), BorderLayout.NORTH);
JScrollPane listScroller = new JScrollPane(existingTags);
listScroller.setMinimumSize(new Dimension(400, 800));
left.add(listScroller, BorderLayout.CENTER);
tags.add(left, BorderLayout.WEST);
FormPanel tagEdit = new FormPanel();
tagEdit.setLayout(new BorderLayout());
FormPanel mappedTags = new FormPanel();
mappedTags.setLayout(new BorderLayout());
mappedTags.add(new JLabel("Tags Mapped to this object"), BorderLayout.NORTH);
JScrollPane listScroller2 = new JScrollPane(enemyTags);
listScroller2.setMinimumSize(new Dimension(400, 800));
mappedTags.add(listScroller2, BorderLayout.CENTER);
tagEdit.add(mappedTags,BorderLayout.EAST);
JPanel controlPanel = new JPanel();
controlPanel.add(select);
controlPanel.add(add);
controlPanel.add(manualEntry);
manualEntry.getInputMap(JList.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke("ENTER"), "addTyped");
manualEntry.getActionMap().put("addTyped", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (!manualEntry.getText().trim().isEmpty()) {
manualAdd(enemyModel);
manualEntry.grabFocus();
}
}
});
controlPanel.add(remove);
tagEdit.add(controlPanel, BorderLayout.CENTER);
tags.add(tagEdit,BorderLayout.CENTER);
JTextArea right1 = new JTextArea("This is really just to pad some space\n" +
"but also to explain the use of tags.\n" +
"Rather than adding 100's of object names\n" +
"to every quest definition, instead we will\n"+
"categorize enemies and points of interest with\n"+
"tags and reference those categories in quests");
right1.setEnabled(false);
tags.add(right1, BorderLayout.EAST);
tabs.addTab("Sprite", visual);
tabs.addTab("Rewards", rewards);
tabs.addTab("Quest Tags", tags);
equipment.getDocument().addDocumentListener(new DocumentChangeListener(EnemyEdit.this::updateEnemy));
atlas.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(EnemyEdit.this::updateEnemy));
colorField.getDocument().addDocumentListener(new DocumentChangeListener(EnemyEdit.this::updateEnemy));
ai.getDocument().addDocumentListener(new DocumentChangeListener(EnemyEdit.this::updateEnemy));
flying.addChangeListener(e -> EnemyEdit.this.updateEnemy());
boss.addChangeListener(e -> EnemyEdit.this.updateEnemy());
ignoreDungeonEffect.addChangeListener(e -> EnemyEdit.this.updateEnemy());
nameField.getDocument().addDocumentListener(new DocumentChangeListener(EnemyEdit.this::updateEnemy));
nameOverride.getDocument().addDocumentListener(new DocumentChangeListener(EnemyEdit.this::updateEnemy));
deck.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(EnemyEdit.this::updateEnemy));
lifeFiled.addChangeListener(e -> EnemyEdit.this.updateEnemy());
speed.addChangeListener(e -> EnemyEdit.this.updateEnemy());
scale.addChangeListener(e -> EnemyEdit.this.updateEnemy());
difficulty.addChangeListener(e -> EnemyEdit.this.updateEnemy());
spawnRate.addChangeListener(e -> EnemyEdit.this.updateEnemy());
rewards.addChangeListener(e -> EnemyEdit.this.updateEnemy());
lifeFiled.addChangeListener(e -> EnemyEdit.this.updateEnemy());
enemyModel.addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent e) {
EnemyEdit.this.updateEnemy();
}
@Override
public void intervalRemoved(ListDataEvent e) {
EnemyEdit.this.updateEnemy();
}
@Override
public void contentsChanged(ListDataEvent e) {
EnemyEdit.this.updateEnemy();
}
});
refresh();
}
private void doUpdate(){
EnemyEdit.this.updateEnemy();
}
private void addSelected(){
if (existingTags.getSelectedIndex()>-1)
enemyModel.addElement(existingTags.getModel().getElementAt(existingTags.getSelectedIndex()));
doUpdate();
}
private void removeSelected(){
if (enemyTags.getSelectedIndex()>-1)
enemyModel.remove(enemyTags.getSelectedIndex());
doUpdate();
}
private void filterExisting(DefaultListModel<String> filter){
DefaultListModel<String> toReturn = new DefaultListModel<>();
for (Enumeration<String> e = QuestController.getInstance().getEnemyTags().elements(); e.hasMoreElements();){
String toTest = e.nextElement();
if (toTest != null & !filter.contains(toTest)){
toReturn.addElement(toTest);
}
}
existingTags.setModel(toReturn);
}
private void manualAdd(DefaultListModel<String> model){
if (!manualEntry.getText().trim().isEmpty())
model.addElement(manualEntry.getText().trim());
manualEntry.setText("");
doUpdate();
}
public void updateEnemy() {
if(currentData==null||updating)
return;
currentData.name=nameField.getText();
currentData.colors=colorField.getText();
currentData.ai=ai.getText();
currentData.flying=flying.isSelected();
currentData.boss=boss.isSelected();
currentData.life= (int) lifeFiled.getValue();
currentData.sprite= atlas.getEdit().getText();
if(equipment.getText().isEmpty())
currentData.equipment=null;
else
currentData.equipment=equipment.getText().split(",");
currentData.speed= speed.floatValue();
currentData.scale= scale.floatValue();
currentData.spawnRate=spawnRate.floatValue();
currentData.difficulty=difficulty.floatValue();
currentData.deck= deck.getEdit().getText().split(",");
currentData.rewards= rewards.getRewards();
preview.setSpritePath(currentData.sprite);
ArrayList<String> tags = new ArrayList<>();
for (Enumeration<String> e = enemyModel.elements(); e.hasMoreElements();){
tags.add(e.nextElement());
}
tags.removeIf(String::isEmpty);
currentData.questTags = tags.toArray(currentData.questTags);
QuestController.getInstance().refresh();
filterExisting(enemyModel);
}
public void setCurrentEnemy(EnemyData data)
{
currentData=data;
refresh();
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
updating=true;
nameField.setText(currentData.name);
colorField.setText(currentData.colors);
ai.setText(currentData.ai);
boss.setSelected(currentData.boss);
flying.setSelected(currentData.flying);
lifeFiled.setValue(currentData.life);
atlas.getEdit().setText(currentData.sprite);
if(currentData.equipment!=null)
equipment.setText(String.join(",",currentData.equipment));
else
equipment.setText("");
deck.getEdit().setText(String.join(",",currentData.deck));
speed.setValue(currentData.speed);
scale.setValue(currentData.scale);
spawnRate.setValue(currentData.spawnRate);
difficulty.setValue(currentData.difficulty);
rewards.setRewards(currentData.rewards);
preview.setSpritePath(currentData.sprite);
enemyModel.clear();
for(String val : currentData.questTags) {
if (val != null)
enemyModel.addElement(val);
}
filterExisting(enemyModel);
updating=false;
}
}

View File

@@ -1,132 +0,0 @@
package forge.adventure.editor;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonWriter;
import forge.adventure.data.EnemyData;
import forge.adventure.util.Config;
import forge.adventure.util.Paths;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class EnemyEditor extends JComponent {
DefaultListModel<EnemyData> model = new DefaultListModel<>();
JList<EnemyData> list = new JList<>(model);
JToolBar toolBar = new JToolBar("toolbar");
EnemyEdit edit=new EnemyEdit();
public class EnemyDataRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof EnemyData))
return label;
EnemyData enemy=(EnemyData) value;
// Get the renderer component from parent class
label.setText(enemy.name);
SwingAtlas atlas=new SwingAtlas(Config.instance().getFile(enemy.sprite));
if(atlas.has("Avatar"))
label.setIcon(atlas.get("Avatar"));
else
{
ImageIcon img=atlas.getAny();
if(img!=null)
label.setIcon(img);
}
return label;
}
}
public void addButton(String name,ActionListener action)
{
JButton newButton=new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public EnemyEditor()
{
list.setCellRenderer(new EnemyDataRenderer());
list.addListSelectionListener(e -> EnemyEditor.this.updateEdit());
addButton("add", e -> EnemyEditor.this.addEnemy());
addButton("remove", e -> EnemyEditor.this.remove());
addButton("copy", e -> EnemyEditor.this.copy());
addButton("load", e -> {
EnemyEditor.this.load();
QuestController.getInstance().load();
});
addButton("save", e -> EnemyEditor.this.save());
BorderLayout layout=new BorderLayout();
setLayout(layout);
add(new JScrollPane(list), BorderLayout.LINE_START);
toolBar.setFloatable(false);
add(toolBar, BorderLayout.PAGE_START);
add(edit,BorderLayout.CENTER);
load();
}
private void copy() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
EnemyData data=new EnemyData(model.get(selected));
model.add(model.size(),data);
}
private void updateEdit() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
edit.setCurrentEnemy(model.get(selected));
edit.updateEnemy();
}
void save()
{
Array<EnemyData> allEnemies=new Array<>();
for(int i=0;i<model.getSize();i++)
allEnemies.add(model.get(i));
Json json = new Json(JsonWriter.OutputType.json);
FileHandle handle = Config.instance().getFile(Paths.ENEMIES);
handle.writeString(json.prettyPrint(json.toJson(allEnemies,Array.class, EnemyData.class)),false);
}
void load()
{
model.clear();
Array<EnemyData> allEnemies=new Array<>();
Json json = new Json();
FileHandle handle = Config.instance().getFile(Paths.ENEMIES);
if (handle.exists())
{
allEnemies = json.fromJson(Array.class, EnemyData.class, handle);
}
for (int i=0;i<allEnemies.size;i++) {
model.add(i,allEnemies.get(i));
}
}
void addEnemy()
{
EnemyData data=new EnemyData();
data.name="Enemy "+model.getSize();
model.add(model.size(),data);
}
void remove()
{
int selected=list.getSelectedIndex();
if(selected<0)
return;
model.remove(selected);
}
}

View File

@@ -1,51 +0,0 @@
package forge.adventure.editor;
import forge.adventure.util.Config;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.io.IOException;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class FilePicker extends Box {
JTextField edit=new JTextField();
JButton findButton=new JButton(UIManager.getIcon("FileView.directoryIcon"));
private final String[] fileEndings;
public FilePicker(String[] fileEndings) {
super(BoxLayout.X_AXIS);
this.fileEndings = fileEndings;
findButton.addActionListener(e -> FilePicker.this.find());
add(edit);
add(findButton);
}
JTextField getEdit()
{
return edit;
}
private void find() {
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(Config.instance().getFilePath(edit.getText())));
fc.setFileFilter( new FileNameExtensionFilter("Pick File",fileEndings));
fc.setMultiSelectionEnabled(false);
if (fc.showOpenDialog(this) ==
JFileChooser.APPROVE_OPTION) {
File selected = fc.getSelectedFile();
try {
if (selected != null&&selected.getCanonicalPath().startsWith(new File(Config.instance().getFilePath("")).getCanonicalPath())) {
edit.setText(selected.getCanonicalPath().substring(new File(Config.instance().getFilePath("")).getCanonicalPath().length()+1).replace('\\','/'));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@@ -1,19 +0,0 @@
package forge.adventure.editor;
import javax.swing.*;
public class FloatSpinner extends JSpinner{
public FloatSpinner()
{
this( 0.f, 1f, 0.1f);
}
public FloatSpinner(float min,float max,float stepSize)
{
super(new SpinnerNumberModel(new Float(0.0f), new Float(min), new Float (max), new Float(stepSize)));
}
public float floatValue()
{
return (Float) getValue();
}
}

View File

@@ -1,63 +0,0 @@
package forge.adventure.editor;
import javax.swing.*;
import java.awt.*;
public class FormPanel extends JPanel {
int row=0;
static final int MAXIMUM_LINES=300;
public FormPanel()
{
setLayout(new GridBagLayout()) ;
GridBagConstraints constraint=new GridBagConstraints();
constraint.weightx = 1.0;
constraint.weighty = 1.0;
constraint.gridy=MAXIMUM_LINES;
constraint.gridx=0;
constraint.gridwidth=2;
add(Box.createVerticalGlue(),constraint);
row++;
}
public void add(JComponent name,JComponent element)
{
GridBagConstraints constraint=new GridBagConstraints();
constraint.ipadx = 5;
constraint.ipady = 5;
constraint.weightx = 1.0;
constraint.weighty = 0.0;
constraint.gridy=row;
constraint.gridx=0;
constraint.anchor=GridBagConstraints.NORTHWEST;
add(name,constraint);
constraint.gridy=row;
constraint.gridx=1;
constraint.fill=GridBagConstraints.HORIZONTAL;
constraint.anchor=GridBagConstraints.NORTHEAST;
add(element,constraint);
row++;
}
public void add(String name,JComponent element)
{
add(new JLabel(name),element);
}
public void add(JComponent element)
{
GridBagConstraints constraint=new GridBagConstraints();
constraint.ipadx = 5;
constraint.ipady = 5;
constraint.weightx = 1.0;
constraint.weighty = 0.0;
constraint.gridy=row;
constraint.gridx=0;
constraint.gridwidth=2;
constraint.fill=GridBagConstraints.HORIZONTAL;
constraint.anchor=GridBagConstraints.NORTHEAST;
add(element,constraint);
row++;
}
}

View File

@@ -1,20 +0,0 @@
package forge.adventure.editor;
import javax.swing.*;
public class IntSpinner extends JSpinner {
public IntSpinner()
{
this( 0, 100, 1);
}
public IntSpinner(int min,int max,int stepSize)
{
super(new SpinnerNumberModel(new Integer(0), new Integer(min), new Integer (max), new Integer(stepSize)));
}
public int intValue()
{
return (Integer) getValue();
}
}

View File

@@ -1,86 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.ItemData;
import javax.swing.*;
import java.awt.*;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class ItemEdit extends JComponent {
ItemData currentData;
JTextField nameField=new JTextField();
JTextField equipmentSlot=new JTextField();
JTextField iconName=new JTextField();
EffectEditor effect=new EffectEditor(false);
JTextField description=new JTextField();
JCheckBox questItem=new JCheckBox();
JSpinner cost= new JSpinner(new SpinnerNumberModel(0, 0, 100000, 1));
private boolean updating=false;
public ItemEdit()
{
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
FormPanel parameters=new FormPanel();
parameters.setBorder(BorderFactory.createTitledBorder("Parameter"));
parameters.add("Name:",nameField);
parameters.add("equipmentSlot:",equipmentSlot);
parameters.add("description:",description);
parameters.add("iconName",iconName);
parameters.add("questItem",questItem);
parameters.add("cost",cost);
add(parameters);
add(effect);
add(new Box.Filler(new Dimension(0,0),new Dimension(0,Integer.MAX_VALUE),new Dimension(0,Integer.MAX_VALUE)));
nameField.getDocument().addDocumentListener(new DocumentChangeListener(ItemEdit.this::updateItem));
equipmentSlot.getDocument().addDocumentListener(new DocumentChangeListener(ItemEdit.this::updateItem));
description.getDocument().addDocumentListener(new DocumentChangeListener(ItemEdit.this::updateItem));
iconName.getDocument().addDocumentListener(new DocumentChangeListener(ItemEdit.this::updateItem));
cost.addChangeListener(e -> ItemEdit.this.updateItem());
questItem.addChangeListener(e -> ItemEdit.this.updateItem());
effect.addChangeListener(e -> ItemEdit.this.updateItem());
refresh();
}
private void updateItem() {
if(currentData==null||updating)
return;
currentData.name=nameField.getText();
currentData.equipmentSlot= equipmentSlot.getText();
currentData.effect= effect.getCurrentEffect();
currentData.description=description.getText();
currentData.iconName=iconName.getText();
currentData.questItem=questItem.isSelected();
currentData.cost= (Integer) cost.getValue();
}
public void setCurrentItem(ItemData data)
{
currentData=data;
refresh();
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
updating=true;
nameField.setText(currentData.name);
effect.setCurrentEffect(currentData.effect);
equipmentSlot.setText(currentData.equipmentSlot);
description.setText(currentData.description);
iconName.setText(currentData.iconName);
questItem.setSelected(currentData.questItem);
cost.setValue(currentData.cost);
updating=false;
}
}

View File

@@ -1,127 +0,0 @@
package forge.adventure.editor;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonWriter;
import forge.adventure.data.ItemData;
import forge.adventure.util.Config;
import forge.adventure.util.Paths;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class ItemsEditor extends JComponent {
DefaultListModel<ItemData> model = new DefaultListModel<>();
JList<ItemData> list = new JList<>(model);
JToolBar toolBar = new JToolBar("toolbar");
ItemEdit edit=new ItemEdit();
static SwingAtlas itemAtlas;
public class ItemDataRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof ItemData item))
return label;
// Get the renderer component from parent class
label.setText(item.name);
if(itemAtlas==null)
itemAtlas=new SwingAtlas(Config.instance().getFile(Paths.ITEMS_ATLAS));
if(itemAtlas.has(item.iconName))
label.setIcon(itemAtlas.get(item.iconName));
else
{
ImageIcon img=itemAtlas.getAny();
if(img!=null)
label.setIcon(img);
}
return label;
}
}
public void addButton(String name, ActionListener action)
{
JButton newButton=new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public ItemsEditor()
{
list.setCellRenderer(new ItemsEditor.ItemDataRenderer());
list.addListSelectionListener(e -> ItemsEditor.this.updateEdit());
addButton("add", e -> ItemsEditor.this.addItem());
addButton("remove", e -> ItemsEditor.this.remove());
addButton("copy", e -> ItemsEditor.this.copy());
addButton("load", e -> ItemsEditor.this.load());
addButton("save", e -> ItemsEditor.this.save());
BorderLayout layout=new BorderLayout();
setLayout(layout);
add(new JScrollPane(list), BorderLayout.LINE_START);
toolBar.setFloatable(false);
add(toolBar, BorderLayout.PAGE_START);
add(edit,BorderLayout.CENTER);
load();
}
private void copy() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
ItemData data=new ItemData(model.get(selected));
model.add(model.size(),data);
}
private void updateEdit() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
edit.setCurrentItem(model.get(selected));
}
void save()
{
Array<ItemData> allEnemies=new Array<>();
for(int i=0;i<model.getSize();i++)
allEnemies.add(model.get(i));
Json json = new Json(JsonWriter.OutputType.json);
FileHandle handle = Config.instance().getFile(Paths.ITEMS);
handle.writeString(json.prettyPrint(json.toJson(allEnemies,Array.class, ItemData.class)),false);
}
void load()
{
model.clear();
Array<ItemData> allEnemies=new Array<>();
Json json = new Json();
FileHandle handle = Config.instance().getFile(Paths.ITEMS);
if (handle.exists())
{
allEnemies =json.fromJson(Array.class, ItemData.class, handle);
}
for (int i=0;i<allEnemies.size;i++) {
model.add(i,allEnemies.get(i));
}
}
void addItem()
{
ItemData data=new ItemData();
data.name="Item "+model.getSize();
model.add(model.size(),data);
}
void remove()
{
int selected=list.getSelectedIndex();
if(selected<0)
return;
model.remove(selected);
}
}

View File

@@ -1,274 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.PointOfInterestData;
import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Enumeration;
public class PointOfInterestEdit extends JComponent {
PointOfInterestData currentData;
JTextField name = new JTextField();
JTextField type = new JTextField();
JSpinner count = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
FilePicker spriteAtlas = new FilePicker(new String[]{"atlas"});
JTextField sprite = new JTextField();
FilePicker map = new FilePicker(new String[]{"tmx"});
JSpinner radiusFactor= new JSpinner(new SpinnerNumberModel(0.0f, 0.0f, 2.0f, 0.1f));
SwingAtlasPreview preview=new SwingAtlasPreview(256,2000);
JTextField manualEntry = new JTextField(20);
DefaultListModel<String> existingModel = new DefaultListModel<>();
DefaultListModel<String> POIModel = new DefaultListModel<>();
JList<String> existingTags;
JList<String> POITags;
private boolean updating=false;
public PointOfInterestEdit()
{
JTabbedPane tabs = new JTabbedPane();
add(tabs, BorderLayout.CENTER);
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
FormPanel parameters=new FormPanel();
//parameters.setLayout(new BoxLayout(parameters, BoxLayout.Y_AXIS));
parameters.setBorder(BorderFactory.createTitledBorder("Parameter"));
JPanel tags = new JPanel();
tabs.addTab("Basic Info", parameters);
tabs.addTab("Quest Tags", tags);
parameters.add("Name:",name);
parameters.add("Type:",type);
parameters.add("Count:",count);
parameters.add("Sprite atlas:",spriteAtlas);
parameters.add("Sprite:",sprite);
parameters.add("Map:",map);
parameters.add("Radius factor:",radiusFactor);
parameters.add(preview);
name.getDocument().addDocumentListener(new DocumentChangeListener(PointOfInterestEdit.this::updateItem));
type.getDocument().addDocumentListener(new DocumentChangeListener(PointOfInterestEdit.this::updateItem));
count.addChangeListener(e -> PointOfInterestEdit.this.updateItem());
spriteAtlas.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(PointOfInterestEdit.this::updateItem));
sprite.getDocument().addDocumentListener(new DocumentChangeListener(PointOfInterestEdit.this::updateItem));
map.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(PointOfInterestEdit.this::updateItem));
radiusFactor.addChangeListener(e -> PointOfInterestEdit.this.updateItem());
existingTags = new JList<>();
existingTags.getInputMap(JList.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke("ENTER"), "addSelected");
existingTags.getActionMap().put("addSelected", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int index = existingTags.getSelectedIndex();
String selectedItem = existingTags.getSelectedValue();
if (selectedItem != null) {
POIModel.addElement(selectedItem);
existingTags.grabFocus();
existingTags.setSelectedIndex(index<existingModel.size()?index:index-1);
}
}
});
existingModel = QuestController.getInstance().getPOITags();
existingTags.setModel(existingModel);
POITags = new JList<>();
POIModel = new DefaultListModel<>();
POITags.setModel(POIModel);
POITags.getModel().addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent e) {
updateItem();
}
@Override
public void intervalRemoved(ListDataEvent e) {
updateItem();
}
@Override
public void contentsChanged(ListDataEvent e) {
updateItem();
}
});
JButton select = new JButton("Select");
select.addActionListener(q -> addSelected());
JButton add = new JButton("Manual Add");
add.addActionListener(q -> manualAdd(POIModel));
JButton remove = new JButton("Remove Item");
remove.addActionListener(q -> removeSelected());
tags.setLayout(new BorderLayout());
JPanel left = new JPanel();
left.setLayout(new BorderLayout());
left.add(new JLabel("Tags already in use"), BorderLayout.NORTH);
JScrollPane listScroller = new JScrollPane(existingTags);
listScroller.setMinimumSize(new Dimension(400, 800));
left.add(listScroller, BorderLayout.CENTER);
tags.add(left, BorderLayout.WEST);
FormPanel tagEdit = new FormPanel();
tagEdit.setLayout(new BorderLayout());
FormPanel mappedTags = new FormPanel();
mappedTags.setLayout(new BorderLayout());
mappedTags.add(new JLabel("Tags Mapped to this object"), BorderLayout.NORTH);
JScrollPane listScroller2 = new JScrollPane(POITags);
listScroller2.setMinimumSize(new Dimension(400, 800));
mappedTags.add(listScroller2, BorderLayout.CENTER);
tagEdit.add(mappedTags,BorderLayout.EAST);
JPanel controlPanel = new JPanel();
controlPanel.add(select);
controlPanel.add(add);
controlPanel.add(manualEntry);
manualEntry.getInputMap(JList.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke("ENTER"), "addTyped");
manualEntry.getActionMap().put("addTyped", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (!manualEntry.getText().trim().isEmpty()) {
manualAdd(POIModel);
manualEntry.grabFocus();
}
}
});
controlPanel.add(remove);
tagEdit.add(controlPanel, BorderLayout.CENTER);
tags.add(tagEdit,BorderLayout.CENTER);
JTextArea right1 = new JTextArea("This is really just to pad some space\n" +
"but also to explain the use of tags.\n" +
"Rather than adding 100's of object names\n" +
"to every quest definition, instead we will\n"+
"categorize enemies and points of interest with\n"+
"tags and reference those categories in quests");
right1.setEnabled(false);
tags.add(right1, BorderLayout.EAST);
refresh();
}
private void updateItem() {
if(currentData==null||updating)
return;
currentData.name=name.getText();
currentData.type= type.getText();
currentData.count= (Integer) count.getValue();
currentData.spriteAtlas=spriteAtlas.getEdit().getText();
currentData.sprite=sprite.getText();
currentData.map=map.getEdit().getText();
currentData.radiusFactor= (Float) radiusFactor.getValue();
ArrayList<String> tags = new ArrayList<>();
for (Enumeration<String> e = POIModel.elements(); e.hasMoreElements();){
tags.add(e.nextElement());
}
currentData.questTags = tags.toArray(currentData.questTags);
QuestController.getInstance().refresh();
filterExisting(POIModel);
}
public void setCurrent(PointOfInterestData data)
{
currentData=data;
refresh();
}
private void addSelected(){
if (existingTags.getSelectedIndex()>-1)
POIModel.addElement(existingTags.getModel().getElementAt(existingTags.getSelectedIndex()));
updateItem();
}
private void removeSelected(){
if (POITags.getSelectedIndex()>-1)
POIModel.remove(POITags.getSelectedIndex());
updateItem();
}
private void filterExisting(DefaultListModel<String> filter){
DefaultListModel<String> toReturn = new DefaultListModel<>();
for (Enumeration<String> e = QuestController.getInstance().getPOITags().elements(); e.hasMoreElements();){
String toTest = e.nextElement();
if (toTest != null & !filter.contains(toTest)){
toReturn.addElement(toTest);
}
}
existingTags.setModel(toReturn);
}
private void manualAdd(DefaultListModel<String> model){
if (!manualEntry.getText().trim().isEmpty())
model.addElement(manualEntry.getText().trim());
manualEntry.setText("");
updateItem();
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
updating=true;
name.setText(currentData.name);
type.setText(currentData.type);
count.setValue(currentData.count);
spriteAtlas.getEdit().setText(currentData.spriteAtlas);
sprite.setText(currentData.sprite);
map.getEdit().setText(currentData.map);
radiusFactor.setValue(currentData.radiusFactor);
preview.setSpritePath(currentData.spriteAtlas,currentData.sprite);
POIModel.clear();
for(String val : currentData.questTags) {
if (val != null)
POIModel.addElement(val);
}
filterExisting(POIModel);
updating=false;
}
}

View File

@@ -1,134 +0,0 @@
package forge.adventure.editor;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonWriter;
import forge.adventure.data.PointOfInterestData;
import forge.adventure.util.Config;
import forge.adventure.util.Paths;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.HashMap;
public class PointOfInterestEditor extends JComponent {
DefaultListModel<PointOfInterestData> model = new DefaultListModel<>();
JList<PointOfInterestData> list = new JList<>(model);
JToolBar toolBar = new JToolBar("toolbar");
PointOfInterestEdit edit=new PointOfInterestEdit();
static HashMap<String,SwingAtlas> atlas=new HashMap<>();
public static class PointOfInterestRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof PointOfInterestData))
return label;
PointOfInterestData poi=(PointOfInterestData) value;
// Get the renderer component from parent class
label.setText(poi.name);
if(!atlas.containsKey(poi.spriteAtlas))
atlas.put(poi.spriteAtlas,new SwingAtlas(Config.instance().getFile(poi.spriteAtlas)));
SwingAtlas poiAtlas = atlas.get(poi.spriteAtlas);
if(poiAtlas.has(poi.sprite))
label.setIcon(poiAtlas.get(poi.sprite));
else
{
ImageIcon img=poiAtlas.getAny();
if(img!=null)
label.setIcon(img);
}
return label;
}
}
public void addButton(String name, ActionListener action)
{
JButton newButton=new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public PointOfInterestEditor()
{
list.setCellRenderer(new PointOfInterestEditor.PointOfInterestRenderer());
list.addListSelectionListener(e -> PointOfInterestEditor.this.updateEdit());
addButton("add", e -> PointOfInterestEditor.this.addItem());
addButton("remove", e -> PointOfInterestEditor.this.remove());
addButton("copy", e -> PointOfInterestEditor.this.copy());
addButton("load", e -> PointOfInterestEditor.this.load());
addButton("save", e -> PointOfInterestEditor.this.save());
BorderLayout layout=new BorderLayout();
setLayout(layout);
add(new JScrollPane(list), BorderLayout.LINE_START);
toolBar.setFloatable(false);
add(toolBar, BorderLayout.PAGE_START);
add(edit,BorderLayout.CENTER);
load();
}
private void copy() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
PointOfInterestData data=new PointOfInterestData(model.get(selected));
model.add(model.size(),data);
}
private void updateEdit() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
edit.setCurrent(model.get(selected));
}
void save()
{
Array<PointOfInterestData> allEnemies=new Array<>();
for(int i=0;i<model.getSize();i++)
allEnemies.add(model.get(i));
Json json = new Json(JsonWriter.OutputType.json);
FileHandle handle = Config.instance().getFile(Paths.POINTS_OF_INTEREST);
handle.writeString(json.prettyPrint(json.toJson(allEnemies,Array.class, PointOfInterestData.class)),false);
}
void load()
{
model.clear();
Array<PointOfInterestData> allEnemies=new Array<>();
Json json = new Json();
FileHandle handle = Config.instance().getFile(Paths.POINTS_OF_INTEREST);
if (handle.exists())
{
allEnemies =json.fromJson(Array.class, PointOfInterestData.class, handle);
}
for (int i=0;i<allEnemies.size;i++) {
model.add(i,allEnemies.get(i));
}
QuestController.getInstance().load();
}
void addItem()
{
PointOfInterestData data=new PointOfInterestData();
data.name="PoI "+model.getSize();
model.add(model.size(),data);
}
void remove()
{
int selected=list.getSelectedIndex();
if(selected<0)
return;
model.remove(selected);
}
}

View File

@@ -1,236 +0,0 @@
package forge.adventure.editor;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonWriter;
import forge.adventure.data.AdventureQuestData;
import forge.adventure.data.EnemyData;
import forge.adventure.data.PointOfInterestData;
import forge.adventure.util.Config;
import forge.adventure.util.Paths;
import javax.swing.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class QuestController {
public final DefaultListModel<String> POITags = new DefaultListModel<>();
public final DefaultListModel<String> enemyTags = new DefaultListModel<>();
public final DefaultListModel<String> questEnemyTags = new DefaultListModel<>();
public final DefaultListModel<String> questTags = new DefaultListModel<>();
public final DefaultListModel<String> questPOITags = new DefaultListModel<>();
private final DefaultListModel<PointOfInterestData> allPOI = new DefaultListModel<>();
private final DefaultListModel<EnemyData> allEnemies = new DefaultListModel<>();
private final DefaultListModel<String> questSourceTags = new DefaultListModel<>();
private final DefaultListModel<AdventureQuestData> allQuests = new DefaultListModel<>();
private static QuestController instance;
public static QuestController getInstance() {
if (instance == null)
instance = new QuestController();
return instance;
}
public DefaultListModel<AdventureQuestData> getAllQuests() {
return allQuests;
}
private QuestController(){
load();
}
public DefaultListModel<String> getEnemyTags(){
DefaultListModel<String> toReturn = new DefaultListModel<>();
for (int i = 0; i < enemyTags.size(); i++){
toReturn.removeElement(enemyTags.get(i));
toReturn.addElement(enemyTags.get(i));
}
List<Object> sortedObjects = Arrays.stream(toReturn.toArray()).sorted().collect(Collectors.toList());
toReturn.clear();
for (Object sortedObject : sortedObjects) {
toReturn.addElement((String) sortedObject);
}
return toReturn;
}
public DefaultListModel<String> getPOITags(){
DefaultListModel<String> toReturn = new DefaultListModel<>();
for (int i = 0; i < POITags.size(); i++){
toReturn.removeElement(POITags.get(i));
toReturn.addElement(POITags.get(i));
}
List<Object> sortedObjects = Arrays.stream(toReturn.toArray()).sorted().collect(Collectors.toList());
toReturn.clear();
for (Object sortedObject : sortedObjects) {
toReturn.addElement((String) sortedObject);
}
return toReturn;
}
public DefaultListModel<String> getSourceTags(){
DefaultListModel<String> toReturn = new DefaultListModel<>();
for (int i = 0; i < questSourceTags.size(); i++)
{
toReturn.removeElement(questSourceTags.get(i));
toReturn.addElement(questSourceTags.get(i));
}
List<Object> sortedObjects = Arrays.stream(toReturn.toArray()).sorted().collect(Collectors.toList());
toReturn.clear();
for (Object sortedObject : sortedObjects) {
toReturn.addElement((String) sortedObject);
}
return toReturn;
}
public void refresh(){
enemyTags.clear();
POITags.clear();
questPOITags.clear();
questEnemyTags.clear();
questTags.clear();
questSourceTags.clear();
for (int i=0;i<allEnemies.size();i++) {
for (String tag : allEnemies.get(i).questTags)
{
enemyTags.removeElement(tag); //Ensure uniqueness
if (tag!= null)
enemyTags.addElement(tag);
}
}
for (int i=0;i<allPOI.size();i++) {
for (String tag : allPOI.get(i).questTags)
{
POITags.removeElement(tag); //Ensure uniqueness
if (tag!= null)
POITags.addElement(tag);
}
}
for (int i=0;i<allQuests.size();i++) {
for (String tag : allQuests.get(i).questEnemyTags)
{
questEnemyTags.removeElement(tag); //Ensure uniqueness
if (tag!= null)
questEnemyTags.addElement(tag);
}
for (String tag : allQuests.get(i).questPOITags)
{
questPOITags.removeElement(tag); //Ensure uniqueness
if (tag!= null)
questPOITags.addElement(tag);
}
for (String tag : allQuests.get(i).questSourceTags)
{
questSourceTags.removeElement(tag); //Ensure uniqueness
if (tag!= null)
questSourceTags.addElement(tag);
}
}
}
public void load()
{
allEnemies.clear();
Array<EnemyData> enemyJSON=new Array<>();
Json json = new Json();
FileHandle handle = Config.instance().getFile(Paths.ENEMIES);
if (handle.exists())
{
enemyJSON = json.fromJson(Array.class, EnemyData.class, handle);
}
for (int i=0;i<enemyJSON.size;i++) {
allEnemies.add(i,enemyJSON.get(i));
for (String tag : enemyJSON.get(i).questTags)
{
enemyTags.removeElement(tag); //Ensure uniqueness
if (tag!= null)
enemyTags.addElement(tag);
}
}
allPOI.clear();
Array<PointOfInterestData> POIJSON=new Array<>();
json = new Json();
handle = Config.instance().getFile(Paths.POINTS_OF_INTEREST);
if (handle.exists())
{
POIJSON = json.fromJson(Array.class, PointOfInterestData.class, handle);
}
for (int i=0;i<POIJSON.size;i++) {
allPOI.add(i,POIJSON.get(i));
for (String tag : POIJSON.get(i).questTags)
{
POITags.removeElement(tag); //Ensure uniqueness
if (tag!= null)
POITags.addElement(tag);
}
}
allQuests.clear();
Array<AdventureQuestData> questJSON=new Array<>();
json = new Json();
handle = Config.instance().getFile(Paths.QUESTS);
if (handle.exists())
{
questJSON = json.fromJson(Array.class, AdventureQuestData.class, handle);
}
for (int i=0;i<questJSON.size;i++) {
AdventureQuestData template = questJSON.get(i);
template.isTemplate = true;
allQuests.add(i,template);
for (String tag : template.questEnemyTags)
{
questEnemyTags.removeElement(tag); //Ensure uniqueness
if (tag!= null)
questEnemyTags.addElement(tag);
}
for (String tag : template.questPOITags)
{
questPOITags.removeElement(tag); //Ensure uniqueness
if (tag!= null)
questPOITags.addElement(tag);
}
for (String tag : template.questSourceTags)
{
questSourceTags.removeElement(tag); //Ensure uniqueness
if (tag!= null)
questSourceTags.addElement(tag);
}
}
}
void save()
{
Json json = new Json(JsonWriter.OutputType.json);
FileHandle handle = Config.instance().getFile(Paths.QUESTS);
AdventureQuestData[] saveData = Arrays.stream(allQuests.toArray()).map(AdventureQuestData.class::cast).toArray(AdventureQuestData[]::new);
handle.writeString(json.prettyPrint(json.toJson(saveData,Array.class, AdventureQuestData.class)),false);
}
}

View File

@@ -1,387 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.AdventureQuestData;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Enumeration;
public class QuestEdit extends FormPanel {
AdventureQuestData currentData;
//public JSpinner spawnWeight= new JSpinner(new SpinnerNumberModel(0.0f, 0.f, 1f, 0.1f));
public JLabel id = new JLabel();
public JTextField name=new JTextField();
public JTextField description=new JTextField();
public JTextField synopsis=new JTextField();
public JCheckBox storyQuest = new JCheckBox();
public JTextField rewardDescription=new JTextField();
public QuestStageEditor stages =new QuestStageEditor();
JTabbedPane tabs =new JTabbedPane();
public DialogEditor prologueEditor =new DialogEditor();
public DialogEditor epilogueEditor =new DialogEditor();
public DialogEditor offerEditor = new DialogEditor();
public DialogEditor failureEditor = new DialogEditor();
public DialogEditor declineEditor = new DialogEditor();
private boolean updating=false;
JTextField manualEntry = new JTextField(20);
DefaultListModel<String> existingModel = new DefaultListModel<>();
DefaultListModel<String> selectedTagModel = new DefaultListModel<>();
JList<String> existingTags;
JList<String> selectedTags;
JPanel tags = new JPanel();
public QuestEdit()
{
FormPanel center=new FormPanel() { };
center.add("Quest ID:", id);
center.add("Name:",name);
//center.add("Synopsis (dev mode):",synopsis);
center.add("Description:",description);
center.add("Reward Description:",rewardDescription);
center.add("Storyline Quest", storyQuest);
add(center);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(tabs);
tabs.add("Quest Stages", getStagesTab());
tabs.add("Offer Dialog",getOfferTab());
tabs.add("Prologue",getPrologueTab());
tabs.add("Epilogue",getEpilogueTab());
tabs.add("Failure Dialog", getFailureTab());
tabs.add("Decline Dialog",getDeclineTab());
tabs.add("Quest Sources", getSourcesTab());
existingTags = new JList<>();
existingTags.getInputMap(JList.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke("ENTER"), "addSelected");
existingTags.getActionMap().put("addSelected", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
addSelected();
int index = existingTags.getSelectedIndex();
String selectedItem = existingTags.getSelectedValue();
if (selectedItem != null) {
selectedTagModel.addElement(selectedItem);
existingTags.grabFocus();
existingTags.setSelectedIndex(index<existingModel.size()?index:index-1);
}
}
});
existingModel = QuestController.getInstance().getSourceTags();
existingTags.setModel(existingModel);
selectedTags = new JList<>();
selectedTagModel = new DefaultListModel<>();
selectedTags.setModel(selectedTagModel);
selectedTags.getModel().addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent e) {
doUpdate();
}
@Override
public void intervalRemoved(ListDataEvent e) {
doUpdate();
}
@Override
public void contentsChanged(ListDataEvent e) {
doUpdate();
}
});
JButton select = new JButton("Select");
select.addActionListener(q -> addSelected());
JButton add = new JButton("Manual Add");
add.addActionListener(q -> manualAdd(selectedTagModel));
JButton remove = new JButton("Remove Item");
remove.addActionListener(q -> removeSelected());
tags.setLayout(new BorderLayout());
JPanel left = new JPanel();
left.setLayout(new BorderLayout());
left.add(new JLabel("Tags already in use"), BorderLayout.NORTH);
JScrollPane listScroller = new JScrollPane(existingTags);
listScroller.setMinimumSize(new Dimension(400, 800));
left.add(listScroller, BorderLayout.CENTER);
tags.add(left, BorderLayout.WEST);
FormPanel tagEdit = new FormPanel();
tagEdit.setLayout(new BorderLayout());
FormPanel mappedTags = new FormPanel();
mappedTags.setLayout(new BorderLayout());
mappedTags.add(new JLabel("Tags Mapped to this object"), BorderLayout.NORTH);
JScrollPane listScroller2 = new JScrollPane(selectedTags);
listScroller2.setMinimumSize(new Dimension(400, 800));
mappedTags.add(listScroller2, BorderLayout.CENTER);
tagEdit.add(mappedTags,BorderLayout.EAST);
JPanel controlPanel = new JPanel();
controlPanel.add(select);
controlPanel.add(add);
controlPanel.add(manualEntry);
manualEntry.getInputMap(JList.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke("ENTER"), "addTyped");
manualEntry.getActionMap().put("addTyped", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (!manualEntry.getText().trim().isEmpty()) {
manualAdd(selectedTagModel);
manualEntry.grabFocus();
}
}
});
controlPanel.add(remove);
tagEdit.add(controlPanel, BorderLayout.CENTER);
tags.add(tagEdit,BorderLayout.CENTER);
JTextArea right1 = new JTextArea("This is really just to pad some space\n" +
"but also to explain the use of tags.\n" +
"Rather than adding 100's of object names\n" +
"to every quest definition, instead we will\n"+
"categorize enemies and points of interest with\n"+
"tags and reference those categories in quests");
right1.setEnabled(false);
tags.add(right1, BorderLayout.EAST);
name.getDocument().addDocumentListener(new DocumentChangeListener(QuestEdit.this::updateQuest));
description.getDocument().addDocumentListener(new DocumentChangeListener(QuestEdit.this::updateQuest));
synopsis.getDocument().addDocumentListener(new DocumentChangeListener(QuestEdit.this::updateQuest));
storyQuest.getModel().addChangeListener(q -> QuestEdit.this.updateQuest());
rewardDescription.getDocument().addDocumentListener(new DocumentChangeListener(QuestEdit.this::updateQuest));
stages.addChangeListener(e -> QuestEdit.this.updateQuest());
offerEditor.addChangeListener(e -> QuestEdit.this.updateQuest());
prologueEditor.addChangeListener(e -> QuestEdit.this.updateQuest());
epilogueEditor.addChangeListener(e -> QuestEdit.this.updateQuest());
failureEditor.addChangeListener(e -> QuestEdit.this.updateQuest());
declineEditor.addChangeListener(e -> QuestEdit.this.updateQuest());
stages.addChangeListener(e -> QuestEdit.this.updateQuest());
selectedTagModel.addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent e) {
QuestEdit.this.updateQuest();
}
@Override
public void intervalRemoved(ListDataEvent e) {
QuestEdit.this.updateQuest();
}
@Override
public void contentsChanged(ListDataEvent e) {
QuestEdit.this.updateQuest();
}
});
refresh();
}
private void doUpdate(){
QuestEdit.this.updateQuest();
}
private void addSelected(){
if (existingTags.getSelectedIndex()>-1)
selectedTagModel.addElement(existingTags.getModel().getElementAt(existingTags.getSelectedIndex()));
doUpdate();
}
private void removeSelected(){
if (selectedTags.getSelectedIndex()>-1)
selectedTagModel.remove(selectedTags.getSelectedIndex());
doUpdate();
}
private void filterExisting(DefaultListModel<String> filter){
DefaultListModel<String> toReturn = new DefaultListModel<>();
for (Enumeration<String> e = QuestController.getInstance().getSourceTags().elements(); e.hasMoreElements();){
String toTest = e.nextElement();
if (toTest != null & !filter.contains(toTest)){
toReturn.addElement(toTest);
}
}
existingTags.setModel(toReturn);
}
private void manualAdd(DefaultListModel<String> model){
if (!manualEntry.getText().trim().isEmpty())
model.addElement(manualEntry.getText().trim());
manualEntry.setText("");
doUpdate();
}
protected void updateQuest() {
if(currentData==null||updating)
return;
currentData.name = name.getText();
currentData.storyQuest = storyQuest.isSelected();
currentData.synopsis = synopsis.getText();
currentData.description = description.getText();
currentData.rewardDescription = rewardDescription.getText();
currentData.stages = stages.getStages();
currentData.offerDialog = offerEditor.getDialogData();
currentData.prologue = prologueEditor.getDialogData();
currentData.epilogue = epilogueEditor.getDialogData();
currentData.failureDialog = failureEditor.getDialogData();
currentData.declinedDialog = declineEditor.getDialogData();
ArrayList<String> tags = new ArrayList<>();
for (Enumeration<String> e = selectedTagModel.elements(); e.hasMoreElements();){
tags.add(e.nextElement());
}
currentData.questSourceTags = tags.toArray(currentData.questSourceTags);
QuestController.getInstance().refresh();
filterExisting(selectedTagModel);
}
public void setCurrentQuest(AdventureQuestData data)
{
currentData=data;
refresh();
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
setVisible(true);
updating=true;
id.setText(String.valueOf(currentData.getID()));
name.setText(currentData.name);
description.setText(currentData.description);
synopsis.setText(currentData.synopsis);
storyQuest.getModel().setSelected(currentData.storyQuest);
rewardDescription.setText(currentData.rewardDescription);
stages.setStages(currentData);
offerEditor.loadData(currentData.offerDialog);
prologueEditor.loadData(currentData.prologue);
epilogueEditor.loadData(currentData.epilogue);
failureEditor.loadData(currentData.failureDialog);
declineEditor.loadData(currentData.declinedDialog);
selectedTagModel.clear();
for(String val : currentData.questSourceTags) {
if (val != null)
selectedTagModel.addElement(val);
}
filterExisting(selectedTagModel);
updating=false;
}
public JPanel getOfferTab(){
JPanel offerTab = new JPanel();
offerTab.setLayout(new BoxLayout(offerTab, BoxLayout.Y_AXIS));
FormPanel center = new FormPanel();
center.add(offerEditor);
offerTab.add(center);
return offerTab;
}
public JPanel getPrologueTab(){
JPanel prologueTab = new JPanel();
prologueTab.setLayout(new BoxLayout(prologueTab, BoxLayout.Y_AXIS));
FormPanel center = new FormPanel();
center.add(prologueEditor);
prologueTab.add(center);
return prologueTab;
}
public JPanel getEpilogueTab(){
JPanel epilogueTab = new JPanel();
epilogueTab.setLayout(new BoxLayout(epilogueTab, BoxLayout.Y_AXIS));
FormPanel center = new FormPanel();
center.add(epilogueEditor);
epilogueTab.add(center);
return epilogueTab;
}
public JPanel getFailureTab(){
JPanel failureTab = new JPanel();
failureTab.setLayout(new BoxLayout(failureTab, BoxLayout.Y_AXIS));
FormPanel center = new FormPanel();
center.add(failureEditor);
failureTab.add(center);
return failureTab;
}
public JPanel getDeclineTab(){
JPanel declineTab = new JPanel();
declineTab.setLayout(new BoxLayout(declineTab, BoxLayout.Y_AXIS));
FormPanel center = new FormPanel();
center.add(declineEditor);
declineTab.add(center);
return declineTab;
}
public JPanel getStagesTab(){
JPanel stagesTab = new JPanel();
stagesTab.setLayout(new BoxLayout(stagesTab, BoxLayout.Y_AXIS));
FormPanel center = new FormPanel();
center.add(stages);
stagesTab.add(center);
return stagesTab;
}
public JPanel getSourcesTab(){
JPanel sourcesTab = new JPanel();
sourcesTab.setLayout(new BoxLayout(sourcesTab, BoxLayout.Y_AXIS));
FormPanel center = new FormPanel();
center.add(tags);
sourcesTab.add(center);
return sourcesTab;
}
}

View File

@@ -1,103 +0,0 @@
package forge.adventure.editor;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonWriter;
import forge.adventure.data.AdventureQuestData;
import forge.adventure.util.Config;
import forge.adventure.util.Paths;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class QuestEditor extends JComponent {
JList<AdventureQuestData> list = new JList<>(QuestController.getInstance().getAllQuests());
JToolBar toolBar = new JToolBar("toolbar");
QuestEdit edit=new QuestEdit();
public class QuestDataRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof AdventureQuestData quest))
return label;
// Get the renderer component from parent class
label.setText(quest.name);
return label;
}
}
public void addButton(String name,ActionListener action)
{
JButton newButton=new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public QuestEditor()
{
list.setCellRenderer(new QuestDataRenderer());
list.addListSelectionListener(e -> QuestEditor.this.updateEdit());
addButton("Add Quest", e -> QuestEditor.this.addStage());
addButton("Remove", e -> QuestEditor.this.remove());
addButton("Copy", e -> QuestEditor.this.copy());
addButton("Load", e -> QuestController.getInstance().load());
addButton("Save", e -> QuestEditor.this.save());
BorderLayout layout=new BorderLayout();
setLayout(layout);
add(new JScrollPane(list), BorderLayout.LINE_START);
toolBar.setFloatable(false);
add(toolBar, BorderLayout.PAGE_START);
add(edit,BorderLayout.CENTER);
edit.setVisible(false);
}
private void copy() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
AdventureQuestData data=new AdventureQuestData(QuestController.getInstance().getAllQuests().get(selected));
data.isTemplate = true;
QuestController.getInstance().getAllQuests().add(QuestController.getInstance().getAllQuests().size(),data);
}
private void updateEdit() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
edit.setCurrentQuest(QuestController.getInstance().getAllQuests().get(selected));
}
void save()
{
Array<AdventureQuestData> allQuests=new Array<>();
for(int i=0;i<QuestController.getInstance().getAllQuests().getSize();i++) {
allQuests.add(QuestController.getInstance().getAllQuests().get(i));
}
Json json = new Json(JsonWriter.OutputType.json);
FileHandle handle = Config.instance().getFile(Paths.QUESTS);
handle.writeString(json.prettyPrint(json.toJson(allQuests,Array.class, AdventureQuestData.class)),false);
QuestController.getInstance().save();
}
void addStage()
{
AdventureQuestData data=new AdventureQuestData();
data.name="New Quest "+QuestController.getInstance().getAllQuests().getSize();
data.isTemplate = true;
QuestController.getInstance().getAllQuests().add(QuestController.getInstance().getAllQuests().size(),data);
}
void remove()
{
int selected=list.getSelectedIndex();
if(selected<0)
return;
QuestController.getInstance().getAllQuests().remove(selected);
edit.setVisible(false);
}
}

View File

@@ -1,779 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.*;
import forge.adventure.util.AdventureQuestController;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class QuestStageEdit extends FormPanel {
private boolean updating=false;
AdventureQuestStage currentData;
AdventureQuestData currentQuestData;
public JTextField name=new JTextField("", 25);
public JTextField description=new JTextField("", 25);
public TextListEdit itemNames =new TextListEdit();
public TextListEdit spriteNames =new TextListEdit();
public TextListEdit equipNames =new TextListEdit();
public TextListEdit prerequisites =new TextListEdit(currentQuestData!=null?(String[])Arrays.stream(currentQuestData.stages).filter(q -> !q.equals(currentData)).toArray():new String[]{}); //May not be the right way to do this, will come back to it.
JTabbedPane tabs =new JTabbedPane();
DialogEditor prologueEditor = new DialogEditor();
DialogEditor epilogueEditor = new DialogEditor();
public QuestStageEdit()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(getInfoTab());
add(tabs);
tabs.add("Objective", getObjectiveTab());
tabs.add("Prologue",getPrologueTab());
tabs.add("Epilogue",getEpilogueTab());
tabs.add("Prerequisites",getPrereqTab());
//temp
nyi.setForeground(Color.red);
//
addListeners();
}
public JPanel getInfoTab(){
JPanel infoTab = new JPanel();
FormPanel center=new FormPanel();
center.add("name:",name);
center.add("description:",description);
name.setSize(400, name.getHeight());
description.setSize(400, description.getHeight());
infoTab.add(center);
name.getDocument().addDocumentListener(new DocumentChangeListener(QuestStageEdit.this::updateStage));
description.getDocument().addDocumentListener(new DocumentChangeListener(QuestStageEdit.this::updateStage));
prerequisites.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(QuestStageEdit.this::updateStage));
return infoTab;
}
public JPanel getPrologueTab(){
JPanel prologueTab = new JPanel();
prologueTab.setLayout(new BoxLayout(prologueTab, BoxLayout.Y_AXIS));
FormPanel center = new FormPanel();
center.add(prologueEditor);
prologueTab.add(center);
return prologueTab;
}
public JPanel getEpilogueTab(){
JPanel epilogueTab = new JPanel();
epilogueTab.setLayout(new BoxLayout(epilogueTab, BoxLayout.Y_AXIS));
FormPanel center = new FormPanel();
center.add(epilogueEditor);
epilogueTab.add(center);
return epilogueTab;
}
private JComboBox<AdventureQuestController.ObjectiveTypes> objectiveType;
private final JLabel nyi = new JLabel("Not yet implemented");
private final JTextField deliveryItem=new JTextField(25);
private final JTextField mapFlag = new JTextField(25);
private Box mapFlagGroup;
private final JSpinner flagSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 1000, 1));
private Box flagValueGroup;
private final JRadioButton anyPOI = new JRadioButton("Any Point of Interest matching tags is valid");
private final JRadioButton specificPOI = new JRadioButton("Only a specific Point of Interest is valid");
private final ButtonGroup anyPOIGroup = new ButtonGroup();
private final JCheckBox here = new JCheckBox("Use current map instead of selecting tags");
private final JCheckBox mixedEnemies = new JCheckBox("Mixture of enemy types matching");
private final JLabel count1Description = new JLabel("(Count 1 description)");
private final JLabel count2Description = new JLabel("(Count 2 description)");
private final JLabel count3Description = new JLabel("(Count 3 description)");
private final JLabel count4Description = new JLabel("(Count 4 description)");
private final JSpinner count1Spinner = new JSpinner(new SpinnerNumberModel(1, 0, 100, 1));
private final JSpinner count2Spinner = new JSpinner(new SpinnerNumberModel(1, 0, 100, 1));
private final JSpinner count3Spinner = new JSpinner(new SpinnerNumberModel(1, 0, 100, 1));
private final JSpinner count4Spinner = new JSpinner(new SpinnerNumberModel(1, 0, 100, 1));
private final JLabel arenaLabel = new JLabel("Enter the arena and prove your worth. (Note: Please be sure the PoIs selected have an arena)");
private final JLabel characterFlagLabel = new JLabel("Have the selected character flag set to a given value. (Caution: You're probably looking for QuestFlag or MapFlag instead)");
private final JLabel clearLabel = new JLabel("Clear all enemies from the target area.");
private final JLabel completeQuestLabel = new JLabel("Complete other quests issued by target POI. Primarily used for busy work as a part of storyline quests.");
private final JLabel defeatLabel = new JLabel("Defeat a number of enemies of the indicated type.");
private final JLabel deliveryLabel = new JLabel("Travel to the given destination to deliver an item (not tracked in inventory).");
private final JLabel escortLabel = new JLabel("Protect your target as they travel to their destination.");
private final JLabel eventFinishLabel = new JLabel("Finish (win or lose) tavern events");
private final JLabel eventWinLabel = new JLabel("Finish and win tavern events");
private final JLabel eventWinMatchLabel = new JLabel("Win individual matches in tavern events");
private final JLabel fetchLabel = new JLabel("Obtain the requested items (not tracked in inventory).");
private final JLabel findLabel = new JLabel("Locate the and enter a PoI.");
private final JLabel gatherLabel = new JLabel("Have the requested item in your inventory (tracked in inventory)");
private final JLabel giveLabel = new JLabel("Have the requested items removed from your inventory.");
private final JLabel haveReputationLabel = new JLabel("Have a minimum reputation in the selected PoI");
private final JLabel haveReputationInCurrentLocationLabel = new JLabel("Have a minimum reputation in the selected PoI (and be in it)");
private final JLabel huntLabel = new JLabel("Track down and defeat your target (on the overworld map).");
private final JLabel leaveLabel = new JLabel("Exit the current PoI and return to the overworld map.");
private final JLabel mapFlagLabel = new JLabel("Have a map flag set to a minimum value");
private final JLabel noneLabel = new JLabel("No visible objective. Use in coordination with hidden parallel objectives to track when to progress");
private final JLabel patrolLabel = new JLabel("Get close to generated coordinates before starting your next objective");
private final JLabel rescueLabel = new JLabel("Reach and rescue the target");
private final JLabel siegeLabel = new JLabel("Travel to the target location and defeat enemies attacking it");
private final JLabel questFlagLabel = new JLabel("Have a global quest flag set to a minimum value");
private final JLabel travelLabel = new JLabel("Travel to the given destination.");
private final JLabel useLabel = new JLabel("Use the indicated item from your inventory.");
private JTabbedPane poiPane = new JTabbedPane();
private final QuestTagSelector poiSelector = new QuestTagSelector("Destination Tags", false,true);
private final QuestTagSelector enemySelector = new QuestTagSelector("Enemy Tags", true,false);
private final JTextField poiTokenInput = new JTextField(25);
private final JLabel poiTokenLabel = new JLabel();
private final JLabel poiTokenDescription = new JLabel(
"At the bottom of many objectives involving a PoI, you will see a text field in the format of '$poi_#'." +
"Enter that tag here to ignore the PoI tag selector of this stage and instead use the same PoI that was selected " +
"for that stage as the target PoI for this one as well.");
private void hideAllControls(){
arenaLabel.setVisible(false);
clearLabel.setVisible(false);
deliveryLabel.setVisible(false);
defeatLabel.setVisible(false);
escortLabel.setVisible(false);
fetchLabel.setVisible(false);
findLabel.setVisible(false);
gatherLabel.setVisible(false);
giveLabel.setVisible(false);
haveReputationLabel.setVisible(false);
huntLabel.setVisible(false);
leaveLabel.setVisible(false);
noneLabel.setVisible(false);
patrolLabel.setVisible(false);
rescueLabel.setVisible(false);
siegeLabel.setVisible(false);
mapFlagLabel.setVisible(false);
questFlagLabel.setVisible(false);
travelLabel.setVisible(false);
useLabel.setVisible(false);
deliveryItem.setVisible(false);
mapFlagGroup.setVisible(false);
flagValueGroup.setVisible(false);
anyPOI.setVisible(false);
specificPOI.setVisible(false);
here.setVisible(false);
mixedEnemies.setVisible(false);
enemySelector.setVisible(false);
count1Description.setVisible(false);
count2Description.setVisible(false);
count3Description.setVisible(false);
count4Description.setVisible(false);
count1Spinner.setVisible(false);
count2Spinner.setVisible(false);
count3Spinner.setVisible(false);
count4Spinner.setVisible(false);
poiPane.setVisible(false);
poiTokenLabel.setVisible(false);
nyi.setVisible(false);
}
private void switchPanels(){
hideAllControls();
if (objectiveType.getSelectedItem() == null){
return;
}
switch(objectiveType.getSelectedItem().toString()){
case "Arena":
arenaLabel.setVisible(true);
poiPane.setVisible(true);
count3Description.setText("Arena tournaments to win (minimum 1)");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
count4Description.setText("Fail after tournaments not won (only applied if > 0)");
count4Description.setVisible(true);
count4Spinner.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "CharacterFlag":
characterFlagLabel.setVisible(true);
nyi.setVisible(true);
mapFlagGroup.setVisible(true);
flagValueGroup.setVisible(true);
break;
case "Clear":
clearLabel.setVisible(true);
poiPane.setVisible(true);
count1Description.setText("Target % of possible distances");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Plus or minus %");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "CompleteQuest":
completeQuestLabel.setVisible(true);
poiPane.setVisible(true);
count1Description.setText("Target % of possible distances");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Plus or minus %");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
count3Description.setText("Number of quests to complete (minimum 1)");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "Defeat":
defeatLabel.setVisible(true);
mixedEnemies.setVisible(true);
count3Description.setText("Matches to win");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
count4Description.setText("Fail after matches not won (only applied if > 0)");
count4Description.setVisible(true);
count4Spinner.setVisible(true);
enemySelector.setVisible(true);
break;
case "Delivery":
deliveryLabel.setVisible(true);
nyi.setVisible(true);
poiPane.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
deliveryItem.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "Escort":
escortLabel.setVisible(true);
nyi.setVisible(true);
poiPane.setVisible(true);
here.setVisible(true);
spriteNames.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "EventFinish":
eventFinishLabel.setVisible(true);
poiPane.setVisible(true);
count1Description.setText("Target % of possible distances");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Plus or minus %");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
count3Description.setText("Events to complete (minimum 1)");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "EventWin":
eventWinLabel.setVisible(true);
poiPane.setVisible(true);
count1Description.setText("Target % of possible distances");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Plus or minus %");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
count3Description.setText("Events to win (minimum 1)");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
count4Description.setText("Fail after events not won (only applied if > 0)");
count4Description.setVisible(true);
count4Spinner.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "EventWinMatch":
eventWinMatchLabel.setVisible(true);
poiPane.setVisible(true);
count1Description.setText("Target % of possible distances");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Plus or minus %");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
count3Description.setText("Event matches to win (minimum 1)");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
count4Description.setText("Fail after matches not won (only applied if > 0)");
count4Description.setVisible(true);
count4Spinner.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "Fetch":
fetchLabel.setVisible(true);
nyi.setVisible(true);
poiPane.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
deliveryItem.setVisible(true);
enemySelector.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "Find":
findLabel.setVisible(true);
nyi.setVisible(true);
poiPane.setVisible(true);
anyPOI.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "Gather":
gatherLabel.setVisible(true);
gatherLabel.setVisible(true);
nyi.setVisible(true);
itemNames.setVisible(true);
break;
case "Give":
giveLabel.setVisible(true);
nyi.setVisible(true);
itemNames.setVisible(true);
poiPane.setVisible(true);
poiTokenLabel.setVisible(true);
here.setVisible(true);
break;
case "HaveReputation":
poiPane.setVisible(true);
poiTokenLabel.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
count1Description.setText("Target % of possible distances");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Plus or minus %");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
count3Description.setText("Minimum reputation needed");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
break;
case "haveReputationInCurrentLocation":
haveReputationInCurrentLocationLabel.setVisible(true);
poiPane.setVisible(true);
poiTokenLabel.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
count1Description.setText("Target % of possible distances");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Plus or minus %");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
count3Description.setText("Minimum reputation needed");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
break;
case "Hunt":
huntLabel.setVisible(true);
enemySelector.setVisible(true);
count3Description.setText("Lifespan (seconds to complete hunt before despawn)");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
break;
case "Leave":
leaveLabel.setVisible(true);
poiPane.setVisible(true);
poiTokenLabel.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
count1Description.setText("Target % of possible distances");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Plus or minus %");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
count3Description.setText("Number of times to leave before triggering (minimum 1)");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
break;
case "MapFlag":
mapFlagLabel.setVisible(true);
poiPane.setVisible(true);
here.setVisible(true);
anyPOI.setVisible(true);
mapFlagGroup.setVisible(true);
flagValueGroup.setVisible(true);
break;
case "None":
noneLabel.setVisible(true);
nyi.setVisible(true);
break;
case "Patrol":
patrolLabel.setVisible(true);
nyi.setVisible(true);
break;
case "Rescue":
rescueLabel.setVisible(true);
nyi.setVisible(true);
poiPane.setVisible(true);
anyPOI.setVisible(true);
poiTokenLabel.setVisible(true);
here.setVisible(true);
spriteNames.setVisible(true);
enemySelector.setVisible(true);
break;
case "Siege":
siegeLabel.setVisible(true);
nyi.setVisible(true);
poiPane.setVisible(true);
poiTokenLabel.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
enemySelector.setVisible(true);
mixedEnemies.setVisible(true);
poiPane.setVisible(true);
count1Description.setText("Target % of possible distances");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Plus or minus %");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
count3Description.setText("Number of enemies to defeat");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
count3Spinner.setVisible(true);
count4Description.setText("Time limit (will only fail if > 0)");
count4Description.setVisible(true);
count4Spinner.setVisible(true);
break;
case "QuestFlag":
questFlagLabel.setVisible(true);
mapFlagGroup.setVisible(true);
flagValueGroup.setVisible(true);
break;
case "Travel":
travelLabel.setVisible(true);
poiPane.setVisible(true);
poiTokenLabel.setVisible(true);
poiTokenInput.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
count1Description.setText("Target % of possible distances");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Plus or minus %");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
count3Description.setText("Number of times to enter before triggering (minimum 1)");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
break;
case "Use":
useLabel.setVisible(true);
nyi.setVisible(true);
itemNames.setVisible(true);
poiPane.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
poiTokenLabel.setVisible(true);
here.setVisible(true);
count3Description.setText("Number of times to use triggering (minimum 1)");
count3Description.setVisible(true);
count3Spinner.setVisible(true);
break;
}
specificPOI.setVisible(anyPOI.isVisible());
}
private void changeObjective(){
if (objectiveType.getSelectedItem() != null)
currentData.objective = AdventureQuestController.ObjectiveTypes.valueOf(objectiveType.getSelectedItem().toString());
switchPanels();
}
private JPanel getObjectiveTab(){
objectiveType = new JComboBox<>(AdventureQuestController.ObjectiveTypes.values());
objectiveType.addActionListener( e -> changeObjective());
JPanel objectiveTab = new JPanel();
JScrollPane scrollPane = new JScrollPane();
objectiveTab.add(scrollPane);
FormPanel center=new FormPanel();
center.add(objectiveType);
scrollPane.add(center);
mapFlagGroup = new Box(BoxLayout.Y_AXIS);
mapFlagGroup.add(new JLabel("Map flag to check"));
mapFlagGroup.add(mapFlag);
flagValueGroup = new Box(BoxLayout.Y_AXIS);
flagValueGroup.add(new JLabel("Flag value to check"));
flagValueGroup.add(flagSpinner);
anyPOIGroup.add(anyPOI);
anyPOIGroup.add(specificPOI);
JPanel poiSelectorPane = new JPanel();
poiSelectorPane.setLayout(new BorderLayout());
poiSelectorPane.add(poiSelector, BorderLayout.CENTER);
JPanel poiTokenPanel = new JPanel();
JPanel tokenPanel = new JPanel();
tokenPanel.add(new JLabel("Token to use:"));
tokenPanel.add(poiTokenInput);
tokenPanel.setBorder(new EmptyBorder(10, 10, 30, 10));
poiTokenPanel.add(poiTokenDescription);
poiTokenPanel.add(tokenPanel);
poiTokenPanel.add(here);
GroupLayout poiTokenLayout = new GroupLayout(poiTokenPanel);
poiTokenLayout.setHorizontalGroup(
poiTokenLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(poiTokenDescription)
.addComponent(tokenPanel,GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addComponent(here));
poiTokenLayout.setVerticalGroup(
poiTokenLayout.createSequentialGroup()
.addComponent(poiTokenDescription)
.addComponent(tokenPanel,GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addComponent(here));
poiTokenPanel.setLayout(poiTokenLayout);
poiPane.add("Specific PoI", poiTokenPanel);
poiPane.add("Tag Selector", poiSelectorPane);
poiPane.setPreferredSize(new Dimension(0,200));
center.add(arenaLabel);
center.add(clearLabel);
center.add(defeatLabel);
center.add(deliveryLabel);
center.add(escortLabel);
center.add(fetchLabel);
center.add(findLabel);
center.add(gatherLabel);
center.add(giveLabel);
center.add(haveReputationLabel);
center.add(huntLabel);
center.add(leaveLabel);
center.add(noneLabel);
center.add(patrolLabel);
center.add(rescueLabel);
center.add(siegeLabel);
center.add(mapFlagLabel);
center.add(questFlagLabel);
center.add(travelLabel);
center.add(useLabel);
center.add(nyi);
center.add(deliveryItem);
center.add(mapFlagGroup);
center.add(flagValueGroup);
center.add(anyPOI);
center.add(specificPOI);
center.add(mixedEnemies);
center.add(enemySelector);
center.add(count1Description);
center.add(count1Spinner);
center.add(count2Description);
center.add(count2Spinner);
center.add(count3Description);
center.add(count3Spinner);
center.add(count4Description);
center.add(count4Spinner);
center.add(poiPane);
center.add(poiTokenLabel);
switchPanels();
poiSelector.selectedItems.addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent e) {
rebuildPOIList();
rebuildEnemyList();
}
@Override
public void intervalRemoved(ListDataEvent e) {
rebuildPOIList();
rebuildEnemyList();
}
@Override
public void contentsChanged(ListDataEvent e) {
rebuildPOIList();
rebuildEnemyList();
}
});
return center;
}
private void rebuildPOIList(){
List<String> currentList = new ArrayList<>();
for(int i = 0; i< poiSelector.selectedItems.getSize(); i++){
currentList.add(poiSelector.selectedItems.getElementAt(i));
}
currentData.POITags = currentList;
}
private void rebuildEnemyList(){
List<String> currentList = new ArrayList<>();
for(int i = 0; i< enemySelector.selectedItems.getSize(); i++){
currentList.add(enemySelector.selectedItems.getElementAt(i));
}
currentData.enemyTags = currentList;
}
private JPanel getPrereqTab(){
JPanel prereqTab = new JPanel();
prereqTab.add(new JLabel("Insert Prereq data here"));
return prereqTab;
}
private void refresh() {
if(currentData==null)
{
return;
}
setEnabled(false);
updating=true;
objectiveType.setSelectedItem(currentData.objective);
if (objectiveType.getSelectedItem() != null)
currentData.objective = AdventureQuestController.ObjectiveTypes.valueOf(objectiveType.getSelectedItem().toString()); //Ensuring this gets initialized on new
name.setText(currentData.name);
description.setText(currentData.description);
deliveryItem.setText(currentData.deliveryItem);
if (currentData.enemyTags != null){
DefaultListModel<String> selectedEnemies = new DefaultListModel<>();
for (int i = 0; i < currentData.enemyTags.size(); i++) {
selectedEnemies.add(i, currentData.enemyTags.get(i));
}
enemySelector.load(selectedEnemies);
}
if (currentData.POITags != null){
DefaultListModel<String> selectedPOI = new DefaultListModel<>();
for (int i = 0; i < currentData.POITags.size(); i++) {
selectedPOI.add(i, currentData.POITags.get(i));
}
poiSelector.load(selectedPOI);
}
itemNames.setText(currentData.itemNames);
equipNames.setText(currentData.equipNames);
prologueEditor.loadData(currentData.prologue);
epilogueEditor.loadData(currentData.epilogue);
if (currentData.POITags != null){
DefaultListModel<String> selectedPOI = new DefaultListModel<>();
for (int i = 0; i < currentData.POITags.size(); i++) {
selectedPOI.add(i, currentData.POITags.get(i));
}
poiSelector.load(selectedPOI);
}
here.getModel().setSelected(currentData.here);
anyPOI.getModel().setSelected(currentData.anyPOI);
specificPOI.getModel().setSelected(!currentData.anyPOI);
poiTokenInput.setText(currentData.POIToken);
poiTokenLabel.setText( "To reference this point of interest: $(poi_" + currentData.id + ")");
ArrayList<String> temp = new ArrayList<>();
for (AdventureQuestStage stage : currentQuestData.stages){
if (stage.equals(currentData))
continue;
temp.add(stage.name);
}
prerequisites.setOptions(temp);
count1Spinner.getModel().setValue(currentData.count1);
count2Spinner.getModel().setValue(currentData.count2);
count3Spinner.getModel().setValue(currentData.count3);
count4Spinner.getModel().setValue(currentData.count4);
updating=false;
setEnabled(true);
}
public void updateStage()
{
if(currentData==null||updating)
return;
currentData.name=name.getText();
currentData.description= description.getText();
currentData.prologue = prologueEditor.getDialogData();
currentData.epilogue = epilogueEditor.getDialogData();
currentData.deliveryItem = deliveryItem.getText();
currentData.itemNames = itemNames.getList()==null?new ArrayList<>():Arrays.asList(itemNames.getList());
currentData.equipNames = equipNames.getList()==null?new ArrayList<>():Arrays.asList(equipNames.getList());
currentData.anyPOI = anyPOI.getModel().isSelected();
currentData.mapFlag = mapFlag.getText();
currentData.mapFlagValue = Integer.parseInt(flagSpinner.getModel().getValue().toString());
currentData.count1 = Integer.parseInt(count1Spinner.getModel().getValue().toString());
currentData.count2 = Integer.parseInt(count2Spinner.getModel().getValue().toString());
currentData.count3 = Integer.parseInt(count3Spinner.getModel().getValue().toString());
currentData.count4 = Integer.parseInt(count4Spinner.getModel().getValue().toString());
currentData.mixedEnemies = mixedEnemies.getModel().isSelected();
currentData.here = here.getModel().isSelected();
currentData.POIToken = poiTokenInput.getText();
rebuildPOIList();
rebuildEnemyList();
emitChanged();
}
public void setCurrentStage(AdventureQuestStage stageData, AdventureQuestData data) {
if (stageData == null)
stageData = new AdventureQuestStage();
if (data == null)
data = new AdventureQuestData();
currentData =stageData;
currentQuestData=data;
setVisible(true);
refresh();
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
protected void emitChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
private void addListeners(){
deliveryItem.getDocument().addDocumentListener(new DocumentChangeListener(QuestStageEdit.this::updateStage));
mapFlag.getDocument().addDocumentListener(new DocumentChangeListener(QuestStageEdit.this::updateStage));
flagSpinner.getModel().addChangeListener(q -> QuestStageEdit.this.updateStage());
count1Spinner.getModel().addChangeListener(q -> QuestStageEdit.this.updateStage());
count2Spinner.getModel().addChangeListener(q -> QuestStageEdit.this.updateStage());
count3Spinner.getModel().addChangeListener(q -> QuestStageEdit.this.updateStage());
count4Spinner.getModel().addChangeListener(q -> QuestStageEdit.this.updateStage());
mixedEnemies.getModel().addChangeListener(q -> QuestStageEdit.this.updateStage());
here.getModel().addChangeListener(q -> QuestStageEdit.this.updateStage());
anyPOI.getModel().addChangeListener(q -> QuestStageEdit.this.updateStage());
deliveryItem.getDocument().addDocumentListener(new DocumentChangeListener(QuestStageEdit.this::updateStage));
mapFlag.getDocument().addDocumentListener(new DocumentChangeListener(QuestStageEdit.this::updateStage));
prologueEditor.addChangeListener(q -> QuestStageEdit.this.updateStage());
epilogueEditor.addChangeListener(q -> QuestStageEdit.this.updateStage());
}
}

View File

@@ -1,138 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.AdventureQuestData;
import forge.adventure.data.AdventureQuestStage;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionListener;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class QuestStageEditor extends JComponent{
DefaultListModel<AdventureQuestStage> model = new DefaultListModel<>();
JList<AdventureQuestStage> list = new JList<>(model);
JScrollPane scroll;
JToolBar toolBar = new JToolBar("toolbar");
QuestStageEdit edit=new QuestStageEdit();
AdventureQuestData currentData;
public class QuestStageRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof AdventureQuestStage stageData))
return label;
label.setText(stageData.name);
//label.setIcon(new ImageIcon(Config.instance().getFilePath(stageData.sourcePath))); //Type icon eventually?
return label;
}
}
public void addButton(String name, ActionListener action)
{
JButton newButton=new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public QuestStageEditor()
{
list.setCellRenderer(new QuestStageRenderer());
list.addListSelectionListener(e -> QuestStageEditor.this.updateEdit());
addButton("Add Quest Stage", e -> QuestStageEditor.this.addStage());
addButton("Remove Selected", e -> QuestStageEditor.this.remove());
toolBar.setFloatable(false);
setLayout(new BorderLayout());
scroll = new JScrollPane(list);
add(scroll, BorderLayout.WEST);
JPanel editPanel = new JPanel();
editPanel.setLayout(new BorderLayout());
add(toolBar, BorderLayout.NORTH);
editPanel.add(edit,BorderLayout.CENTER);
add(editPanel);
edit.addChangeListener(e -> emitChanged());
}
protected void emitChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
private void updateEdit() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
edit.setCurrentStage(model.get(selected),currentData);
}
void addStage()
{
AdventureQuestStage data=new AdventureQuestStage();
data.name = "New Stage";
model.add(model.size(),data);
edit.setVisible(true);
scroll.setVisible(true);
int id = 0;
for (int i = 0; i < model.size(); i++)
{
if (model.get(i).id >= id)
id = model.get(i).id +1;
}
data.id = id;
if (model.size() == 1){
list.setSelectedIndex(0);
}
emitChanged();
}
void remove()
{
int selected=list.getSelectedIndex();
if(selected<0)
return;
model.remove(selected);
edit.setVisible(false);
scroll.setVisible(list.getModel().getSize() > 0);
emitChanged();
}
public void setStages(AdventureQuestData data) {
currentData=data;
model.clear();
if(data==null||data.stages==null || data.stages.length == 0)
{
edit.setVisible(false);
return;
}
for (int i=0;i<data.stages.length;i++) {
model.add(i,data.stages[i]);
}
if (model.size() > 0) {
list.setSelectedIndex(0);
}
}
public AdventureQuestStage[] getStages() {
AdventureQuestStage[] stages= new AdventureQuestStage[model.getSize()];
for(int i=0;i<model.getSize();i++)
{
stages[i]=model.get(i);
}
return stages;
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
}

View File

@@ -1,107 +0,0 @@
package forge.adventure.editor;
import javax.swing.*;
import java.awt.*;
public class QuestTagSelector extends JComponent {
DefaultListModel<String> allItems = new DefaultListModel<>();
DefaultListModel<String> selectedItems = new DefaultListModel<>();
JList<String> unselectedList;
JList<String> selectedList;
boolean useEnemyTags = false;
boolean usePOITags = false;
public QuestTagSelector(String title, boolean useEnemyTags, boolean usePOITags)
{
if (useEnemyTags){
this.useEnemyTags = true;
} else if (usePOITags) {
this.usePOITags = true;
}
else{
return;
}
unselectedList = new JList<>(allItems);
selectedList = new JList<>(selectedItems);
// unselectedList.setCellRenderer(new PointOfInterestEditor.PointOfInterestRenderer()); // Replace with use count of tag?
// selectedList.setCellRenderer(new PointOfInterestEditor.PointOfInterestRenderer());
JButton addButton=new JButton("add");
JButton removeButton=new JButton("remove");
addButton.addActionListener( e -> QuestTagSelector.this.addTag());
removeButton.addActionListener( e -> QuestTagSelector.this.removeTag());
BorderLayout layout=new BorderLayout();
setLayout(layout);
if (title.length() > 0)
add(new JLabel(title),BorderLayout.PAGE_START);
add(new JScrollPane(unselectedList), BorderLayout.LINE_START);
add(new JScrollPane(selectedList), BorderLayout.LINE_END);
JPanel buttonPanel = new JPanel();
GridLayout buttonLayout = new GridLayout(2,0);
buttonPanel.setLayout(buttonLayout);
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
add(buttonPanel);
}
public void addTag(){
if (unselectedList.isSelectionEmpty()){
return;
}
for (String toAdd : unselectedList.getSelectedValuesList())
{
if (selectedItems.contains(toAdd)) continue;
selectedItems.addElement(toAdd);
}
refresh();
}
public void removeTag(){
if (selectedList.isSelectionEmpty()){
return;
}
for (String toRemove : selectedList.getSelectedValuesList())
{
selectedItems.removeElement(toRemove);
}
refresh();
}
public void load(DefaultListModel<String> selectedNames)
{
allItems.clear();
selectedItems.clear();
if (useEnemyTags){
allItems = QuestController.getInstance().getEnemyTags();
}
else if (usePOITags) {
allItems = QuestController.getInstance().getPOITags();
}
unselectedList.setModel(allItems);
for (int i=0;i<allItems.size();i++){
if (selectedNames.contains(allItems.get(i))){
selectedItems.addElement(allItems.get(i));
}
}
}
private boolean updating=false;
private void refresh() {
setEnabled(allItems!=null);
if(allItems==null)
{
return;
}
updating=true;
//unselectedList = new JList<>(allItems);
//selectedList = new JList<>(selectedItems);
updating=false;
}
}

View File

@@ -1,144 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.RewardData;
import forge.card.CardType;
import forge.game.keyword.Keyword;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.util.Arrays;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class RewardEdit extends FormPanel {
RewardData currentData;
JComboBox typeField =new JComboBox(new String[] { "card", "gold", "life", "deckCard", "item","shards"});
JSpinner probability = new JSpinner(new SpinnerNumberModel(0f, 0, 1, 0.1f));
JSpinner count = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
JSpinner addMaxCount = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
JTextField cardName =new JTextField();
JTextField itemName =new JTextField();
TextListEdit editions =new TextListEdit();
TextListEdit colors =new TextListEdit(new String[] { "White", "Blue", "Black", "Red", "Green" });
TextListEdit rarity =new TextListEdit(new String[] { "Basic Land", "Common", "Uncommon", "Rare", "Mythic Rare" });
TextListEdit subTypes =new TextListEdit();
TextListEdit cardTypes =new TextListEdit(Arrays.stream(CardType.CoreType.values()).map(CardType.CoreType::toString).toArray(String[]::new));
TextListEdit superTypes =new TextListEdit(Arrays.stream(CardType.Supertype.values()).map(CardType.Supertype::toString).toArray(String[]::new));
TextListEdit manaCosts =new TextListEdit();
TextListEdit keyWords =new TextListEdit(Arrays.stream(Keyword.values()).map(Keyword::toString).toArray(String[]::new));
JComboBox colorType =new JComboBox(new String[] { "Any", "Colorless", "MultiColor", "MonoColor"});
JTextField cardText =new JTextField();
private boolean updating=false;
public RewardEdit()
{
add("Type:",typeField);
add("probability:",probability);
add("count:",count);
add("addMaxCount:",addMaxCount);
add("cardName:",cardName);
add("itemName:",itemName);
add("editions:",editions);
add("colors:",colors);
add("rarity:",rarity);
add("subTypes:",subTypes);
add("cardTypes:",cardTypes);
add("superTypes:",superTypes);
add("manaCosts:",manaCosts);
add("keyWords:",keyWords);
add("colorType:",colorType);
add("cardText:",cardText);
typeField.addActionListener((e -> RewardEdit.this.updateReward()));
probability.addChangeListener(e -> RewardEdit.this.updateReward());
count.addChangeListener(e -> RewardEdit.this.updateReward());
addMaxCount.addChangeListener(e -> RewardEdit.this.updateReward());
cardName.getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
itemName.getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
editions.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
colors.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
rarity.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
subTypes.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
cardTypes.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
superTypes.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
manaCosts.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
keyWords.getEdit().getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
colorType.addActionListener((e -> RewardEdit.this.updateReward()));
cardText.getDocument().addDocumentListener(new DocumentChangeListener(RewardEdit.this::updateReward));
}
private void updateReward() {
if(currentData==null||updating)
return;
currentData.type=typeField.getSelectedItem()==null?null:typeField.getSelectedItem().toString();
currentData.probability=((Double)probability.getValue()).floatValue();
currentData.count= (int) count.getValue();
currentData.addMaxCount= (int) addMaxCount.getValue();
currentData.cardName = cardName.getText().isEmpty()?null:cardName.getText();
currentData.itemNames = itemName.getText().isEmpty()?null:itemName.getText().split(",");
currentData.editions = editions.getList();
currentData.colors = colors.getList();
currentData.rarity = rarity.getList();
currentData.subTypes = subTypes.getList();
currentData.cardTypes = cardTypes.getList();
currentData.superTypes = superTypes.getList();
currentData.manaCosts = manaCosts.getListAsInt();
currentData.keyWords = keyWords.getList();
currentData.colorType=colorType.getSelectedItem()==null?null:colorType.getSelectedItem().toString();
currentData.cardText = cardText.getText().isEmpty()?null:cardText.getText();
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
public void setCurrentReward(RewardData data)
{
currentData=data;
refresh();
}
private void refresh() {
setEnabled(currentData!=null);
if(currentData==null)
{
return;
}
updating=true;
typeField.setSelectedItem(currentData.type);
probability.setValue((double) currentData.probability);
count.setValue(currentData.count);
addMaxCount.setValue(currentData.addMaxCount);
cardName.setText(currentData.cardName);
itemName.setText(currentData.itemName);
editions.setText(currentData.editions);
colors.setText(currentData.colors);
rarity.setText(currentData.rarity);
subTypes.setText(currentData.subTypes);
cardTypes.setText(currentData.cardTypes);
superTypes.setText(currentData.superTypes);
manaCosts.setText(currentData.manaCosts);
keyWords.setText(currentData.keyWords);
colorType.setSelectedItem(currentData.colorType);
cardText.setText(currentData.cardText);
updating=false;
}
}

View File

@@ -1,140 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.RewardData;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionListener;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class RewardsEditor extends JComponent{
DefaultListModel<RewardData> model = new DefaultListModel<>();
JList<RewardData> list = new JList<>(model);
JToolBar toolBar = new JToolBar("toolbar");
RewardEdit edit=new RewardEdit();
boolean updating;
public class RewardDataRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof RewardData))
return label;
RewardData reward=(RewardData) value;
StringBuilder builder=new StringBuilder();
if(reward.type==null||reward.type.isEmpty())
builder.append("Reward");
else
builder.append(reward.type);
builder.append(" ");
builder.append(reward.count);
if(reward.addMaxCount>0)
{
builder.append("-");
builder.append(reward.count+reward.addMaxCount);
}
label.setText(builder.toString());
return label;
}
}
public void addButton(String name, ActionListener action)
{
JButton newButton=new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public RewardsEditor()
{
list.setCellRenderer(new RewardDataRenderer());
list.addListSelectionListener(e -> RewardsEditor.this.updateEdit());
addButton("add", e -> RewardsEditor.this.addReward());
addButton("remove", e -> RewardsEditor.this.remove());
addButton("copy", e -> RewardsEditor.this.copy());
BorderLayout layout=new BorderLayout();
setLayout(layout);
add(list, BorderLayout.LINE_START);
add(toolBar, BorderLayout.PAGE_START);
add(edit,BorderLayout.CENTER);
edit.addChangeListener(e -> emitChanged());
}
protected void emitChanged() {
if (updating)
return;
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
private void copy() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
RewardData data=new RewardData(model.get(selected));
model.add(model.size(),data);
}
private void updateEdit() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
edit.setCurrentReward(model.get(selected));
}
void addReward()
{
RewardData data=new RewardData();
model.add(model.size(),data);
}
void remove()
{
int selected=list.getSelectedIndex();
if(selected<0)
return;
model.remove(selected);
}
public void setRewards(RewardData[] rewards) {
model.clear();
if(rewards==null)
return;
for (int i=0;i<rewards.length;i++) {
model.add(i,rewards[i]);
}
}
public RewardData[] getRewards() {
RewardData[] rewards= new RewardData[model.getSize()];
for(int i=0;i<model.getSize();i++)
{
rewards[i]=model.get(i);
}
return rewards;
}
public void clear(){
updating = true;
model.clear();
updating = false;
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
}

View File

@@ -1,217 +0,0 @@
package forge.adventure.editor;
import com.badlogic.gdx.graphics.Color;
import forge.adventure.data.BiomeData;
import forge.adventure.data.BiomeStructureData;
import forge.adventure.util.Config;
import forge.adventure.world.BiomeStructure;
import forge.adventure.world.ColorMap;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class StructureEditor extends JComponent{
DefaultListModel<BiomeStructureData> model = new DefaultListModel<>();
JList<BiomeStructureData> list = new JList<>(model);
JToolBar toolBar = new JToolBar("toolbar");
BiomeStructureEdit edit=new BiomeStructureEdit();
BiomeData currentData;
public class StructureDataRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof BiomeStructureData))
return label;
BiomeStructureData structureData=(BiomeStructureData) value;
label.setText("Structure");
label.setIcon(new ImageIcon(Config.instance().getFilePath(structureData.sourcePath)));
return label;
}
}
public void addButton(String name, ActionListener action)
{
JButton newButton=new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public StructureEditor()
{
list.setCellRenderer(new StructureDataRenderer());
list.addListSelectionListener(e -> StructureEditor.this.updateEdit());
addButton("add", e -> StructureEditor.this.addStructure());
addButton("remove", e -> StructureEditor.this.remove());
addButton("copy", e -> StructureEditor.this.copy());
addButton("test", e -> StructureEditor.this.test());
BorderLayout layout=new BorderLayout();
setLayout(layout);
add(list, BorderLayout.WEST);
add(toolBar, BorderLayout.NORTH);
add(edit,BorderLayout.CENTER);
edit.addChangeListener(e -> emitChanged());
}
protected void emitChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
private void test() {
if (list.isSelectionEmpty())
return;
long start = System.currentTimeMillis();
BiomeStructureData data = model.get(list.getSelectedIndex());
try
{
BiomeStructure struct = new BiomeStructure(data, System.currentTimeMillis(),
(int) (currentData.width * EditorMainWindow.worldEditor.width.intValue() ),
(int) (currentData.width * EditorMainWindow.worldEditor.height.intValue()));
BufferedImage sourceImage= null;
try {
sourceImage = ImageIO.read(new File(struct.sourceImagePath()));
ColorMap sourceColorMap=new ColorMap(sourceImage.getWidth(),sourceImage.getHeight());
for(int y=0;y<sourceColorMap.getHeight();y++)
for(int x=0;x<sourceColorMap.getWidth();x++)
{
Color c =new Color();
Color.argb8888ToColor(c,sourceImage.getRGB(x,y));
sourceColorMap.setColor(x,y,c);
}
BufferedImage maskImage= ImageIO.read(new File(struct.maskImagePath()));
ColorMap maskColorMap=new ColorMap(maskImage.getWidth(),maskImage.getHeight());
for(int y=0;y<maskColorMap.getHeight();y++)
for(int x=0;x<maskColorMap.getWidth();x++)
{
Color c =new Color();
Color.argb8888ToColor(c,maskImage.getRGB(x,y));
maskColorMap.setColor(x,y,c);
}
struct.initialize(sourceColorMap,maskColorMap);
} catch (IOException e) {
throw new RuntimeException(e);
}
float calcTime=(System.currentTimeMillis() - start)/1000f;
JLabel label = new JLabel();
ColorMap colorMap=struct.image;
BufferedImage image = new BufferedImage(colorMap.getWidth(),colorMap.getHeight(),BufferedImage.TYPE_INT_ARGB);
for(int y=0;y<colorMap.getHeight();y++)
for(int x=0;x<colorMap.getWidth();x++)
image.setRGB(x,y,Color.argb8888(colorMap.getColor(x,y)));
if (image.getWidth() < 640 | image.getHeight() < 640) {
if (image.getHeight() > image.getWidth()) {
BufferedImage nimage = new BufferedImage(640, 640 * (image.getWidth() / image.getHeight()), BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(640 / image.getHeight(), 640 / image.getHeight());
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
image = scaleOp.filter(image, nimage);
} else {
BufferedImage nimage = new BufferedImage(640 * (image.getHeight() / image.getWidth()), 640, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(640 / image.getWidth(), 640 / image.getWidth());
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
image = scaleOp.filter(image, nimage);
}
}
label.setIcon(new ImageIcon(image));
label.setSize(640, 640);
JOptionPane.showMessageDialog(this, label,"Calculating took "+ calcTime+" seconds",JOptionPane.PLAIN_MESSAGE);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(this, "WaveFunctionCollapse was not successful","can not calculate function "+e.getMessage(),JOptionPane.ERROR_MESSAGE);
}
}
private void copy() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
BiomeStructureData data=new BiomeStructureData(model.get(selected));
model.add(model.size(),data);
}
private void updateEdit() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
edit.setCurrentStructure(model.get(selected),currentData);
}
void addStructure()
{
BiomeStructureData data=new BiomeStructureData();
model.add(model.size(),data);
}
void remove()
{
int selected=list.getSelectedIndex();
if(selected<0)
return;
model.remove(selected);
}
public void setStructures(BiomeData data) {
currentData=data;
model.clear();
if(data==null||data.structures==null)
{
edit.setCurrentStructure(null,null);
return;
}
for (int i=0;i<data.structures.length;i++) {
model.add(i,data.structures[i]);
}
list.setSelectedIndex(0);
}
public BiomeStructureData[] getBiomeStructureData() {
BiomeStructureData[] rewards= new BiomeStructureData[model.getSize()];
for(int i=0;i<model.getSize();i++)
{
rewards[i]=model.get(i);
}
return rewards;
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
}

View File

@@ -1,92 +0,0 @@
package forge.adventure.editor;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.utils.Array;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import static java.awt.Image.SCALE_FAST;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class SwingAtlas {
int imageSize=32;
HashMap<String, ArrayList<ImageIcon>> images=new HashMap<>();
public HashMap<String, ArrayList<ImageIcon>> getImages()
{
return images;
}
public SwingAtlas(FileHandle path,int imageSize)
{
this.imageSize=imageSize;
if(!path.exists()||!path.toString().endsWith(".atlas"))
return;
TextureAtlas.TextureAtlasData data=new TextureAtlas.TextureAtlasData(path,path.parent(),false);
for(TextureAtlas.TextureAtlasData.Region region: new Array.ArrayIterator<>(data.getRegions()))
{
String name=region.name;
if(!images.containsKey(name))
{
images.put(name,new ArrayList<>());
}
ArrayList<ImageIcon> imageList=images.get(name);
try
{
imageList.add(spriteToImage(region));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public SwingAtlas(FileHandle path)
{
this(path,32);
}
private ImageIcon spriteToImage(TextureAtlas.TextureAtlasData.Region sprite) throws IOException {
try
{
BufferedImage img = ImageIO.read(sprite.page.textureFile.file());
if(sprite.width== sprite.height)
return new ImageIcon(img.getSubimage(sprite.left,sprite.top, sprite.width, sprite.height).getScaledInstance(imageSize,imageSize,SCALE_FAST));
if(sprite.width>sprite.height)
return new ImageIcon(img.getSubimage(sprite.left,sprite.top, sprite.width, sprite.height).getScaledInstance(imageSize, (int) (imageSize*(sprite.height/(float)sprite.width)),SCALE_FAST));
return new ImageIcon(img.getSubimage(sprite.left,sprite.top, sprite.width, sprite.height).getScaledInstance((int) (imageSize*(sprite.width/(float)sprite.height)),imageSize,SCALE_FAST));
}
catch (Exception e)
{
return null;
}
}
public ImageIcon get(String name) {
if(images.get(name).size()==0)
return null;
return images.get(name).get(0);
}
public boolean has(String name) {
return images.containsKey(name);
}
public ImageIcon getAny() {
if(images.isEmpty())
return null;
ArrayList<ImageIcon> imageList= images.get(images.keySet().iterator().next());
if(imageList.isEmpty())
return null;
return imageList.get(0);
}
}

View File

@@ -1,94 +0,0 @@
package forge.adventure.editor;
import forge.adventure.util.Config;
import org.apache.commons.lang3.tuple.Pair;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class SwingAtlasPreview extends Box {
int imageSize=32;
private String sprite="";
private String spriteName="";
Timer timer;
public SwingAtlasPreview()
{
this(64,200);
}
public SwingAtlasPreview(int imageSize,int timeDelay) {
super(BoxLayout.Y_AXIS);
timer = new Timer(timeDelay, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
counter++;
for (Pair<JLabel, ArrayList<ImageIcon>> element : labels) {
element.getKey().setIcon(element.getValue().get(counter % element.getValue().size()));
}
}
});
this.imageSize=imageSize;
}
static Map<String,Map<Integer,SwingAtlas>> cache=new HashMap<>();
public SwingAtlasPreview(int size) {
this();
imageSize=size;
}
int counter=0;
List<Pair<JLabel,ArrayList<ImageIcon>>> labels=new ArrayList<>();
public void setSpritePath(String sprite) {
setSpritePath(sprite,null);
}
public void setSpritePath(String sprite,String name) {
if(this.sprite==null||sprite==null||(this.sprite.equals(sprite)&&(spriteName != null && spriteName.equals(name))))
return;
removeAll();
counter=0;
labels.clear();
this.sprite=sprite;
this.spriteName=name;
SwingAtlas atlas;
if(!cache.containsKey(sprite))
{
cache.put(sprite,new HashMap<>() );
}
if(!cache.get(sprite).containsKey(imageSize))
{
cache.get(sprite).put(imageSize,new SwingAtlas(Config.instance().getFile(sprite),imageSize) );
}
atlas=cache.get(sprite).get(imageSize);
int maxCount=0;
for(Map.Entry<String, ArrayList<ImageIcon>> element:atlas.getImages().entrySet())
{
if(name==null||element.getKey().equals(name))
{
JLabel image=new JLabel(element.getValue().get(0));
if(maxCount<element.getValue().size())
maxCount=element.getValue().size();
add(new JLabel(element.getKey()));
add(image);
labels.add(Pair.of(image, element.getValue()));
}
}
if(maxCount<=1)
{
timer.stop();
}
else
{
timer.restart();
}
// doLayout(); //These lines cause images to bleed on to other tabs and don't appear to be needed
// revalidate();
// update(getGraphics());
// repaint();
}
}

View File

@@ -1,134 +0,0 @@
package forge.adventure.editor;
import forge.adventure.data.BiomeData;
import forge.adventure.data.BiomeTerrainData;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionListener;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class TerrainsEditor extends JComponent{
DefaultListModel<BiomeTerrainData> model = new DefaultListModel<>();
JList<BiomeTerrainData> list = new JList<>(model);
JToolBar toolBar = new JToolBar("toolbar");
BiomeTerrainEdit edit=new BiomeTerrainEdit();
BiomeData currentData;
public class TerrainDataRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof BiomeTerrainData))
return label;
BiomeTerrainData terrainData=(BiomeTerrainData) value;
/*StringBuilder builder=new StringBuilder();
builder.append("Terrain");
builder.append(" ");
builder.append(terrainData.spriteName);*/
label.setText("Terrain " + terrainData.spriteName);
return label;
}
}
public void addButton(String name, ActionListener action)
{
JButton newButton=new JButton(name);
newButton.addActionListener(action);
toolBar.add(newButton);
}
public TerrainsEditor()
{
list.setCellRenderer(new TerrainDataRenderer());
list.addListSelectionListener(e -> TerrainsEditor.this.updateEdit());
addButton("add", e -> TerrainsEditor.this.addTerrain());
addButton("remove", e -> TerrainsEditor.this.remove());
addButton("copy", e -> TerrainsEditor.this.copy());
BorderLayout layout=new BorderLayout();
setLayout(layout);
add(list, BorderLayout.LINE_START);
add(toolBar, BorderLayout.PAGE_START);
add(edit,BorderLayout.CENTER);
edit.addChangeListener(e -> emitChanged());
}
protected void emitChanged() {
ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
if (listeners != null && listeners.length > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
private void copy() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
BiomeTerrainData data=new BiomeTerrainData(model.get(selected));
model.add(model.size(),data);
}
private void updateEdit() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
edit.setCurrentTerrain(model.get(selected),currentData);
}
void addTerrain()
{
BiomeTerrainData data=new BiomeTerrainData();
model.add(model.size(),data);
}
void remove()
{
int selected=list.getSelectedIndex();
if(selected<0)
return;
model.remove(selected);
}
public void setTerrains(BiomeData data) {
currentData=data;
model.clear();
if(data==null||data.terrain==null)
return;
for (int i=0;i<data.terrain.length;i++) {
model.add(i,data.terrain[i]);
}
list.setSelectedIndex(0);
}
public BiomeTerrainData[] getBiomeTerrainData() {
BiomeTerrainData[] rewards= new BiomeTerrainData[model.getSize()];
for(int i=0;i<model.getSize();i++)
{
rewards[i]=model.get(i);
}
return rewards;
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
}

View File

@@ -1,118 +0,0 @@
package forge.adventure.editor;
import javax.swing.*;
import java.awt.*;
import java.util.List;
/**
* Editor class to edit configuration, maybe moved or removed
*/
public class TextListEdit extends Box {
JTextField edit=new JTextField();
JButton findButton=new JButton(UIManager.getIcon("add"));
JComboBox elements;
public TextListEdit(String[] possibleElements) {
super(BoxLayout.X_AXIS);
findButton.addActionListener(e -> TextListEdit.this.find());
add(edit);
edit.setPreferredSize(new Dimension(400,edit.getPreferredSize().height));
add(findButton);
elements= new JComboBox(possibleElements);
add(elements);
}
public TextListEdit()
{
this(new String[0]);
}
JTextField getEdit()
{
return edit;
}
private void find() {
edit.setText((edit.getText().trim().length()>0?edit.getText() + ";": "")+elements.getSelectedItem().toString());
elements.remove(elements.getSelectedIndex());
elements.setSelectedIndex(0);
// JFileChooser fc = new JFileChooser();
// fc.setCurrentDirectory(new File(Config.instance().getFilePath("")));
// fc.setMultiSelectionEnabled(false);
// if (fc.showOpenDialog(this) ==
// JFileChooser.APPROVE_OPTION) {
// File selected = fc.getSelectedFile();
//
// try {
// if (selected != null&&selected.getCanonicalPath().startsWith(new File(Config.instance().getFilePath("")).getCanonicalPath())) {
// edit.setText(selected.getCanonicalPath().substring(new File(Config.instance().getFilePath("")).getCanonicalPath().length()+1));
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
}
public void setOptions(List<String> itemNames) {
if(itemNames==null)
elements.removeAllItems();
else {
for(String item: itemNames)
elements.addItem(item);
}
}
public void setText(List<String> itemNames) {
if(itemNames==null)
edit.setText("");
else
edit.setText(String.join(";",itemNames));
}
public void setText(String[] itemName) {
if(itemName==null)
edit.setText("");
else
edit.setText(String.join(";",itemName));
}
public void setText(int[] intValues) {
if(intValues==null)
{
edit.setText("");
return;
}
StringBuilder values= new StringBuilder();
for(int i=0;i<intValues.length;i++)
{
values.append(intValues[i]);
if(intValues.length>i+2)
values.append("\n");
}
edit.setText(values.toString());
}
public String[] getList() {
return edit.getText().isEmpty()?null:edit.getText().split(";");
}
public int[] getListAsInt() {
if(edit.getText().isEmpty())
return null;
String[] stringList=getList();
int[] retList=new int[stringList.length];
for(int i=0;i<retList.length;i++)
{
String intName=stringList[i];
try
{
retList[i] = Integer.parseInt(intName);
}
catch (NumberFormatException e)
{
retList[i] =0;
}
}
return retList;
}
}

View File

@@ -1,227 +0,0 @@
package forge.adventure.editor;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonWriter;
import forge.adventure.data.BiomeData;
import forge.adventure.data.WorldData;
import forge.adventure.util.Config;
import forge.adventure.util.Paths;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class WorldEditor extends JComponent {
WorldData currentData;
IntSpinner width= new IntSpinner( 0, 100000, 1);
IntSpinner height= new IntSpinner( 0, 100000, 1);
FloatSpinner playerStartPosX= new FloatSpinner( 0, 1, .1f);
FloatSpinner playerStartPosY= new FloatSpinner(0, 1, .1f);
FloatSpinner noiseZoomBiome= new FloatSpinner( 0, 1000f, 1f);
IntSpinner tileSize= new IntSpinner( 0, 100000, 1);
JTextField biomesSprites = new JTextField();
FloatSpinner maxRoadDistance = new FloatSpinner( 0, 100000f, 1f);
TextListEdit biomesNames = new TextListEdit();
DefaultListModel<BiomeData> model = new DefaultListModel<>();
JList<BiomeData> list = new JList<>(model);
BiomeEdit edit=new BiomeEdit();
JTabbedPane tabs =new JTabbedPane();
static HashMap<String,SwingAtlas> atlas=new HashMap<>();
public class BiomeDataRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(!(value instanceof BiomeData biome))
return label;
// Get the renderer component from parent class
label.setText(biome.name);
if(!atlas.containsKey(biome.tilesetAtlas))
atlas.put(biome.tilesetAtlas,new SwingAtlas(Config.instance().getFile(biome.tilesetAtlas)));
SwingAtlas poiAtlas = atlas.get(biome.tilesetAtlas);
if(poiAtlas.has(biome.tilesetName))
label.setIcon(poiAtlas.get(biome.tilesetName));
else
{
ImageIcon img=poiAtlas.getAny();
if(img!=null)
label.setIcon(img);
}
return label;
}
}
/**
*
*/
private void updateBiome() {
int selected=list.getSelectedIndex();
if(selected<0)
return;
edit.setCurrentBiome(model.get(selected));
}
public WorldEditor() {
list.setCellRenderer(new BiomeDataRenderer());
list.addListSelectionListener(e -> WorldEditor.this.updateBiome());
BorderLayout layout = new BorderLayout();
setLayout(layout);
add(tabs);
JSplitPane biomeData=new JSplitPane();
tabs.addTab("BiomeData", biomeData);
FormPanel worldPanel=new FormPanel();
worldPanel.add("width:",width);
worldPanel.add("height:",height);
worldPanel.add("playerStartPosX:",playerStartPosX);
worldPanel.add("playerStartPosY:",playerStartPosY);
worldPanel.add("noiseZoomBiome:",noiseZoomBiome);
worldPanel.add("tileSize:",tileSize);
worldPanel.add("biomesSprites:",biomesSprites);
worldPanel.add("maxRoadDistance:",maxRoadDistance);
worldPanel.add("biomesNames:",biomesNames);
tabs.addTab("WorldData", worldPanel);
JScrollPane pane = new JScrollPane(edit);
biomeData.setLeftComponent(list); biomeData.setRightComponent(pane);
load();
JToolBar toolBar = new JToolBar("toolbar");
add(toolBar, BorderLayout.PAGE_START);
JButton newButton=new JButton("save");
newButton.addActionListener(e -> WorldEditor.this.save());
toolBar.add(newButton);
newButton=new JButton("save selected biome");
newButton.addActionListener(e -> WorldEditor.this.saveBiome());
toolBar.add(newButton);
newButton=new JButton("load");
newButton.addActionListener(e -> WorldEditor.this.load());
toolBar.add(newButton);
toolBar.addSeparator();
newButton=new JButton("test map");
newButton.addActionListener(e -> WorldEditor.this.test());
toolBar.add(newButton);
newButton=new JButton("edit effects");
newButton.addActionListener(e -> WorldEditor.this.startEffectEditor());
toolBar.add(newButton);
}
private void startEffectEditor() {
}
private void test() {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = forge.adventure.Main.class.getName();
ArrayList<String> command = new ArrayList<>();
command.add(javaBin);
command.add("-cp");
command.add(classpath);
command.add(className);
command.add("testMap");
ProcessBuilder build= new ProcessBuilder(command);
build .redirectInput(ProcessBuilder.Redirect.INHERIT)
.redirectOutput(ProcessBuilder.Redirect.INHERIT)
.redirectError(ProcessBuilder.Redirect.INHERIT);
try {
Process process= build.start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
void saveBiome()
{
edit.updateTerrain();
Json json = new Json(JsonWriter.OutputType.json);
FileHandle handle = Config.instance().getFile(currentData.biomesNames[list.getSelectedIndex()]);
handle.writeString(json.prettyPrint(json.toJson(edit.currentData, BiomeData.class)),false);
}
void save()
{
currentData.width=width.intValue();
currentData.height=height.intValue();
currentData.playerStartPosX=playerStartPosX.floatValue();
currentData.playerStartPosY=playerStartPosY.floatValue();
currentData.noiseZoomBiome=noiseZoomBiome.floatValue();
currentData.tileSize=tileSize.intValue();
currentData.biomesSprites=biomesSprites.getText();
currentData.maxRoadDistance=maxRoadDistance.floatValue();
currentData.biomesNames= (biomesNames.getList());
Json json = new Json(JsonWriter.OutputType.json);
FileHandle handle = Config.instance().getFile(Paths.WORLD);
handle.writeString(json.prettyPrint(json.toJson(currentData, WorldData.class)),false);
}
void load()
{
model.clear();
Json json = new Json();
FileHandle handle = Config.instance().getFile(Paths.WORLD);
if (handle.exists())
{
currentData=json.fromJson(WorldData.class, WorldData.class, handle);
}
update();
}
private void update() {
width.setValue(currentData.width);
height.setValue(currentData.height);
playerStartPosX.setValue(currentData.playerStartPosX);
playerStartPosY.setValue(currentData.playerStartPosY);
noiseZoomBiome.setValue(currentData.noiseZoomBiome);
tileSize.setValue(currentData.tileSize);
biomesSprites.setText(currentData.biomesSprites);
maxRoadDistance.setValue(currentData.maxRoadDistance);
biomesNames.setText(currentData.biomesNames);
for(String path:currentData.biomesNames)
{
Json json = new Json();
FileHandle handle = Config.instance().getFile(path);
if (handle.exists())
{
BiomeData data=json.fromJson(BiomeData.class, BiomeData.class, handle);
model.addElement(data);
}
}
}
}

10
forge-ai/.classpath Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java"/>
<classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="con" path="org.testng.TESTNG_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry combineaccessrules="false" kind="src" path="/forge-core"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>

24
forge-ai/.project Normal file
View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>forge-ai</name>
<comment></comment>
<projects>
<project>forge-game</project>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,3 @@
eclipse.preferences.version=1
encoding//src/main/java=ISO-8859-1
encoding/<project>=UTF-8

View File

@@ -0,0 +1,5 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.7

View File

@@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@@ -6,7 +6,7 @@
<parent>
<artifactId>forge</artifactId>
<groupId>forge</groupId>
<version>${revision}</version>
<version>1.6.20-SNAPSHOT</version>
</parent>
<artifactId>forge-ai</artifactId>

View File

@@ -1,5 +1,5 @@
package forge.ai;
public enum AIOption {
USE_SIMULATION
USE_SIMULATION;
}

View File

@@ -1,9 +0,0 @@
package forge.ai;
public record AiAbilityDecision(int rating, AiPlayDecision decision) {
private static int MIN_RATING = 30;
public boolean willingToPlay() {
return rating > MIN_RATING && decision.willingToPlay();
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -18,16 +18,12 @@
package forge.ai;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import forge.game.card.Card;
import forge.game.player.Player;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* <p>
@@ -59,20 +55,71 @@ public class AiCardMemory {
ATTACHED_THIS_TURN, // These equipments were attached to something already this turn
ANIMATED_THIS_TURN, // These cards had their AF Animate effect activated this turn
BOUNCED_THIS_TURN, // These cards were bounced this turn
ACTIVATED_THIS_TURN, // These cards had their ability activated this turn
CHOSEN_FOG_EFFECT, // These cards are marked as the Fog-like effect the AI is planning to cast this turn
MARKED_TO_AVOID_REENTRY, // These cards may cause a stack smash when processed recursively, and are thus marked to avoid a crash
PAYS_TAP_COST, // These cards will be tapped as part of a cost and cannot be chosen in another part
PAYS_SAC_COST, // These cards will be sacrificed as part of a cost and cannot be chosen in another part
REVEALED_CARDS // These cards were recently revealed to the AI by a call to PlayerControllerAi.reveal
MARKED_TO_AVOID_REENTRY // These cards may cause a stack smash when processed recursively, and are thus marked to avoid a crash
//REVEALED_CARDS // stub, not linked to AI code yet
}
private final Supplier<Map<MemorySet, Set<Card>>> memoryMap = Suppliers.memoize(Maps::newConcurrentMap);
private final Set<Card> memMandatoryAttackers;
private final Set<Card> memTrickAttackers;
private final Set<Card> memHeldManaSources;
private final Set<Card> memHeldManaSourcesForCombat;
private final Set<Card> memHeldManaSourcesForEnemyCombat;
private final Set<Card> memHeldManaSourcesForNextSpell;
private final Set<Card> memAttachedThisTurn;
private final Set<Card> memAnimatedThisTurn;
private final Set<Card> memBouncedThisTurn;
private final Set<Card> memActivatedThisTurn;
private final Set<Card> memChosenFogEffect;
private final Set<Card> memMarkedToAvoidReentry;
public AiCardMemory() {
this.memMandatoryAttackers = new HashSet<>();
this.memHeldManaSources = new HashSet<>();
this.memHeldManaSourcesForCombat = new HashSet<>();
this.memHeldManaSourcesForEnemyCombat = new HashSet<>();
this.memAttachedThisTurn = new HashSet<>();
this.memAnimatedThisTurn = new HashSet<>();
this.memBouncedThisTurn = new HashSet<>();
this.memActivatedThisTurn = new HashSet<>();
this.memTrickAttackers = new HashSet<>();
this.memChosenFogEffect = new HashSet<>();
this.memMarkedToAvoidReentry = new HashSet<>();
this.memHeldManaSourcesForNextSpell = new HashSet<>();
}
private Set<Card> getMemorySet(MemorySet set) {
return memoryMap.get().computeIfAbsent(set, value -> Sets.newConcurrentHashSet());
switch (set) {
case MANDATORY_ATTACKERS:
return memMandatoryAttackers;
case TRICK_ATTACKERS:
return memTrickAttackers;
case HELD_MANA_SOURCES_FOR_MAIN2:
return memHeldManaSources;
case HELD_MANA_SOURCES_FOR_DECLBLK:
return memHeldManaSourcesForCombat;
case HELD_MANA_SOURCES_FOR_ENEMY_DECLBLK:
return memHeldManaSourcesForEnemyCombat;
case HELD_MANA_SOURCES_FOR_NEXT_SPELL:
return memHeldManaSourcesForNextSpell;
case ATTACHED_THIS_TURN:
return memAttachedThisTurn;
case ANIMATED_THIS_TURN:
return memAnimatedThisTurn;
case BOUNCED_THIS_TURN:
return memBouncedThisTurn;
case ACTIVATED_THIS_TURN:
return memActivatedThisTurn;
case CHOSEN_FOG_EFFECT:
return memChosenFogEffect;
case MARKED_TO_AVOID_REENTRY:
return memMarkedToAvoidReentry;
//case REVEALED_CARDS:
// return memRevealedCards;
default:
return null;
}
}
/**
@@ -87,7 +134,10 @@ public class AiCardMemory {
if (c == null) {
return false;
}
return getMemorySet(set).contains(c);
Set<Card> memorySet = getMemorySet(set);
return memorySet == null ? false : memorySet.contains(c);
}
/**
@@ -99,7 +149,17 @@ public class AiCardMemory {
* @return true, if at least one card with the given name is remembered in the given memory set
*/
public boolean isRememberedCardByName(String cardName, MemorySet set) {
return getMemorySet(set).stream().anyMatch(c -> c.getName().equals(cardName));
Set<Card> memorySet = getMemorySet(set);
Iterator<Card> it = memorySet.iterator();
while (it.hasNext()) {
Card c = it.next();
if (c.getName().equals(cardName)) {
return true;
}
}
return false;
}
/**
@@ -113,7 +173,17 @@ public class AiCardMemory {
* @return true, if at least one card with the given name is remembered in the given memory set
*/
public boolean isRememberedCardByName(String cardName, MemorySet set, Player owner) {
return getMemorySet(set).stream().anyMatch(c -> c.getName().equals(cardName) && c.getOwner().equals(owner));
Set<Card> memorySet = getMemorySet(set);
Iterator<Card> it = memorySet.iterator();
while (it.hasNext()) {
Card c = it.next();
if (c.getName().equals(cardName) && c.getOwner().equals(owner)) {
return true;
}
}
return false;
}
/**
@@ -126,7 +196,9 @@ public class AiCardMemory {
public boolean rememberCard(Card c, MemorySet set) {
if (c == null)
return false;
return getMemorySet(set).add(c);
getMemorySet(set).add(c);
return true;
}
/**
@@ -143,7 +215,9 @@ public class AiCardMemory {
if (!isRememberedCard(c, set)) {
return false;
}
return getMemorySet(set).remove(c);
getMemorySet(set).remove(c);
return true;
}
/**
@@ -154,11 +228,16 @@ public class AiCardMemory {
* @return true, if at least one card with the given name was previously remembered in the given memory set and was successfully forgotten
*/
public boolean forgetAnyCardWithName(String cardName, MemorySet set) {
for (Card c : getMemorySet(set)) {
Set<Card> memorySet = getMemorySet(set);
Iterator<Card> it = memorySet.iterator();
while (it.hasNext()) {
Card c = it.next();
if (c.getName().equals(cardName)) {
return forgetCard(c, set);
}
}
return false;
}
@@ -171,11 +250,16 @@ public class AiCardMemory {
* @return true, if at least one card with the given name was previously remembered in the given memory set and was successfully forgotten
*/
public boolean forgetAnyCardWithName(String cardName, MemorySet set, Player owner) {
for (Card c : getMemorySet(set)) {
Set<Card> memorySet = getMemorySet(set);
Iterator<Card> it = memorySet.iterator();
while (it.hasNext()) {
Card c = it.next();
if (c.getName().equals(cardName) && c.getOwner().equals(owner)) {
return forgetCard(c, set);
}
}
return false;
}
@@ -185,16 +269,14 @@ public class AiCardMemory {
* @return true, if the given memory set contains no remembered cards.
*/
public boolean isMemorySetEmpty(MemorySet set) {
return set == null || getMemorySet(set).isEmpty();
return getMemorySet(set).isEmpty();
}
/**
* Clears the given memory set.
*/
public void clearMemorySet(MemorySet set) {
if (set != null) {
getMemorySet(set).clear();
}
getMemorySet(set).clear();
}
/**
@@ -207,12 +289,6 @@ public class AiCardMemory {
}
// Static functions to simplify access to AI card memory of a given AI player.
public static Set<Card> getMemorySet(Player ai, MemorySet set) {
if (!ai.getController().isAI()) {
return null;
}
return ((PlayerControllerAi)ai.getController()).getAi().getCardMemory().getMemorySet(set);
}
public static void rememberCard(Player ai, Card c, MemorySet set) {
if (!ai.getController().isAI()) {
return;
@@ -269,4 +345,4 @@ public class AiCardMemory {
public static boolean isMemorySetEmpty(AiController aic, MemorySet set) {
return aic.getCardMemory().isMemorySetEmpty(set);
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,125 +0,0 @@
package forge.ai;
import forge.card.CardRules;
import forge.card.CardType;
import forge.deck.CardPool;
import forge.deck.Deck;
import forge.deck.DeckSection;
import forge.game.card.Card;
import forge.game.player.Player;
import forge.item.PaperCard;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class AiDeckStatistics {
public float averageCMC = 0;
// TODO implement this. Use a numerically stable algorithm from
// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Weighted_incremental_algorithm
public float stddevCMC = 0;
public int maxCost = 0;
public int maxColoredCost = 0;
// in WUBRGC order from ManaCost.getColorShardCounts()
public int[] maxPips = null;
// public int[] numSources = new int[6];
public int numLands = 0;
public AiDeckStatistics(float averageCMC, float stddevCMC, int maxCost, int maxColoredCost, int[] maxPips, int numLands) {
this.averageCMC = averageCMC;
this.stddevCMC = stddevCMC;
this.maxCost = maxCost;
this.maxColoredCost = maxColoredCost;
this.maxPips = maxPips;
this.numLands = numLands;
}
public static AiDeckStatistics fromCards(List<Card> cards) {
int totalCMC = 0;
int totalCount = 0;
int numLands = 0;
int maxCost = 0;
int[] maxPips = new int[6];
int maxColoredCost = 0;
for (Card c : cards) {
CardRules rules = c.getRules();
if (rules == null) {
System.err.println(c + " CardRules is null" + (c.isToken() ? "/token" : "."));
continue;
}
CardType type = rules.getType();
if (type.isLand()) {
numLands += 1;
} else {
int cost = rules.getManaCost().getCMC();
// TODO use alternate casting costs for this, free spells will usually be cast for free
maxCost = Math.max(maxCost, cost);
totalCMC += cost;
totalCount++;
int[] pips = rules.getManaCost().getColorShardCounts();
int colored_pips = 0;
for (int i = 0; i < pips.length; i++) {
maxPips[i] = Math.max(maxPips[i], pips[i]);
if (i < 5) {
colored_pips += pips[i];
}
}
maxColoredCost = Math.max(maxColoredCost, colored_pips);
}
// TODO implement the number of mana sources
// find the sources
// What about non-mana-ability mana sources?
// fetchlands, ramp spells, etc
}
return new AiDeckStatistics(totalCount == 0 ? 0 : totalCMC / (float)totalCount,
0, // TODO use https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
maxCost,
maxColoredCost,
maxPips,
numLands
);
}
public static AiDeckStatistics fromDeck(Deck deck, Player player) {
List<Card> cardlist = new ArrayList<>();
for (final Map.Entry<DeckSection, CardPool> deckEntry : deck) {
switch (deckEntry.getKey()) {
case Main:
case Commander:
for (final Map.Entry<PaperCard, Integer> poolEntry : deckEntry.getValue()) {
Card card = Card.fromPaperCard(poolEntry.getKey(), player);
cardlist.add(card);
}
break;
default:
break; //ignore other sections
}
}
return fromCards(cardlist);
}
public static AiDeckStatistics fromPlayer(Player player) {
Deck deck = player.getRegisteredPlayer().getDeck();
if (deck.isEmpty()) {
// we're in a test or some weird match, search through the hand and library and build the decklist
List<Card> cardlist = new ArrayList<>();
for (Card c : player.getAllCards()) {
if (c.getPaperCard() == null) {
continue;
}
cardlist.add(c);
}
return fromCards(cardlist);
}
return fromDeck(deck, player);
}
}

View File

@@ -1,52 +1,21 @@
package forge.ai;
public enum AiPlayDecision {
// Play decision reasons
WillPlay,
MandatoryPlay,
PlayToEmptyHand,
ImpactCombat,
ResponseToStackResolve,
AddBoardPresence,
Removal,
Tempo,
CardAdvantage,
// Play later decisions
WaitForCombat,
WaitForMain2,
WaitForEndOfTurn,
StackNotEmpty,
AnotherTime,
// Don't play decision reasons
WillPlay,
CantPlaySa,
CantPlayAi,
CantAfford,
CantAffordX,
DoesntImpactCombat,
DoesntImpactGame,
MissingLogic,
WaitForMain2,
AnotherTime,
MissingNeededCards,
TimingRestrictions,
MissingPhaseRestrictions,
ConditionsNotMet,
NeedsToPlayCriteriaNotMet,
StopRunawayActivations,
TargetingFailed,
CostNotAcceptable,
LifeInDanger,
WouldDestroyLegend,
WouldDestroyOtherPlaneswalker,
WouldBecomeZeroToughnessCreature,
WouldDestroyWorldEnchantment,
BadEtbEffects,
CurseEffects;
public boolean willingToPlay() {
return switch (this) {
case WillPlay, MandatoryPlay, PlayToEmptyHand, AddBoardPresence, ImpactCombat, ResponseToStackResolve, Removal, Tempo, CardAdvantage -> true;
default -> false;
};
}
}

View File

@@ -11,24 +11,28 @@ import forge.game.zone.ZoneType;
public final class AiPlayerPredicates {
public static Comparator<Player> compareByZoneValue(final String type, final ZoneType zone, final SpellAbility sa) {
return (arg0, arg1) -> {
CardCollectionView list0 = AbilityUtils.filterListByType(arg0.getCardsIn(zone), type, sa);
CardCollectionView list1 = AbilityUtils.filterListByType(arg1.getCardsIn(zone), type, sa);
public static final Comparator<Player> compareByZoneValue(final String type, final ZoneType zone,
final SpellAbility sa) {
return new Comparator<Player>() {
@Override
public int compare(Player arg0, Player arg1) {
CardCollectionView list0 = AbilityUtils.filterListByType(arg0.getCardsIn(zone), type, sa);
CardCollectionView list1 = AbilityUtils.filterListByType(arg1.getCardsIn(zone), type, sa);
int v0, v1;
int v0, v1;
if ((CardLists.getNotType(list0, "Creature").isEmpty())
&& (CardLists.getNotType(list1, "Creature").isEmpty())) {
v0 = ComputerUtilCard.evaluateCreatureList(list0);
v1 = ComputerUtilCard.evaluateCreatureList(list1);
} // otherwise evaluate both lists by CMC and pass only if human
// permanents are less valuable
else {
v0 = ComputerUtilCard.evaluatePermanentList(list0);
v1 = ComputerUtilCard.evaluatePermanentList(list1);
if ((CardLists.getNotType(list0, "Creature").isEmpty())
&& (CardLists.getNotType(list1, "Creature").isEmpty())) {
v0 = ComputerUtilCard.evaluateCreatureList(list0);
v1 = ComputerUtilCard.evaluateCreatureList(list1);
} // otherwise evaluate both lists by CMC and pass only if human
// permanents are less valuable
else {
v0 = ComputerUtilCard.evaluatePermanentList(list0);
v1 = ComputerUtilCard.evaluatePermanentList(list1);
}
return Integer.compare(v0, v1);
}
return Integer.compare(v0, v1);
};
}
}

View File

@@ -20,6 +20,7 @@ package forge.ai;
import forge.LobbyPlayer;
import forge.util.Aggregates;
import forge.util.FileUtil;
import forge.util.TextUtil;
import org.apache.commons.lang3.ArrayUtils;
@@ -38,7 +39,7 @@ import java.util.Map;
* @version $Id: AIProfile.java 20169 2013-03-08 08:24:17Z Agetian $
*/
public class AiProfileUtil {
private static Map<String, Map<AiProps, String>> loadedProfiles = new HashMap<>();
private static Map<String, Map<AiProps, String>> loadedProfiles = new HashMap<String, Map<AiProps, String>>();
private static String AI_PROFILE_DIR;
private static final String AI_PROFILE_EXT = ".ai";
@@ -46,26 +47,6 @@ public class AiProfileUtil {
public static final String AI_PROFILE_RANDOM_MATCH = "Random (Every Match)";
public static final String AI_PROFILE_RANDOM_DUEL = "Random (Every Game)";
public enum AISideboardingMode {
Off,
AI,
HumanForAI;
public static AISideboardingMode normalizedValueOf(String value) {
return valueOf(value.replace(" ", ""));
}
}
private static AISideboardingMode aiSideboardingMode = AISideboardingMode.Off;
public static AISideboardingMode getAISideboardingMode() {
return aiSideboardingMode;
}
public static void setAiSideboardingMode(AISideboardingMode mode) {
aiSideboardingMode = mode;
}
/** Builds an AI profile file name with full relative
* path based on the profile name.
* @param profileName the name of the profile.
@@ -92,11 +73,12 @@ public class AiProfileUtil {
* Load a single profile.
* @param profileName a profile to load.
*/
private static Map<AiProps, String> loadProfile(final String profileName) {
Map<AiProps, String> profileMap = new HashMap<>();
private static final Map<AiProps, String> loadProfile(final String profileName) {
Map<AiProps, String> profileMap = new HashMap<AiProps, String>();
List<String> lines = FileUtil.readFile(buildFileName(profileName));
for (String line : lines) {
if (line.startsWith("#") || (line.length() == 0)) {
continue;
}
@@ -138,17 +120,18 @@ public class AiProfileUtil {
* @return ArrayList<String> - an array of strings containing all
* available profiles.
*/
public static List<String> getAvailableProfiles() {
final List<String> availableProfiles = new ArrayList<>();
public static List<String> getAvailableProfiles()
{
final List<String> availableProfiles = new ArrayList<String>();
final File dir = new File(AI_PROFILE_DIR);
final String[] children = dir.list();
if (children == null) {
System.err.println("AIProfile > can't find AI profile directory!");
} else {
for (String child : children) {
if (child.endsWith(AI_PROFILE_EXT)) {
availableProfiles.add(child.substring(0, child.length() - AI_PROFILE_EXT.length()));
for (int i = 0; i < children.length; i++) {
if (children[i].endsWith(AI_PROFILE_EXT)) {
availableProfiles.add(children[i].substring(0, children[i].length() - AI_PROFILE_EXT.length()));
}
}
}
@@ -163,7 +146,7 @@ public class AiProfileUtil {
* available profiles including special random profile tags.
*/
public static List<String> getProfilesDisplayList() {
final List<String> availableProfiles = new ArrayList<>();
final List<String> availableProfiles = new ArrayList<String>();
availableProfiles.add(AI_PROFILE_RANDOM_MATCH);
availableProfiles.add(AI_PROFILE_RANDOM_DUEL);
availableProfiles.addAll(getAvailableProfiles());

View File

@@ -35,7 +35,6 @@ public enum AiProps { /** */
MOVE_EQUIPMENT_TO_BETTER_CREATURES ("from_useless_only"),
MOVE_EQUIPMENT_CREATURE_EVAL_THRESHOLD ("60"),
PRIORITIZE_MOVE_EQUIPMENT_IF_USELESS ("true"),
SAC_TO_REATTACH_TARGET_EVAL_THRESHOLD ("400"),
PREDICT_SPELLS_FOR_MAIN2 ("true"), /** */
RESERVE_MANA_FOR_MAIN2_CHANCE ("0"), /** */
PLAY_AGGRO ("false"),
@@ -75,7 +74,6 @@ public enum AiProps { /** */
ALWAYS_COPY_SPELL_IF_CMC_DIFF ("2"), /** */
ACTIVELY_DESTROY_ARTS_AND_NONAURA_ENCHS ("true"), /** */
ACTIVELY_DESTROY_IMMEDIATELY_UNBLOCKABLE ("false"), /** */
ACTIVELY_PROTECT_VS_CURSE_AURAS("false"), /** */
DESTROY_IMMEDIATELY_UNBLOCKABLE_THRESHOLD ("2"), /** */
DESTROY_IMMEDIATELY_UNBLOCKABLE_ONLY_IN_DNGR ("true"), /** */
DESTROY_IMMEDIATELY_UNBLOCKABLE_LIFE_IN_DNGR ("5"), /** */
@@ -131,21 +129,7 @@ public enum AiProps { /** */
FLASH_USE_BUFF_AURAS_AS_COMBAT_TRICKS("true"),
FLASH_BUFF_AURA_CHANCE_TO_CAST_EARLY("1"),
FLASH_BUFF_AURA_CHANCE_CAST_AT_EOT("5"),
FLASH_BUFF_AURA_CHANCE_TO_RESPOND_TO_STACK("100"),
BLINK_RELOAD_PLANESWALKER_CHANCE("30"), /** */
BLINK_RELOAD_PLANESWALKER_MAX_LOYALTY("2"), /** */
BLINK_RELOAD_PLANESWALKER_LOYALTY_DIFF("2"),
SACRIFICE_DEFAULT_PREF_ENABLE("true"),
SACRIFICE_DEFAULT_PREF_MIN_CMC("0"),
SACRIFICE_DEFAULT_PREF_MAX_CMC("2"),
SACRIFICE_DEFAULT_PREF_ALLOW_TOKENS("true"),
SACRIFICE_DEFAULT_PREF_MAX_CREATURE_EVAL("135"),
SIDEBOARDING_ENABLE("true"),
SIDEBOARDING_CHANCE_PER_CARD("50"),
SIDEBOARDING_CHANCE_ON_WIN("0"),
SIDEBOARDING_IN_LIMITED_FORMATS("false"),
SIDEBOARDING_SHARED_TYPE_ONLY("false"),
SIDEBOARDING_PLANESWALKER_EQ_CREATURE("false");
FLASH_BUFF_AURA_CHANCE_TO_RESPOND_TO_STACK("100"); /** */
// Experimental features, must be promoted or removed after extensive testing and, ideally, defaulting
// <-- There are no experimental options here -->

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,7 @@
package forge.ai;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import forge.card.CardStateName;
import forge.game.Game;
import forge.game.GameActionUtil;
@@ -14,32 +10,38 @@ import forge.game.card.Card;
import forge.game.card.CardCollection;
import forge.game.card.CardCollectionView;
import forge.game.card.CardLists;
import forge.game.cost.CostPart;
import forge.game.cost.CostPayEnergy;
import forge.game.cost.CostPutCounter;
import forge.game.cost.CostRemoveCounter;
import forge.game.keyword.Keyword;
import forge.game.phase.PhaseType;
import forge.game.card.CardPredicates.Presets;
import forge.game.player.Player;
import forge.game.spellability.OptionalCost;
import forge.game.spellability.OptionalCostValue;
import forge.game.spellability.SpellAbility;
import forge.game.spellability.SpellAbilityStackInstance;
import forge.game.zone.ZoneType;
import java.util.Iterator;
import java.util.List;
public class ComputerUtilAbility {
public static CardCollection getAvailableLandsToPlay(final Game game, final Player player) {
if (!game.getStack().isEmpty() || !game.getPhaseHandler().getPhase().isMain()) {
return null;
}
CardCollection landList = new CardCollection(player.getCardsIn(ZoneType.Hand));
final CardCollection hand = new CardCollection(player.getCardsIn(ZoneType.Hand));
hand.addAll(player.getCardsIn(ZoneType.Exile));
CardCollection landList = CardLists.filter(hand, Presets.LANDS);
//filter out cards that can't be played
landList = CardLists.filter(landList, c -> {
if (!c.hasPlayableLandFace()) {
return false;
landList = CardLists.filter(landList, new Predicate<Card>() {
@Override
public boolean apply(final Card c) {
if (!c.getSVar("NeedsToPlay").isEmpty()) {
final String needsToPlay = c.getSVar("NeedsToPlay");
CardCollection list = CardLists.getValidCards(game.getCardsIn(ZoneType.Battlefield), needsToPlay.split(","), c.getController(), c, null);
if (list.isEmpty()) {
return false;
}
}
return player.canPlayLand(c);
}
return player.canPlayLand(c, false, c.getFirstSpellAbility());
});
final CardCollection landsNotInHand = new CardCollection(player.getCardsIn(ZoneType.Graveyard));
@@ -48,7 +50,7 @@ public class ComputerUtilAbility {
landsNotInHand.add(player.getCardsIn(ZoneType.Library).get(0));
}
for (final Card crd : landsNotInHand) {
if (!(crd.hasPlayableLandFace() || (crd.isFaceDown() && crd.getState(CardStateName.Original).getType().isLand()))) {
if (!(crd.isLand() || (crd.isFaceDown() && crd.getState(CardStateName.Original).getType().isLand()))) {
continue;
}
if (!crd.mayPlay(player).isEmpty()) {
@@ -65,42 +67,45 @@ public class ComputerUtilAbility {
CardCollection all = new CardCollection(player.getCardsIn(ZoneType.Hand));
all.addAll(player.getCardsIn(ZoneType.Graveyard));
for (Player p : game.getPlayers()) {
if (!p.getCardsIn(ZoneType.Library).isEmpty()) {
all.add(p.getCardsIn(ZoneType.Library).get(0));
}
all.addAll(player.getCardsIn(ZoneType.Command));
if (!player.getCardsIn(ZoneType.Library).isEmpty()) {
all.add(player.getCardsIn(ZoneType.Library).get(0));
}
for(Player p : game.getPlayers()) {
all.addAll(p.getCardsIn(ZoneType.Exile));
all.addAll(p.getCardsIn(ZoneType.Battlefield));
}
all.addAll(game.getCardsIn(ZoneType.Command));
all.addAll(game.getCardsIn(ZoneType.Exile));
all.addAll(game.getCardsIn(ZoneType.Battlefield));
return all;
}
public static List<SpellAbility> getSpellAbilities(final CardCollectionView l, final Player player) {
final List<SpellAbility> spellAbilities = Lists.newArrayList();
for (final Card c : l) {
spellAbilities.addAll(c.getAllPossibleAbilities(player, false));
for (final SpellAbility sa : c.getSpellAbilities()) {
spellAbilities.add(sa);
}
if (c.isFaceDown() && c.isInZone(ZoneType.Exile) && !c.mayPlay(player).isEmpty()) {
for (final SpellAbility sa : c.getState(CardStateName.Original).getSpellAbilities()) {
spellAbilities.add(sa);
}
}
}
return spellAbilities;
}
public static List<SpellAbility> getOriginalAndAltCostAbilities(final List<SpellAbility> originList, final Player player) {
final List<SpellAbility> newAbilities = Lists.newArrayList();
List<SpellAbility> originListWithAddCosts = Lists.newArrayList();
for (SpellAbility sa : originList) {
// If this spell has alternative additional costs, add them instead of the unmodified SA itself
sa.setActivatingPlayer(player);
originListWithAddCosts.addAll(GameActionUtil.getAdditionalCostSpell(sa));
}
for (SpellAbility sa : originListWithAddCosts) {
// determine which alternative costs are cheaper than the original and prioritize them
List<SpellAbility> saAltCosts = GameActionUtil.getAlternativeCosts(sa, player, false);
List<SpellAbility> saAltCosts = GameActionUtil.getAlternativeCosts(sa, player);
List<SpellAbility> priorityAltSa = Lists.newArrayList();
List<SpellAbility> otherAltSa = Lists.newArrayList();
for (SpellAbility altSa : saAltCosts) {
if (sa.getPayCosts().isOnlyManaCost()
if (altSa.getPayCosts() == null || sa.getPayCosts() == null) {
otherAltSa.add(altSa);
} else if (sa.getPayCosts().isOnlyManaCost()
&& altSa.getPayCosts().isOnlyManaCost() && sa.getPayCosts().getTotalMana().compareTo(altSa.getPayCosts().getTotalMana()) == 1) {
// the alternative cost is strictly cheaper, so why not? (e.g. Omniscience etc.)
priorityAltSa.add(altSa);
@@ -114,7 +119,7 @@ public class ComputerUtilAbility {
newAbilities.add(sa);
newAbilities.addAll(otherAltSa);
}
final List<SpellAbility> result = Lists.newArrayList();
for (SpellAbility sa : newAbilities) {
sa.setActivatingPlayer(player);
@@ -123,10 +128,6 @@ public class ComputerUtilAbility {
boolean choseOptCost = false;
List<OptionalCostValue> list = GameActionUtil.getOptionalCostValues(sa);
if (!list.isEmpty()) {
// still add base spell in case of Promise Gift
if (list.stream().anyMatch(ocv -> ocv.getType().equals(OptionalCost.PromiseGift))) {
result.add(sa);
}
list = player.getController().chooseOptionalCosts(sa, list);
if (!list.isEmpty()) {
choseOptCost = true;
@@ -150,13 +151,13 @@ public class ComputerUtilAbility {
return null;
}
SpellAbility tgtSA = it.next().getSpellAbility();
SpellAbility tgtSA = it.next().getSpellAbility(true);
// Grab the topmost spellability that isn't this SA and use that for comparisons
if (sa.equals(tgtSA) && game.getStack().size() > 1) {
if (!it.hasNext()) {
return null;
}
tgtSA = it.next().getSpellAbility();
tgtSA = it.next().getSpellAbility(true);
}
return tgtSA;
}
@@ -201,7 +202,7 @@ public class ComputerUtilAbility {
}
}
for (SpellAbilityStackInstance si : ai.getGame().getStack()) {
SpellAbility ab = si.getSpellAbility();
SpellAbility ab = si.getSpellAbility(false);
if (ab != null && ab.getApi() == api && si.getTargetChoices() != null) {
for (Card c : cardList) {
// TODO: somehow ensure that the detected SA won't be countered
@@ -215,217 +216,4 @@ public class ComputerUtilAbility {
return targeted;
}
public static boolean isFullyTargetable(SpellAbility sa) {
SpellAbility sub = sa;
while (sub != null) {
if (sub.usesTargeting() && sub.getTargetRestrictions().getNumCandidates(sub, true) < sub.getMinTargets()) {
return false;
}
sub = sub.getSubAbility();
}
return true;
}
public final static saComparator saEvaluator = new saComparator();
// not sure "playing biggest spell" matters?
public final static class saComparator implements Comparator<SpellAbility> {
@Override
public int compare(final SpellAbility a, final SpellAbility b) {
return compareEvaluator(a, b, false);
}
public int compareEvaluator(final SpellAbility a, final SpellAbility b, boolean safeToEvaluateCreatures) {
// sort from highest cost to lowest
// we want the highest costs first
int a1 = a.getPayCosts().getTotalMana().getCMC();
int b1 = b.getPayCosts().getTotalMana().getCMC();
// deprioritize SAs explicitly marked as preferred to be activated last compared to all other SAs
if (a.hasParam("AIActivateLast") && !b.hasParam("AIActivateLast")) {
return 1;
} else if (b.hasParam("AIActivateLast") && !a.hasParam("AIActivateLast")) {
return -1;
}
// deprioritize planar die roll marked with AIRollPlanarDieParams:LowPriority$ True
if (ApiType.RollPlanarDice == a.getApi() || ApiType.RollPlanarDice == b.getApi()) {
Card hostCardForGame = a.getHostCard();
if (hostCardForGame == null) {
if (b.getHostCard() != null) {
hostCardForGame = b.getHostCard();
} else {
return 0; // fallback if neither SA have a host card somehow
}
}
Game game = hostCardForGame.getGame();
if (game.getActivePlanes() != null) {
for (Card c : game.getActivePlanes()) {
if (c.hasSVar("AIRollPlanarDieParams") && c.getSVar("AIRollPlanarDieParams").toLowerCase().matches(".*lowpriority\\$\\s*true.*")) {
if (ApiType.RollPlanarDice == a.getApi()) {
return 1;
} else {
return -1;
}
}
}
}
}
// deprioritize pump spells with pure energy cost (can be activated last,
// since energy is generally scarce, plus can benefit e.g. Electrostatic Pummeler)
int a2 = 0, b2 = 0;
if (a.getApi() == ApiType.Pump && a.getPayCosts().getCostEnergy() != null) {
if (a.getPayCosts().hasOnlySpecificCostType(CostPayEnergy.class)) {
a2 = a.getPayCosts().getCostEnergy().convertAmount();
}
}
if (b.getApi() == ApiType.Pump && b.getPayCosts().getCostEnergy() != null) {
if (b.getPayCosts().hasOnlySpecificCostType(CostPayEnergy.class)) {
b2 = b.getPayCosts().getCostEnergy().convertAmount();
}
}
if (a2 == 0 && b2 > 0) {
return -1;
} else if (b2 == 0 && a2 > 0) {
return 1;
}
// cast 0 mana cost spells first (might be a Mox)
if (a1 == 0 && b1 > 0 && ApiType.Mana != a.getApi()) {
return -1;
} else if (a1 > 0 && b1 == 0 && ApiType.Mana != b.getApi()) {
return 1;
}
if (a.getHostCard() != null && a.getHostCard().hasSVar("FreeSpellAI")) {
return -1;
} else if (b.getHostCard() != null && b.getHostCard().hasSVar("FreeSpellAI")) {
return 1;
}
if (a.getHostCard().equals(b.getHostCard()) && a.getApi() == b.getApi()) {
// Cheaper Spectacle costs should be preferred
// FIXME: Any better way to identify that these are the same ability, one with Spectacle and one not?
// (looks like it's not a full-fledged alternative cost as such, and is not processed with other alt costs)
if (a.isSpectacle() && !b.isSpectacle() && a1 < b1) {
return 1;
} else if (b.isSpectacle() && !a.isSpectacle() && b1 < a1) {
return 1;
}
}
a1 += getSpellAbilityPriority(a);
b1 += getSpellAbilityPriority(b);
// If both are creature spells sort them after
if (safeToEvaluateCreatures) {
a1 += Math.round(ComputerUtilCard.evaluateCreature(a) / 100f);
b1 += Math.round(ComputerUtilCard.evaluateCreature(b) / 100f);
}
return b1 - a1;
}
private static int getSpellAbilityPriority(SpellAbility sa) {
int p = 0;
Card source = sa.getHostCard();
final Player ai = source == null ? sa.getActivatingPlayer() : source.getController();
if (ai == null) {
System.err.println("Error: couldn't figure out the activating player and host card for SA: " + sa);
return 0;
}
final boolean noCreatures = ai.getCreaturesInPlay().isEmpty();
if (source != null) {
// puts creatures in front of spells
if (source.isCreature()) {
p += 1;
}
if (source.hasSVar("AIPriorityModifier")) {
p += Integer.parseInt(source.getSVar("AIPriorityModifier"));
}
// try to use it before it's gone
if (source.isInPlay() && source.hasSVar("EndOfTurnLeavePlay")) {
p += 1;
}
if (ComputerUtilCard.isCardRemAIDeck(sa.getOriginalHost() != null ? sa.getOriginalHost() : source)) {
p -= 10;
}
// don't play equipments before having any creatures
if (source.isEquipment() && noCreatures) {
p -= 9;
}
// don't equip stuff in main 2 if there's more stuff to cast at the moment
if (sa.getApi() == ApiType.Attach && !sa.isCurse() && source.getGame().getPhaseHandler().getPhase().isAfter(PhaseType.COMBAT_DECLARE_BLOCKERS)) {
p -= 1;
}
// 1. increase chance of using Surge effects
// 2. non-surged versions are usually inefficient
if (source.hasKeyword(Keyword.SURGE) && !sa.isSurged()) {
p -= 9;
}
// move snap-casted spells to front
if (source.isInZone(ZoneType.Graveyard)) {
if (sa.getMayPlay() != null && source.mayPlay(sa.getMayPlay()) != null) {
p += 50;
}
}
// if the profile specifies it, deprioritize Storm spells in an attempt to build up storm count
if (source.hasKeyword(Keyword.STORM) && ai.getController() instanceof PlayerControllerAi) {
p -= (((PlayerControllerAi) ai.getController()).getAi().getIntProperty(AiProps.PRIORITY_REDUCTION_FOR_STORM_SPELLS));
}
}
// use Surge and Prowl costs when able to
if (sa.isSurged() || sa.isProwl()) {
p += 9;
}
// sort planeswalker abilities with most costly first
if (sa.isPwAbility()) {
final CostPart cost = sa.getPayCosts().getCostParts().get(0);
if (cost instanceof CostRemoveCounter) {
p += cost.convertAmount() == null ? 1 : cost.convertAmount();
} else if (cost instanceof CostPutCounter) {
p -= cost.convertAmount();
}
if (sa.hasParam("Ultimate")) {
p += 9;
}
}
if (ApiType.DestroyAll == sa.getApi()) {
// check boardwipe earlier
p += 4;
} else if (ApiType.Mana == sa.getApi()) {
// keep mana abilities for paying
p -= 9;
}
// try to cast mana ritual spells before casting spells to maximize potential mana
if ("ManaRitual".equals(sa.getParam("AILogic"))) {
p += 9;
}
return p;
}
}
public static List<SpellAbility> sortCreatureSpells(final List<SpellAbility> all) {
// try to smoothen power creep by making CMC less of a factor
final List<SpellAbility> creatures = AiController.filterListByApi(Lists.newArrayList(all), ApiType.PermanentCreature);
if (creatures.size() <= 1) {
return all;
}
// TODO this doesn't account for nearly identical creatures where one is a newer but more cost efficient variant
creatures.sort(ComputerUtilCard.EvaluateCreatureSpellComparator);
int idx = 0;
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getApi() == ApiType.PermanentCreature) {
all.set(i, creatures.get(idx));
idx++;
}
}
return all;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,41 +1,31 @@
package forge.ai;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import forge.game.GameObject;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import forge.ai.AiCardMemory.MemorySet;
import forge.ai.ability.AnimateAi;
import forge.card.ColorSet;
import forge.game.Game;
import forge.game.ability.AbilityUtils;
import forge.game.card.*;
import forge.game.card.CardPredicates.Presets;
import forge.game.combat.Combat;
import forge.game.cost.*;
import forge.game.keyword.Keyword;
import forge.game.phase.PhaseType;
import forge.game.player.Player;
import forge.game.spellability.Spell;
import forge.game.spellability.SpellAbility;
import forge.game.spellability.TargetChoices;
import forge.game.zone.ZoneType;
import forge.util.IterableUtil;
import forge.util.MyRandom;
import forge.util.TextUtil;
import forge.util.collect.FCollectionView;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Set;
public class ComputerUtilCost {
private static boolean suppressRecursiveSacCostCheck = false;
public static void setSuppressRecursiveSacCostCheck(boolean shouldSuppress) {
suppressRecursiveSacCostCheck = shouldSuppress;
}
/**
* Check add m1 m1 counter cost.
@@ -51,10 +41,11 @@ public class ComputerUtilCost {
return true;
}
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostPutCounter addCounter) {
if (part instanceof CostPutCounter) {
final CostPutCounter addCounter = (CostPutCounter) part;
final CounterType type = addCounter.getCounter();
if (type.is(CounterEnumType.M1M1)) {
if (type.equals(CounterType.M1M1)) {
return false;
}
}
@@ -62,6 +53,9 @@ public class ComputerUtilCost {
return true;
}
public static boolean checkRemoveCounterCost(final Cost cost, final Card source) {
return checkRemoveCounterCost(cost, source, null);
}
/**
* Check remove counter cost.
*
@@ -75,24 +69,36 @@ public class ComputerUtilCost {
if (cost == null) {
return true;
}
final AiCostDecision decision = new AiCostDecision(sa.getActivatingPlayer(), sa, false);
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostRemoveCounter remCounter) {
if (part instanceof CostRemoveCounter) {
final CostRemoveCounter remCounter = (CostRemoveCounter) part;
final CounterType type = remCounter.counter;
if (!part.payCostFromSource()) {
if (type.is(CounterEnumType.P1P1)) {
if (CounterType.P1P1.equals(type)) {
return false;
}
continue;
}
// even if it can be paid, removing zero counters should not be done.
// even if it can be paid, removing zero counters should not be done.
if (part.payCostFromSource() && source.getCounters(type) <= 0) {
return false;
}
// Remove X counters - set ChosenX to max possible value here, the SAs should correct that
// value later as the AI decides what to do (in checkApiLogic / checkAiLogic)
if (sa != null && sa.hasSVar(remCounter.getAmount())) {
final String sVar = sa.getSVar(remCounter.getAmount());
if (sVar.equals("XChoice") && !sa.hasSVar("ChosenX")) {
sa.setSVar("ChosenX", String.valueOf(source.getCounters(type)));
}
}
// check the sa what the PaymentDecision is.
// ignore Loyality abilities with Zero as Cost
if (!type.is(CounterEnumType.LOYALTY)) {
if (sa != null && !CounterType.LOYALTY.equals(type)) {
final AiCostDecision decision = new AiCostDecision(sa.getActivatingPlayer(), sa);
PaymentDecision pay = decision.visit(remCounter);
if (pay == null || pay.c <= 0) {
return false;
@@ -100,13 +106,10 @@ public class ComputerUtilCost {
}
//don't kill the creature
if (type.is(CounterEnumType.P1P1) && source.getLethalDamage() <= 1
if (CounterType.P1P1.equals(type) && source.getLethalDamage() <= 1
&& !source.hasKeyword(Keyword.UNDYING)) {
return false;
}
} else if (part instanceof CostRemoveAnyCounter remCounter) {
PaymentDecision pay = decision.visit(remCounter);
return pay != null;
}
}
return true;
@@ -121,7 +124,7 @@ public class ComputerUtilCost {
* the source
* @return true, if successful
*/
public static boolean checkDiscardCost(final Player ai, final Cost cost, final Card source, SpellAbility sa) {
public static boolean checkDiscardCost(final Player ai, final Cost cost, final Card source) {
if (cost == null) {
return true;
}
@@ -129,38 +132,27 @@ public class ComputerUtilCost {
CardCollection hand = new CardCollection(ai.getCardsIn(ZoneType.Hand));
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostDiscard disc) {
if (part instanceof CostDiscard) {
final CostDiscard disc = (CostDiscard) part;
final String type = disc.getType();
final CardCollection typeList;
int num;
if (type.equals("Hand")) {
typeList = hand;
num = hand.size();
} else {
if (type.equals("CARDNAME")) {
if (source.getAbilityText().contains("Bloodrush")) {
continue;
}
if (ai.getGame().getPhaseHandler().is(PhaseType.END_OF_TURN, ai)
&& !ai.isUnlimitedHandSize() && ai.getCardsIn(ZoneType.Hand).size() > ai.getMaxHandSize()) {
// Better do something than just discard stuff
return true;
}
return false;
}
typeList = CardLists.getValidCards(hand, type, source.getController(), source, sa);
if (typeList.size() > ai.getMaxHandSize()) {
continue;
}
num = AbilityUtils.calculateAmount(source, disc.getAmount(), sa);
if (type.equals("CARDNAME") && source.getAbilityText().contains("Bloodrush")) {
continue;
}
final CardCollection typeList = CardLists.getValidCards(hand, type.split(","), source.getController(), source, null);
if (typeList.size() > ai.getMaxHandSize()) {
continue;
}
int num = AbilityUtils.calculateAmount(source, disc.getAmount(), null);
for (int i = 0; i < num; i++) {
Card pref = ComputerUtil.getCardPreference(ai, source, "DiscardCost", typeList);
if (pref == null) {
return false;
} else {
typeList.remove(pref);
hand.remove(pref);
}
typeList.remove(pref);
hand.remove(pref);
}
}
}
@@ -178,13 +170,14 @@ public class ComputerUtilCost {
* the remaining life
* @return true, if successful
*/
public static boolean checkDamageCost(final Player ai, final Cost cost, final Card source, final int remainingLife, final SpellAbility sa) {
public static boolean checkDamageCost(final Player ai, final Cost cost, final Card source, final int remainingLife) {
if (cost == null) {
return true;
}
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostDamage pay) {
int realDamage = ComputerUtilCombat.predictDamageTo(ai, pay.getAbilityAmount(sa), source, false);
if (part instanceof CostDamage) {
final CostDamage pay = (CostDamage) part;
int realDamage = ComputerUtilCombat.predictDamageTo(ai, pay.convertAmount(), source, false);
if (ai.getLife() - realDamage < remainingLife
&& realDamage > 0 && !ai.cantLoseForZeroOrLessLife()
&& ai.canLoseLife()) {
@@ -215,8 +208,13 @@ public class ComputerUtilCost {
return true;
}
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostPayLife payLife) {
int amount = payLife.getAbilityAmount(sourceAbility);
if (part instanceof CostPayLife) {
final CostPayLife payLife = (CostPayLife) part;
Integer amount = payLife.convertAmount();
if (amount == null) {
amount = AbilityUtils.calculateAmount(source, payLife.getAmount(), sourceAbility);
}
// check if there's override for the remainingLife threshold
if (sourceAbility != null && sourceAbility.hasParam("AILifeThreshold")) {
@@ -231,46 +229,6 @@ public class ComputerUtilCost {
return true;
}
public static boolean checkForManaSacrificeCost(final Player ai, final Cost cost, final SpellAbility sourceAbility, final boolean effect) {
// TODO cheating via autopay can still happen, need to get the real ai player from controlledBy
if (cost == null || !ai.isAI()) {
return true;
}
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostSacrifice) {
CardCollection list = new CardCollection();
final CardCollection exclude = new CardCollection();
if (AiCardMemory.getMemorySet(ai, MemorySet.PAYS_SAC_COST) != null) {
exclude.addAll(AiCardMemory.getMemorySet(ai, MemorySet.PAYS_SAC_COST));
}
if (part.payCostFromSource()) {
list.add(sourceAbility.getHostCard());
} else if (part.getType().equals("OriginalHost")) {
list.add(sourceAbility.getOriginalHost());
} else if (part.getAmount().equals("All")) {
// Does the AI want to use Sacrifice All?
return false;
} else {
int c = part.getAbilityAmount(sourceAbility);
final AiController aic = ((PlayerControllerAi)ai.getController()).getAi();
CardCollectionView choices = aic.chooseSacrificeType(part.getType(), sourceAbility, effect, c, exclude);
if (choices != null) {
list.addAll(choices);
}
}
list.removeAll(exclude);
if (list.isEmpty()) {
return false;
}
for (Card choice : list) {
AiCardMemory.rememberCard(ai, choice, MemorySet.PAYS_SAC_COST);
}
return true;
}
}
return true;
}
/**
* Check creature sacrifice cost.
*
@@ -285,7 +243,8 @@ public class ComputerUtilCost {
return true;
}
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostSacrifice sac) {
if (part instanceof CostSacrifice) {
final CostSacrifice sac = (CostSacrifice) part;
final int amount = AbilityUtils.calculateAmount(source, sac.getAmount(), sourceAbility);
if (sac.payCostFromSource() && source.isCreature()) {
@@ -298,10 +257,7 @@ public class ComputerUtilCost {
}
final CardCollection sacList = new CardCollection();
CardCollection typeList = CardLists.getValidCards(ai.getCardsIn(ZoneType.Battlefield), type.split(";"), source.getController(), source, sourceAbility);
// don't sacrifice the card we're pumping
typeList = paymentChoicesWithoutTargets(typeList, sourceAbility, ai);
final CardCollection typeList = CardLists.getValidCards(ai.getCardsIn(ZoneType.Battlefield), type.split(";"), source.getController(), source, null);
int count = 0;
while (count < amount) {
@@ -334,14 +290,11 @@ public class ComputerUtilCost {
return true;
}
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostSacrifice sac) {
if (suppressRecursiveSacCostCheck) {
return false;
}
if (part instanceof CostSacrifice) {
final CostSacrifice sac = (CostSacrifice) part;
final int amount = AbilityUtils.calculateAmount(source, sac.getAmount(), sourceAbility);
String type = sac.getType();
final String type = sac.getType();
if (type.equals("CARDNAME")) {
if (!important) {
@@ -350,51 +303,19 @@ public class ComputerUtilCost {
if (!CardLists.filterControlledBy(source.getEnchantedBy(), source.getController()).isEmpty()) {
return false;
}
if (source.isCreature()) {
// e.g. Sakura-Tribe Elder
final Combat combat = ai.getGame().getCombat();
final boolean beforeNextTurn = ai.getGame().getPhaseHandler().is(PhaseType.END_OF_TURN) && ai.getGame().getPhaseHandler().getNextTurn().equals(ai) && ComputerUtilCard.evaluateCreature(source) <= 150;
final boolean creatureInDanger = ComputerUtil.predictCreatureWillDieThisTurn(ai, source, sourceAbility, false)
&& !ComputerUtilCombat.willOpposingCreatureDieInCombat(ai, source, combat);
final int lifeThreshold = ai.getController().isAI() ? (((PlayerControllerAi) ai.getController()).getAi().getIntProperty(AiProps.AI_IN_DANGER_THRESHOLD)) : 4;
final boolean aiInDanger = ai.getLife() <= lifeThreshold && ai.canLoseLife() && !ai.cantLoseForZeroOrLessLife();
if (creatureInDanger && !ComputerUtilCombat.isDangerousToSacInCombat(ai, source, combat)) {
return true;
} else if (aiInDanger || !beforeNextTurn) {
return false;
}
}
continue;
}
boolean differentNames = false;
if (type.contains("+WithDifferentNames")) {
type = type.replace("+WithDifferentNames", "");
differentNames = true;
}
CardCollection typeList = CardLists.getValidCards(ai.getCardsIn(ZoneType.Battlefield), type.split(";"), source.getController(), source, sourceAbility);
if (differentNames) {
final Set<Card> uniqueNameCards = Sets.newHashSet();
for (final Card card : typeList) {
// CR 201.2b Those objects have different names only if each of them has at least one name and no two objects in that group have a name in common
if (!card.hasNoName()) {
uniqueNameCards.add(card);
}
}
typeList.clear();
typeList.addAll(uniqueNameCards);
}
// don't sacrifice the card we're pumping
typeList = paymentChoicesWithoutTargets(typeList, sourceAbility, ai);
final CardCollection sacList = new CardCollection();
final CardCollection typeList = CardLists.getValidCards(ai.getCardsIn(ZoneType.Battlefield), type.split(";"), source.getController(), source, null);
int count = 0;
while (count < amount) {
Card prefCard = ComputerUtil.getCardPreference(ai, source, "SacCost", typeList, sourceAbility);
Card prefCard = ComputerUtil.getCardPreference(ai, source, "SacCost", typeList);
if (prefCard == null) {
return false;
}
sacList.add(prefCard);
typeList.remove(prefCard);
count++;
}
@@ -403,6 +324,66 @@ public class ComputerUtilCost {
return true;
}
public static boolean isSacrificeSelfCost(final Cost cost) {
if (cost == null) {
return false;
}
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostSacrifice) {
if ("CARDNAME".equals(part.getType())) {
return true;
}
}
}
return false;
}
/**
* Check creature sacrifice cost.
*
* @param cost
* the cost
* @param source
* the source
* @return true, if successful
*/
public static boolean checkTapTypeCost(final Player ai, final Cost cost, final Card source, final SpellAbility sa) {
if (cost == null) {
return true;
}
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostTapType) {
/*
* Only crew with creatures weaker than vehicle
*
* Possible improvements:
* - block against evasive (flyers, intimidate, etc.)
* - break board stall by racing with evasive vehicle
*/
if (sa.hasParam("Crew")) {
Card vehicle = AnimateAi.becomeAnimated(source, sa);
final int vehicleValue = ComputerUtilCard.evaluateCreature(vehicle);
String type = part.getType();
String totalP = type.split("withTotalPowerGE")[1];
type = TextUtil.fastReplace(type, TextUtil.concatNoSpace("+withTotalPowerGE", totalP), "");
CardCollection exclude = CardLists.getValidCards(
new CardCollection(ai.getCardsIn(ZoneType.Battlefield)), type.split(";"),
source.getController(), source, sa);
exclude = CardLists.filter(exclude, new Predicate<Card>() {
@Override
public boolean apply(final Card c) {
return ComputerUtilCard.evaluateCreature(c) >= vehicleValue;
}
}); // exclude creatures >= vehicle
return ComputerUtil.chooseTapTypeAccumulatePower(ai, type, sa, true,
Integer.parseInt(totalP), exclude) != null;
}
return false;
}
}
return true;
}
/**
* Check sacrifice cost.
*
@@ -413,94 +394,38 @@ public class ComputerUtilCost {
* @return true, if successful
*/
public static boolean checkSacrificeCost(final Player ai, final Cost cost, final Card source, final SpellAbility sourceAbility) {
return checkSacrificeCost(ai, cost, source, sourceAbility, true);
}
public static boolean isSacrificeSelfCost(final Cost cost) {
if (cost == null) {
return false;
}
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostSacrifice && part.payCostFromSource()) {
return true;
}
}
return false;
return checkSacrificeCost(ai, cost, source, sourceAbility,true);
}
/**
* Check TapType cost.
* <p>
* shouldPayCost.
* </p>
*
* @param hostCard
* a {@link forge.game.card.Card} object.
* @param cost
* the cost
* @param source
* the source
* @return true, if successful
* @return a boolean.
*/
public static boolean checkTapTypeCost(final Player ai, final Cost cost, final Card source, final SpellAbility sa, final Collection<Card> alreadyTapped) {
if (cost == null) {
return true;
}
public static boolean shouldPayCost(final Player ai, final Card hostCard, final Cost cost) {
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostTapType) {
String type = part.getType();
/*
* Only crew with creatures weaker than vehicle
*
* Possible improvements:
* - block against evasive (flyers, intimidate, etc.)
* - break board stall by racing with evasive vehicle
*/
if (sa.isCrew()) {
Card vehicle = AnimateAi.becomeAnimated(source, sa);
final int vehicleValue = ComputerUtilCard.evaluateCreature(vehicle);
String totalP = type.split("withTotalPowerGE")[1];
type = TextUtil.fastReplace(type, TextUtil.concatNoSpace("+withTotalPowerGE", totalP), "");
CardCollection exclude = CardLists.getValidCards(ai.getCardsIn(ZoneType.Battlefield), type.split(";"), source.getController(), source, sa);
exclude = CardLists.filter(exclude, c -> ComputerUtilCard.evaluateCreature(c) >= vehicleValue); // exclude creatures >= vehicle
exclude.addAll(alreadyTapped);
CardCollection tappedCrew = ComputerUtil.chooseTapTypeAccumulatePower(ai, type, sa, true, Integer.parseInt(totalP), exclude);
if (tappedCrew != null) {
alreadyTapped.addAll(tappedCrew);
return true;
}
return false;
if (part instanceof CostPayLife) {
if (!ai.cantLoseForZeroOrLessLife()) {
continue;
}
// check if we have a valid card to tap (e.g. Jaspera Sentinel)
Integer c = part.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, part.getAmount(), sa);
final int remainingLife = ai.getLife();
final int lifeCost = ((CostPayLife) part).convertAmount();
if ((remainingLife - lifeCost) < 10) {
return false; //Don't pay life if it would put AI under 10 life
} else if ((remainingLife / lifeCost) < 4) {
return false; //Don't pay life if it is more than 25% of current life
}
CardCollection exclude = new CardCollection();
if (alreadyTapped != null) {
exclude.addAll(alreadyTapped);
}
// trying to produce mana that includes tapping source that will already be tapped
if (exclude.contains(source) && cost.hasTapCost()) {
return false;
}
// if we want to pay for an ability with tapping the source can't be chosen
if (sa.getPayCosts().hasTapCost()) {
exclude.add(sa.getHostCard());
}
CardCollection tapChoices = ComputerUtil.chooseTapType(ai, type, source, cost.hasTapCost(), c, exclude, sa);
if (tapChoices != null) {
if (alreadyTapped != null) {
alreadyTapped.addAll(tapChoices);
// if manasource gets tapped to produce it also can't help paying another
if (cost.hasTapCost()) {
alreadyTapped.add(source);
}
}
return true;
}
return false;
}
}
return true;
}
} // shouldPayCost()
/**
* <p>
@@ -513,103 +438,57 @@ public class ComputerUtilCost {
* a {@link forge.game.player.Player} object.
* @return a boolean.
*/
public static boolean canPayCost(final SpellAbility sa, final Player player, final boolean effect) {
return canPayCost(sa.getPayCosts(), sa, player, effect);
}
public static boolean canPayCost(final Cost cost, final SpellAbility sa, final Player player, final boolean effect) {
public static boolean canPayCost(final SpellAbility sa, final Player player) {
if (sa.getActivatingPlayer() == null) {
sa.setActivatingPlayer(player); // complaints on NPE had came before this line was added.
}
// Check for stuff like Nether Void
int extraManaNeeded = 0;
if (!effect) {
boolean cannotBeCountered = !sa.isCounterableBy(null);
if (sa instanceof Spell) {
for (Card c : player.getGame().getCardsIn(ZoneType.Battlefield)) {
final String snem = c.getSVar("AI_SpellsNeedExtraMana");
if (!StringUtils.isBlank(snem)) {
if (cannotBeCountered && c.getName().equals("Nether Void")) {
continue;
}
String[] parts = TextUtil.split(snem, ' ');
boolean meetsRestriction = parts.length == 1 || player.isValid(parts[1], c.getController(), c, sa);
if(!meetsRestriction)
continue;
if (StringUtils.isNumeric(parts[0])) {
extraManaNeeded += Integer.parseInt(parts[0]);
} else {
System.out.println("wrong SpellsNeedExtraMana SVar format on " + c);
}
}
}
for (Card c : player.getCardsIn(ZoneType.Command)) {
if (cannotBeCountered) {
if (sa instanceof Spell) {
final boolean cannotBeCountered = !CardFactoryUtil.isCounterable(sa.getHostCard());
for (Card c : player.getGame().getCardsIn(ZoneType.Battlefield)) {
final String snem = c.getSVar("AI_SpellsNeedExtraMana");
if (!StringUtils.isBlank(snem)) {
if (cannotBeCountered && c.getName().equals("Nether Void")) {
continue;
}
final String snem = c.getSVar("SpellsNeedExtraManaEffect");
if (!StringUtils.isBlank(snem)) {
if (StringUtils.isNumeric(snem)) {
extraManaNeeded += Integer.parseInt(snem);
} else {
System.out.println("wrong SpellsNeedExtraManaEffect SVar format on " + c);
}
String[] parts = TextUtil.split(snem, ' ');
boolean meetsRestriction = parts.length == 1 || player.isValid(parts[1], c.getController(), c, sa);
if(!meetsRestriction)
continue;
try {
extraManaNeeded += Integer.parseInt(snem);
} catch (final NumberFormatException e) {
System.out.println("wrong SpellsNeedExtraMana SVar format on " + c);
}
}
}
// Try not to lose Planeswalker if not threatened
if (sa.isPwAbility()) {
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostRemoveCounter) {
if (part.convertAmount() != null && part.convertAmount() == sa.getHostCard().getCurrentLoyalty()) {
// refuse to pay if opponent has no creature threats or
// 50% chance otherwise
if (player.getOpponents().getCreaturesInPlay().isEmpty()
|| MyRandom.getRandom().nextFloat() < .5f) {
return false;
}
}
for (Card c : player.getCardsIn(ZoneType.Command)) {
if (cannotBeCountered) {
continue;
}
final String snem = c.getSVar("SpellsNeedExtraManaEffect");
if (!StringUtils.isBlank(snem)) {
try {
extraManaNeeded += Integer.parseInt(snem);
} catch (final NumberFormatException e) {
System.out.println("wrong SpellsNeedExtraManaEffect SVar format on " + c);
}
}
}
}
// Account for possible Ward after the spell is fully targeted
// TODO: ideally, this should be done while targeting, so that a different target can be preferred if the best
// one is warded and can't be paid for. (currently it will be stuck with the target until it could pay)
if (!sa.isTrigger() && !cannotBeCountered) {
Set<GameObject> distinctObjects = Sets.newHashSet();
for (TargetChoices tc : sa.getAllTargetChoices()) {
for (Card tgt : tc.getTargetCards()) {
if (!distinctObjects.add(tgt)) {
continue;
}
// TODO some older cards don't use the keyword, so check for trigger instead
if (tgt.hasKeyword(Keyword.WARD) && tgt.isInPlay() && tgt.getController().isOpponentOf(sa.getHostCard().getController())) {
Cost wardCost = ComputerUtilCard.getTotalWardCost(tgt);
// don't use API converter since it might have special part logic not meant for Ward cost
SpellAbilityAi topAI = new SpellAbilityAi() {};
if (!topAI.willPayCosts(player, sa, wardCost, sa.getHostCard())) {
return false;
}
if (wardCost.hasManaCost()) {
extraManaNeeded += wardCost.getTotalMana().getCMC();
}
}
}
}
}
// Bail early on Casualty in case there are no cards that would make sense to pay with
if (sa.getHostCard().hasKeyword(Keyword.CASUALTY)) {
for (final CostPart part : cost.getCostParts()) {
if (part instanceof CostSacrifice) {
CardCollection valid = CardLists.getValidCards(player.getCardsIn(ZoneType.Battlefield), part.getType().split(";"),
sa.getActivatingPlayer(), sa.getHostCard(), sa);
valid = CardLists.filter(valid, CardPredicates.hasSVar("AIDontSacToCasualty").negate());
if (valid.isEmpty()) {
// Try not to lose Planeswalker if not threatened
if (sa.getRestrictions().isPwAbility()) {
for (final CostPart part : sa.getPayCosts().getCostParts()) {
if (part instanceof CostRemoveCounter) {
if (part.convertAmount() != null && part.convertAmount() == sa.getHostCard().getCurrentLoyalty()) {
// refuse to pay if opponent has no creature threats or
// 50% chance otherwise
if (player.getOpponents().getCreaturesInPlay().isEmpty()
|| MyRandom.getRandom().nextFloat() < .5f) {
return false;
}
}
@@ -617,16 +496,145 @@ public class ComputerUtilCost {
}
}
// TODO both of these call CostAdjustment.adjust, try to reuse instead
return ComputerUtilMana.canPayManaCost(cost, sa, player, extraManaNeeded, effect)
&& CostPayment.canPayAdditionalCosts(cost, sa, effect, player);
// KLD vehicle
if (sa.hasParam("Crew")) { // put under checkTapTypeCost?
for (final CostPart part : sa.getPayCosts().getCostParts()) {
if (part instanceof CostTapType && part.getType().contains("+withTotalPowerGE")) {
return new AiCostDecision(player, sa).visit((CostTapType)part) != null;
}
}
}
// TODO: Alternate costs which involve both paying mana and tapping a card, e.g. Zahid, Djinn of the Lamp
// Current AI decides on each part separately, thus making it possible for the AI to cheat by
// tapping a mana source for mana and for the tap cost at the same time. Until this is improved, AI
// will not consider mana sources valid for paying the tap cost to avoid this exact situation.
if ("DontPayTapCostWithManaSources".equals(sa.getHostCard().getSVar("AIPaymentPreference"))) {
for (final CostPart part : sa.getPayCosts().getCostParts()) {
if (part instanceof CostTapType) {
CardCollectionView nonManaSources =
CardLists.getValidCards(player.getCardsIn(ZoneType.Battlefield), part.getType().split(";"),
sa.getActivatingPlayer(), sa.getHostCard(), sa);
nonManaSources = CardLists.filter(nonManaSources, new Predicate<Card>() {
@Override
public boolean apply(Card card) {
boolean hasManaSa = false;
for (final SpellAbility sa : card.getSpellAbilities()) {
if (sa.isManaAbility() && sa.getPayCosts() != null && sa.getPayCosts().hasTapCost()) {
hasManaSa = true;
break;
}
}
return !hasManaSa;
}
});
if (nonManaSources.size() < part.convertAmount()) {
return false;
}
}
}
}
return ComputerUtilMana.canPayManaCost(sa, player, extraManaNeeded)
&& CostPayment.canPayAdditionalCosts(sa.getPayCosts(), sa);
} // canPayCost()
public static boolean willPayUnlessCost(SpellAbility sa, Player payer, Cost cost, boolean alreadyPaid, FCollectionView<Player> payers) {
final Card source = sa.getHostCard();
final String aiLogic = sa.getParam("UnlessAI");
boolean payForOwnOnly = "OnlyOwn".equals(aiLogic);
boolean payOwner = sa.hasParam("UnlessAI") ? aiLogic.startsWith("Defined") : false;
boolean payNever = "Never".equals(aiLogic);
boolean shockland = "Shockland".equals(aiLogic);
boolean isMine = sa.getActivatingPlayer().equals(payer);
if (payNever) { return false; }
if (payForOwnOnly && !isMine) { return false; }
if (payOwner) {
final String defined = aiLogic.substring(7);
final Player player = AbilityUtils.getDefinedPlayers(source, defined, sa).get(0);
if (!payer.equals(player)) {
return false;
}
} else if ("OnlyDontControl".equals(aiLogic)) {
if (sa.getHostCard() == null || payer.equals(sa.getHostCard().getController())) {
return false;
}
} else if (shockland) {
if (payer.getLife() > 3 && payer.canPayLife(2)) {
final int landsize = payer.getLandsInPlay().size() + 1;
for (Card c : payer.getCardsIn(ZoneType.Hand)) {
// if the new land size would equal the CMC of a card in AIs hand, consider playing it untapped,
// otherwise don't bother running other checks
if (landsize != c.getCMC()) {
continue;
}
// try to determine in the AI is actually planning to play a spell ability from the card
boolean willPlay = ComputerUtil.hasReasonToPlayCardThisTurn(payer, c);
// try to determine if the mana shards provided by the lands would be applicable to pay the mana cost
boolean canPay = c.getManaCost().canBePaidWithAvaliable(ColorSet.fromNames(getAvailableManaColors(payer, source)).getColor());
if (canPay && willPlay) {
return true;
}
}
}
return false;
} else if ("Paralyze".equals(aiLogic)) {
final Card c = source.getEnchantingCard();
if (c == null || c.isUntapped()) {
return false;
}
} else if ("MorePowerful".equals(aiLogic)) {
final int sourceCreatures = sa.getActivatingPlayer().getCreaturesInPlay().size();
final int payerCreatures = payer.getCreaturesInPlay().size();
if (payerCreatures > sourceCreatures + 1) {
return false;
}
} else if (aiLogic != null && aiLogic.startsWith("LifeLE")) {
// if payer can't lose life its no need to pay unless
if (!payer.canLoseLife())
return false;
else if (payer.getLife() <= Integer.valueOf(aiLogic.substring(6))) {
return true;
}
} else if ("WillAttack".equals(aiLogic)) {
AiAttackController aiAtk = new AiAttackController(payer);
Combat combat = new Combat(payer);
aiAtk.declareAttackers(combat);
if (combat.getAttackers().isEmpty()) {
return false;
}
} else if ("nonToken".equals(aiLogic) && AbilityUtils.getDefinedCards(source, sa.getParam("Defined"), sa).get(0).isToken()) {
return false;
} else if ("LowPriority".equals(aiLogic) && MyRandom.getRandom().nextInt(100) < 67) {
return false;
}
// AI will only pay when it's not already payed and only opponents abilities
if (alreadyPaid || (payers.size() > 1 && (isMine && !payForOwnOnly))) {
return false;
}
// AI was crashing because the blank ability used to pay costs
// Didn't have any of the data on the original SA to pay dependant costs
return checkLifeCost(payer, cost, source, 4, sa)
&& checkDamageCost(payer, cost, source, 4)
&& (isMine || checkSacrificeCost(payer, cost, source, sa))
&& (isMine || checkDiscardCost(payer, cost, source))
&& (!source.getName().equals("Tyrannize") || payer.getCardsIn(ZoneType.Hand).size() > 2)
&& (!source.getName().equals("Perplex") || payer.getCardsIn(ZoneType.Hand).size() < 2)
&& (!source.getName().equals("Breaking Point") || payer.getCreaturesInPlay().size() > 1)
&& (!source.getName().equals("Chain of Vapor") || (ComputerUtil.getOpponentFor(payer).getCreaturesInPlay().size() > 0 && payer.getLandsInPlay().size() > 3));
}
public static Set<String> getAvailableManaColors(Player ai, Card additionalLand) {
return getAvailableManaColors(ai, Lists.newArrayList(additionalLand));
}
public static Set<String> getAvailableManaColors(Player ai, List<Card> additionalLands) {
CardCollection cardsToConsider = CardLists.filter(ai.getCardsIn(ZoneType.Battlefield), CardPredicates.UNTAPPED);
CardCollection cardsToConsider = CardLists.filter(ai.getCardsIn(ZoneType.Battlefield), Presets.UNTAPPED);
Set<String> colorsAvailable = Sets.newHashSet();
if (additionalLands != null) {
@@ -654,71 +662,4 @@ public class ComputerUtilCost {
}
return false;
}
public static int getMaxXValue(SpellAbility sa, Player ai, final boolean effect) {
final Card source = sa.getHostCard();
SpellAbility root = sa.getRootAbility();
final Cost abCost = root.getPayCosts();
if (abCost == null || !abCost.hasXInAnyCostPart()) {
return 0;
}
Integer val = null;
if (root.costHasManaX()) {
val = ComputerUtilMana.determineLeftoverMana(root, ai, effect);
}
if (sa.usesTargeting()) {
// if announce is used as min targets, check what the max possible number would be
if ("X".equals(sa.getTargetRestrictions().getMinTargets())) {
val = ObjectUtils.min(val, CardUtil.getValidCardsToTarget(sa).size());
}
if (sa.hasParam("AIMaxTgtsCount")) {
// Cards that have confusing costs for the AI (e.g. Eliminate the Competition) can have forced max target constraints specified
// TODO: is there a better way to predict things like "sac X" costs without needing a special AI variable?
val = ObjectUtils.min(val, AbilityUtils.calculateAmount(source, "Count$" + sa.getParam("AIMaxTgtsCount"), sa));
}
}
val = ObjectUtils.min(val, abCost.getMaxForNonManaX(root, ai, effect));
if (val != null && val > 0) {
// filter cost parts for preferences, don't choose X > than possible preferences
for (final CostPart part : abCost.getCostParts()) {
if (part instanceof CostSacrifice) {
if (part.payCostFromSource()) {
continue;
}
if (!part.getAmount().equals("X")) {
continue;
}
final CardCollection typeList = CardLists.getValidCards(ai.getCardsIn(ZoneType.Battlefield), part.getType().split(";"), source.getController(), source, sa);
int count = 0;
while (count < val) {
Card prefCard = ComputerUtil.getCardPreference(ai, source, "SacCost", typeList);
if (prefCard == null) {
break;
}
typeList.remove(prefCard);
count++;
}
val = ObjectUtils.min(val, count);
}
}
}
return ObjectUtils.defaultIfNull(val, 0);
}
public static CardCollection paymentChoicesWithoutTargets(Iterable<Card> choices, SpellAbility source, Player ai) {
if (source.usesTargeting()) {
final CardCollectionView targets = source.getTargets().getTargetCards();
choices = IterableUtil.filter(choices, Predicate.not(CardPredicates.isController(ai).and(targets::contains)));
}
return new CardCollection(choices);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,23 +1,24 @@
package forge.ai;
import forge.game.GameEntity;
import com.google.common.base.Function;
import forge.game.ability.AbilityUtils;
import forge.game.ability.ApiType;
import forge.game.card.Card;
import forge.game.card.CounterEnumType;
import forge.game.card.CounterType;
import forge.game.cost.CostPayEnergy;
import forge.game.keyword.Keyword;
import forge.game.keyword.KeywordInterface;
import forge.game.spellability.SpellAbility;
import forge.game.staticability.StaticAbilityAssignCombatDamageAsUnblocked;
import forge.game.staticability.StaticAbilityCantAttackBlock;
import forge.game.staticability.StaticAbilityMustAttack;
import forge.game.trigger.Trigger;
import forge.game.trigger.TriggerType;
import java.util.List;
import java.util.function.Function;
public class CreatureEvaluator implements Function<Card, Integer> {
protected int getEffectivePower(final Card c) {
return c.getNetCombatDamage();
}
protected int getEffectiveToughness(final Card c) {
return c.getNetToughness();
}
@Override
public Integer apply(Card c) {
return evaluateCreature(c);
@@ -26,38 +27,32 @@ public class CreatureEvaluator implements Function<Card, Integer> {
public int evaluateCreature(final Card c) {
return evaluateCreature(c, true, true);
}
public int evaluateCreature(final Card c, final boolean considerPT, final boolean considerCMC) {
//Card shouldn't be null and AI shouldn't crash since this is just score
if (c == null)
return 0;
int value = 80;
if (!c.isToken()) {
value += addValue(20, "non-token"); // tokens should be worth less than actual cards
}
int power = c.getNetCombatDamage();
final int toughness = c.getNetToughness();
// TODO replace with ReplacementEffect checks
if (c.hasKeyword("Prevent all combat damage that would be dealt by CARDNAME.")
|| c.hasKeyword("Prevent all damage that would be dealt by CARDNAME.")
|| c.hasKeyword("Prevent all combat damage that would be dealt to and dealt by CARDNAME.")
|| c.hasKeyword("Prevent all damage that would be dealt to and dealt by CARDNAME.")) {
power = 0;
int power = getEffectivePower(c);
final int toughness = getEffectiveToughness(c);
for (KeywordInterface kw : c.getKeywords()) {
String keyword = kw.getOriginal();
if (keyword.equals("Prevent all combat damage that would be dealt by CARDNAME.")
|| keyword.equals("Prevent all damage that would be dealt by CARDNAME.")
|| keyword.equals("Prevent all combat damage that would be dealt to and dealt by CARDNAME.")
|| keyword.equals("Prevent all damage that would be dealt to and dealt by CARDNAME.")) {
power = 0;
break;
}
}
if (considerPT) {
value += addValue(power * 15, "power");
value += addValue(toughness * 10, "toughness: " + toughness);
// because backside is always stronger the potential makes it better than a single faced card
if (c.hasKeyword(Keyword.DAYBOUND) && c.isDoubleFaced()) {
value += addValue(power * 10, "transforming");
}
}
if (considerCMC) {
value += addValue(c.getCMC() * 5, "cmc");
}
// Evasion keywords
if (c.hasKeyword(Keyword.FLYING)) {
value += addValue(power * 10, "flying");
@@ -65,12 +60,10 @@ public class CreatureEvaluator implements Function<Card, Integer> {
if (c.hasKeyword(Keyword.HORSEMANSHIP)) {
value += addValue(power * 10, "horses");
}
if (StaticAbilityCantAttackBlock.cantBlockBy(c, null)) {
if (c.hasKeyword("Unblockable")) {
value += addValue(power * 10, "unblockable");
} else {
if (StaticAbilityAssignCombatDamageAsUnblocked.assignCombatDamageAsUnblocked(c)
|| StaticAbilityAssignCombatDamageAsUnblocked.assignCombatDamageAsUnblocked(c, false)) {
if (c.hasKeyword("You may have CARDNAME assign its combat damage as though it weren't blocked.")) {
value += addValue(power * 6, "thorns");
}
if (c.hasKeyword(Keyword.FEAR)) {
@@ -82,11 +75,11 @@ public class CreatureEvaluator implements Function<Card, Integer> {
if (c.hasKeyword(Keyword.MENACE)) {
value += addValue(power * 4, "menace");
}
if (c.hasKeyword(Keyword.SKULK)) {
value += addValue(power * 3, "skulk");
if (c.hasStartOfKeyword("CantBeBlockedBy")) {
value += addValue(power * 3, "block-restrict");
}
}
// Other good keywords
if (power > 0) {
if (c.hasKeyword(Keyword.DOUBLE_STRIKE)) {
@@ -106,29 +99,29 @@ public class CreatureEvaluator implements Function<Card, Integer> {
if (c.hasKeyword(Keyword.VIGILANCE)) {
value += addValue((power * 5) + (toughness * 5), "vigilance");
}
if (c.hasKeyword(Keyword.WITHER)) {
value += addValue(power * 10, "Wither");
}
if (c.hasKeyword(Keyword.INFECT)) {
value += addValue(power * 15, "infect");
}
else if (c.hasKeyword(Keyword.WITHER)) {
value += addValue(power * 10, "wither");
}
value += addValue(c.getKeywordMagnitude(Keyword.TOXIC) * 5, "toxic");
value += addValue(c.getKeywordMagnitude(Keyword.AFFLICT) * 5, "afflict");
value += addValue(c.getKeywordMagnitude(Keyword.RAMPAGE), "rampage");
value += addValue(c.getKeywordMagnitude(Keyword.AFFLICT) * 5, "afflict");
}
value += addValue(c.getKeywordMagnitude(Keyword.BUSHIDO) * 16, "bushido");
value += addValue(c.getAmountOfKeyword(Keyword.FLANKING) * 15, "flanking");
value += addValue(c.getAmountOfKeyword(Keyword.EXALTED) * 15, "exalted");
value += addValue(c.getKeywordMagnitude(Keyword.ANNIHILATOR) * 50, "eldrazi");
value += addValue(c.getKeywordMagnitude(Keyword.ABSORB) * 11, "absorb");
// Keywords that may produce temporary or permanent buffs over time
if (c.hasKeyword(Keyword.PROWESS)) {
value += addValue(5, "prowess");
}
if (c.hasKeyword(Keyword.OUTLAST)) {
value += addValue(10, "outlast");
}
value += addValue(c.getKeywordMagnitude(Keyword.BUSHIDO) * 16, "bushido");
value += addValue(c.getAmountOfKeyword(Keyword.FLANKING) * 15, "flanking");
value += addValue(c.getAmountOfKeyword(Keyword.EXALTED) * 15, "exalted");
value += addValue(c.getAmountOfKeyword(Keyword.MELEE) * 18, "melee");
value += addValue(c.getAmountOfKeyword(Keyword.PROWESS) * 5, "prowess");
// Defensive Keywords
if (c.hasKeyword(Keyword.REACH) && !c.hasKeyword(Keyword.FLYING)) {
@@ -137,12 +130,10 @@ public class CreatureEvaluator implements Function<Card, Integer> {
if (c.hasKeyword("CARDNAME can block creatures with shadow as though they didn't have shadow.")) {
value += addValue(3, "shadow-block");
}
// Protection
if (c.hasKeyword(Keyword.INDESTRUCTIBLE)) {
value += addValue(70, "darksteel");
} else {
value += addValue(20 * c.getCounters(CounterEnumType.SHIELD), "shielded");
}
if (c.hasKeyword("Prevent all damage that would be dealt to CARDNAME.")) {
value += addValue(60, "cho-manno");
@@ -153,131 +144,91 @@ public class CreatureEvaluator implements Function<Card, Integer> {
value += addValue(35, "hexproof");
} else if (c.hasKeyword(Keyword.SHROUD)) {
value += addValue(30, "shroud");
} else if (c.hasKeyword(Keyword.WARD)) {
value += addValue(10, "ward");
}
if (c.hasKeyword(Keyword.PROTECTION)) {
value += addValue(20, "protection");
}
// paired creatures are more valuable because they grant a bonus to the other creature
if (c.isPaired()) {
value += addValue(14, "paired");
}
if (c.hasEncodedCard()) {
value += addValue(24, "encoded");
}
if (ComputerUtilCard.hasActiveUndyingOrPersist(c)) {
value += addValue(30, "revive");
}
// Bad keywords
if (c.hasKeyword(Keyword.DEFENDER) || c.hasKeyword("CARDNAME can't attack.")) {
value -= subValue((power * 9) + 40, "defender");
} else if (c.getSVar("SacrificeEndCombat").equals("True")) {
value -= subValue(40, "sac-end");
}
if (c.hasKeyword("CARDNAME can't attack or block.")) {
value = addValue(50 + (c.getCMC() * 5), "useless"); // reset everything - useless
} else if (c.hasKeyword("CARDNAME can't block.")) {
if (c.hasKeyword("CARDNAME can't block.")) {
value -= subValue(10, "cant-block");
} else if (c.isGoaded()) {
value -= subValue(5, "goaded");
} else {
List<GameEntity> mAEnt = StaticAbilityMustAttack.entitiesMustAttack(c);
if (mAEnt.contains(c)) {
value -= subValue(10, "must-attack");
} else if (!mAEnt.isEmpty()) {
value -= subValue(10, "must-attack-player");
}/* else if (c.hasKeyword("CARDNAME can block only creatures with flying.")) {
} else if (c.hasKeyword("CARDNAME attacks each turn if able.")
|| c.hasKeyword("CARDNAME attacks each combat if able.")) {
value -= subValue(10, "must-attack");
} else if (c.hasStartOfKeyword("CARDNAME attacks specific player each combat if able")) {
value -= subValue(10, "must-attack-player");
} else if (c.hasKeyword("CARDNAME can block only creatures with flying.")) {
value -= subValue(toughness * 5, "reverse-reach");
}//*/
}
if (c.hasSVar("DestroyWhenDamaged")) {
value -= subValue((toughness - 1) * 9, "dies-to-dmg");
}
if (c.getSVar("Targeting").equals("Dies")) {
value -= subValue(25, "dies");
if (c.hasKeyword("CARDNAME can't attack or block.")) {
value = addValue(50 + (c.getCMC() * 5), "useless"); // reset everything - useless
}
if (c.isUntapped()) {
value += addValue(1, "untapped");
}
if (!c.canUntap(c.getController(), true)) {
if (c.hasKeyword("CARDNAME doesn't untap during your untap step.")) {
if (c.isTapped()) {
value = addValue(50 + (c.getCMC() * 5), "tapped-useless"); // reset everything - useless
} else {
value -= subValue(50, "doesnt-untap");
}
} else {
value -= subValue(10 * c.getCounters(CounterEnumType.STUN), "stunned");
}
if (c.hasSVar("EndOfTurnLeavePlay")) {
value -= subValue(50, "eot-leaves");
} else if (c.hasStartOfKeyword("Cumulative upkeep")) {
value -= subValue(30, "cupkeep");
} else if (c.hasStartOfKeyword("UpkeepCost")) {
value -= subValue(20, "sac-unless");
} else if (c.hasKeyword(Keyword.ECHO) && c.cameUnderControlSinceLastUpkeep()) {
value -= subValue(10, "echo-unpaid");
}
if (c.hasStartOfKeyword("At the beginning of your upkeep, CARDNAME deals")) {
value -= subValue(20, "upkeep-dmg");
}
if (c.hasKeyword(Keyword.FADING)) {
value -= subValue(20, "fading");
}
if (c.hasKeyword(Keyword.VANISHING)) {
value -= subValue(20, "vanishing");
}
if (c.getSVar("Targeting").equals("Dies")) {
value -= subValue(25, "dies");
}
for (final SpellAbility sa : c.getSpellAbilities()) {
if (sa.isAbility()) {
value += addValue(evaluateSpellAbility(sa), "sa: " + sa);
}
}
if (!c.getManaAbilities().isEmpty()) {
value += addValue(10, "manadork");
}
// use scaling because the creature is only available halfway
if (c.hasKeyword(Keyword.PHASING)) {
value -= subValue(Math.max(20, value / 2), "phasing");
if (c.isUntapped()) {
value += addValue(1, "untapped");
}
// paired creatures are more valuable because they grant a bonus to the other creature
if (c.isPaired()) {
value += addValue(14, "paired");
}
if (c.hasSVar("EndOfTurnLeavePlay")) {
value -= subValue(50, "eot-leaves");
} else {
for (Trigger t : c.getTriggers()) {
if (!TriggerType.Phase.equals(t.getMode())) {
continue;
}
if (!"Upkeep".equals(t.getParam("Phase"))) {
continue;
}
if (t.isKeyword(Keyword.CUMULATIVE_UPKEEP)) {
value -= subValue(30, "cupkeep");
} else if (t.isKeyword(Keyword.ECHO) && c.cameUnderControlSinceLastUpkeep()) {
value -= subValue(10, "echo-unpaid");
}
if (t.isKeyword(Keyword.FADING)) {
value -= subValue(20 / (Math.max(1, c.isInPlay() ? c.getCounters(CounterEnumType.FADE) : c.getKeywordMagnitude(Keyword.FADING))), "fading");
}
if (t.isKeyword(Keyword.VANISHING)) {
value -= subValue(20 / (Math.max(1, c.isInPlay() ? c.getCounters(CounterEnumType.TIME) : c.getKeywordMagnitude(Keyword.VANISHING))), "vanishing");
}
SpellAbility ab = t.ensureAbility();
if (ab == null) {
continue;
}
if (ApiType.DealDamage.equals(ab.getApi())) {
if (!"You".equals(ab.getParamOrDefault("Defined", "You"))) {
continue;
}
if (c.getController().canLoseLife()) {
value -= subValue(20, "upkeep-dmg");
}
} else if (ApiType.Sacrifice.equals(ab.getApi())) {
if (!ab.hasParam("UnlessCost")) {
continue;
}
value -= subValue(20, "sac-unless");
}
}
if (!c.getEncodedCards().isEmpty()) {
value += addValue(24, "encoded");
}
// card-specific evaluation modifier
if (c.hasSVar("AIEvaluationModifier")) {
value += AbilityUtils.calculateAmount(c, c.getSVar("AIEvaluationModifier"), null);
int mod = AbilityUtils.calculateAmount(c, c.getSVar("AIEvaluationModifier"), null);
value += mod;
}
return value;
@@ -291,11 +242,11 @@ public class CreatureEvaluator implements Function<Card, Integer> {
&& "+X".equals(sa.getParam("NumDef"))
&& !sa.usesTargeting()
&& (!sa.hasParam("Defined") || "Self".equals(sa.getParam("Defined")))) {
if (sa.getPayCosts().hasOnlySpecificCostType(CostPayEnergy.class)) {
if (sa.getPayCosts() != null && sa.getPayCosts().hasOnlySpecificCostType(CostPayEnergy.class)) {
// Electrostatic Pummeler, can be expanded for similar cards
int initPower = sa.getHostCard().getNetPower();
int initPower = getEffectivePower(sa.getHostCard());
int pumpedPower = initPower;
int energy = sa.getHostCard().getController().getCounters(CounterEnumType.ENERGY);
int energy = sa.getHostCard().getController().getCounters(CounterType.ENERGY);
if (energy > 0) {
int numActivations = energy / 3;
for (int i = 0; i < numActivations; i++) {
@@ -305,9 +256,8 @@ public class CreatureEvaluator implements Function<Card, Integer> {
}
}
}
} else if (ComputerUtilCost.isSacrificeSelfCost(sa.getPayCosts())) {
return -10; // can be sacrificed in response to ability or spell, thus, less prioritable
}
// default value
return 10;
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More